@maincode-ai/matilda-code 0.20.0 → 0.20.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/bundled/mainy/docs/features/headless.md +37 -0
  2. package/bundled/mainy/docs/features/mcp.md +3 -3
  3. package/chunks/{agent-N5H7ZVZN.js → agent-WQRHTEJK.js} +1 -1
  4. package/chunks/{agent-headless-LBLAX66M.js → agent-headless-VPF3VPXU.js} +1 -1
  5. package/chunks/{anthropicContentGenerator-DKMAJXYA.js → anthropicContentGenerator-ATLOKYPR.js} +1 -1
  6. package/chunks/chunk-3YLXGE6T.js +8 -0
  7. package/chunks/{chunk-TRM7SXZ5.js → chunk-A7VPKVYG.js} +1 -1
  8. package/chunks/{chunk-GTR4V2PV.js → chunk-DC7LAFZZ.js} +1 -1
  9. package/chunks/chunk-DORRYU7L.js +101 -0
  10. package/chunks/{chunk-KP6BLFQS.js → chunk-GIIMOLLN.js} +1 -1
  11. package/chunks/{chunk-RO6LKQPB.js → chunk-IGQPRDMV.js} +547 -544
  12. package/chunks/chunk-IMYUVCF7.js +27 -0
  13. package/chunks/{chunk-3KCDX6MY.js → chunk-ISW2QC5B.js} +1 -1
  14. package/chunks/chunk-OCXGNAAT.js +8 -0
  15. package/chunks/{chunk-QT4UNNZ4.js → chunk-QJO23A2D.js} +4 -4
  16. package/chunks/chunk-RGBIKCMN.js +95 -0
  17. package/chunks/{chunk-XXZH7C44.js → chunk-SS5WUOSJ.js} +1 -1
  18. package/chunks/chunk-XJDC3ZQZ.js +8 -0
  19. package/chunks/{chunk-Z7OHKQ7V.js → chunk-YZVC65QR.js} +2 -2
  20. package/chunks/{computer-use-LG4QQFMP.js → computer-use-3BJWOZSA.js} +1 -1
  21. package/chunks/contextCommand-SOQLJJIW.js +3 -0
  22. package/chunks/edit-ZIPLKFNT.js +38 -0
  23. package/chunks/{en-ZU6RPTEW.js → en-75JQMW7P.js} +1 -1
  24. package/chunks/{enter-worktree-OIP2B3NM.js → enter-worktree-MWQ3Z7HX.js} +1 -1
  25. package/chunks/enterPlanMode-XT6MNE2L.js +18 -0
  26. package/chunks/{exit-worktree-VN5I5XWV.js → exit-worktree-O7DBPVFA.js} +1 -1
  27. package/chunks/{exitPlanMode-HE6EEGTO.js → exitPlanMode-FDXKFQJF.js} +14 -14
  28. package/chunks/geminiContentGenerator-HXWUQ2DI.js +8 -0
  29. package/chunks/{glob-EGOAJNOQ.js → glob-GYLGTXYL.js} +1 -1
  30. package/chunks/{grep-JYHW6SSG.js → grep-ZNYUS2MU.js} +1 -1
  31. package/chunks/{matildaAgentContentGenerator-AKNRQW6A.js → matildaAgentContentGenerator-HG4ABAJG.js} +1 -1
  32. package/chunks/matildaContentGenerator-WEAUMFNT.js +8 -0
  33. package/chunks/matildaOAuth2-LKOMJUC6.js +3 -0
  34. package/chunks/{monitor-IDNOTNUP.js → monitor-755GJUC4.js} +1 -1
  35. package/chunks/{notebook-edit-4VBYBZFJ.js → notebook-edit-SWCJ3FMF.js} +1 -1
  36. package/chunks/{openaiContentGenerator-WTRQK5RJ.js → openaiContentGenerator-JIODOCNJ.js} +1 -1
  37. package/chunks/ripGrep-5GE6ECVF.js +3 -0
  38. package/chunks/{scheduler-AOKJEAXJ.js → scheduler-VA6HAYT4.js} +1 -1
  39. package/chunks/{serve-2JJY265V.js → serve-TVYEQNS6.js} +2 -2
  40. package/chunks/shell-JNZXS437.js +3 -0
  41. package/chunks/src-MMNXN6E3.js +3 -0
  42. package/chunks/{team-create-Z6636NPD.js → team-create-CUBBNHIF.js} +1 -1
  43. package/chunks/{update-goal-DH2TEYYU.js → update-goal-6WDBMJ2I.js} +1 -1
  44. package/chunks/{web-fetch-5F7C7MXU.js → web-fetch-QP42GV23.js} +1 -1
  45. package/chunks/{web-search-W2FYCGK5.js → web-search-FURCBRRK.js} +1 -1
  46. package/chunks/{workflow-M7KXXDO6.js → workflow-WRWIXJCG.js} +2 -2
  47. package/chunks/write-file-7BFZXGIJ.js +11 -0
  48. package/cli.js +476 -462
  49. package/locales/en.js +6 -0
  50. package/package.json +2 -2
  51. package/chunks/chunk-7VGUNT5L.js +0 -8
  52. package/chunks/chunk-CLUEFPSU.js +0 -8
  53. package/chunks/chunk-CYTN3WRM.js +0 -101
  54. package/chunks/chunk-IB7TWUWM.js +0 -90
  55. package/chunks/chunk-LLQVLTPB.js +0 -27
  56. package/chunks/contextCommand-7KHYFQ6G.js +0 -3
  57. package/chunks/edit-U4PMKZYZ.js +0 -38
  58. package/chunks/enterPlanMode-6LZSSWFT.js +0 -17
  59. package/chunks/geminiContentGenerator-GWGLIDJJ.js +0 -8
  60. package/chunks/matildaContentGenerator-MXP3V2UQ.js +0 -8
  61. package/chunks/matildaOAuth2-2IUZAZEO.js +0 -3
  62. package/chunks/ripGrep-DOB57AMM.js +0 -3
  63. package/chunks/shell-WFONAKPV.js +0 -3
  64. package/chunks/src-IHYMMU26.js +0 -3
  65. package/chunks/write-file-O4DJX4LP.js +0 -11
@@ -0,0 +1,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-XKDGRW3K.js";import{c as Q}from"./chunk-ESSYHTAZ.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-IOCF4XSR.js";import{L as S,Y as I}from"./chunk-QWBNNEV2.js";import{b as M}from"./chunk-GZPNIYVZ.js";M();import ie from"crypto";import q from"node:path";import{promises as b}from"node:fs";import{EventEmitter as De}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as ue}from"node:util";import{platform as he}from"node:os";import{resolve as Z}from"node:path";import{URL as me,fileURLToPath as fe}from"node:url";var ee=ue(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new me(i)}catch{throw new Error(`Invalid URL: ${i}`)}let o=e?["http:","https:","file:"]:["http:","https:"];if(!o.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${o.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(fe(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(i))throw new Error("URL contains invalid characters")}async function te(i,e={}){pe(i,e);let r=he(),t,o,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:we(n,i);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${ge(l)}. Falling back to the platform browser opener.`)}if(!N({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${i}`);return}switch(r){case"darwin":t="open",o=[i];break;case"win32":t="powershell.exe",o=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${i.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",o=[i];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,o,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[i]):await ee(d,[i],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${i}`);return}}async function re(i,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,o)=>{let n=de(i,e,r),s=!1;n.once("error",c=>{s||(s=!0,o(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function ge(i){return i instanceof Error?i.message:String(i)}function we(i,e){if(!i)return;let r=Ee(i);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(Y(r.command))return;let t=!1,o=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||o.push(e),{command:r.command,args:o}}function Ee(i){let e=[],r="",t;for(let s of i){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[o,...n]=e;if(o)return{command:o,args:n}}function Ve(){return N()}M();import H from"node:path";import{promises as y,unlinkSync as ke}from"node:fs";import{randomUUID as ne}from"node:crypto";var R=I("MATILDA_OAUTH"),_e="oauth_creds.json",Ce="oauth_creds.lock",ve=30*1e3,ye=35e3,Te=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var u=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function Re(i){if(!i||typeof i!="object")throw new Error("Invalid credentials format");let e=i,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var D=class i{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return i.instance||(i.instance=new i),i.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();ke(e)}catch{}},process.on("exit",this.cleanupFunction),process.on("SIGINT",this.cleanupFunction),process.on("SIGTERM",this.cleanupFunction),process.on("uncaughtException",this.cleanupFunction),process.on("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof u?t:new u("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<Te)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let o;return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),new Promise((n,s)=>{o=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new u("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),o=(await y.stat(r)).mtimeMs;o>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=o,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new u("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),o=JSON.parse(t),n=Re(o),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&R.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),o=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new u("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&R.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&R.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new u("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new u("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof P?(R.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new u("REFRESH_FAILED",s.message,s)):s instanceof u?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new u("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new u("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(o)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=H.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let o=JSON.stringify(e,null,2);try{await X(r,o,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ve}getCredentialFilePath(){return H.join(S.getGlobalMatildaDir(),_e)}getLockFilePath(){return H.join(S.getGlobalMatildaDir(),Ce)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:o}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>ye){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),R.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){R.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){R.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,o)}else throw new u("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new u("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&R.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),process.removeListener("SIGINT",this.cleanupFunction),process.removeListener("SIGTERM",this.cleanupFunction),process.removeListener("uncaughtException",this.cleanupFunction),process.removeListener("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var h=I("MATILDA_OAUTH"),J="https://chat.matilda.ai",Ae=`${J}/api/v1/oauth2/device/code`,j=`${J}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Fe=3e4,Se="oauth_creds.json";function Pe(){return ie.randomBytes(32).toString("base64url")}function xe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function Oe(){let i=Pe(),e=xe(i);return{code_verifier:i,code_challenge:e}}function B(i){return Object.keys(i).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&")}function W(i,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${U(i,{url:j})}`,{cause:i})}var P=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},K=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function V(i){return"device_code"in i}function Ie(i){return"access_token"in i&&i.access_token!==null&&i.access_token!==void 0&&typeof i.access_token=="string"&&i.access_token.length>0}function Le(i){return"status"in i&&i.status==="pending"}function L(i){return"error"in i}var G=class{credentials={};sharedManager;constructor(){this.sharedManager=D.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return h.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},o=await fetch(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let s=await o.text();throw new Error(`Device authorization failed: ${o.status} ${o.statusText}. Response: ${s}`)}let n=await o.json();if(V(n))h.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;h.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!V(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:be,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let n=await o.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${o.status} ${o.statusText}. Response: ${n}`);throw l.status=o.status,l}if(o.status===400&&s.error==="authorization_pending")return{status:"pending"};if(o.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new K({oauthError:s.error,description:s.error_description,status:o.status})}return await o.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Fe});h.debug("Refreshing access token...");try{let o;try{o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(e),signal:r})}catch(a){throw W(a,r.aborted)}if(!o.ok){let a;try{a=await o.text()}catch(d){throw W(d,r.aborted)}throw o.status===400||o.status===401?(await ae(),new P("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:o.status,response:a})):new Error(`Token refresh failed: ${o.status} ${o.statusText}. Response: ${a}`)}let n;try{n=await o.text()}catch(a){throw W(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},$e=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))($e||{}),F=new De;async function wr(i,e){let r=new G,t=D.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof u)switch(o.type){case"NO_REFRESH_TOKEN":h.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":h.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":h.warn("Network error during token refresh, trying device flow");break;default:h.warn("Token manager error:",o.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await Ue(r,i);if(!n.success){n.reason==="timeout"&&F.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ne(i){let e="Legacy OAuth Device Authorization",r=i,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(f,T)=>{if(f.startsWith("http://")||f.startsWith("https://")){let v=[];for(let O=0;O<f.length;O+=T)v.push(f.substring(O,O+T));return v}let A=f.split(" "),C=[],_="";for(let v of A)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",E="|"+" ".repeat(n-2)+"|",x="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),m=c(r,s),k="Waiting for authorization to complete...";process.stderr.write(`
4
+ `+w+`
5
+ `),process.stderr.write(E+`
6
+ `);for(let f of g)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
7
+ `);process.stderr.write(E+`
8
+ `);for(let f of m)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
9
+ `);process.stderr.write(E+`
10
+ `),process.stderr.write("| "+k+" ".repeat(s-k.length)+` |
11
+ `),process.stderr.write(E+`
12
+ `),process.stderr.write(x+`
13
+
14
+ `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};F.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return h.debug(`
15
+ `+c),F.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{F.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);h.warn(`Failed to open browser automatically: ${a}`),h.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=Oe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let E=a;throw new Error(`Device authorization failed: ${E?.error||"Unknown error"} - ${E?.error_description||"No details provided"}`)}F.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ne(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),h.debug(`Waiting for authorization...
16
+ `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let E=0;E<p;E++){let x=o();if(x)return x;try{h.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let m=g,k={access_token:m.access_token,refresh_token:m.refresh_token||void 0,token_type:m.token_type,resource_url:m.resource_url,expiry_date:m.expires_in?Date.now()+m.expires_in*1e3:void 0};return i.setCredentials(k),await He(k),n("success","Authentication successful! Access token obtained."),h.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),h.debug(`
17
+ Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${E+1}/${p})`),await new Promise(f=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),f();return}if(A>=d){clearInterval(C),f();return}},100)});let k=o();if(k)return k;continue}if(L(g)){let m=g;throw new Error(`Token polling failed: ${m?.error||"Unknown error"} - ${m?.error_description||"No details provided"}`)}}catch(g){let m=g instanceof Error?g.message:String(g),k=g instanceof Error?g.status:null,f=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(m.includes("Failed to cache credentials"))return f("error",m);if(m.includes("401")||k===401)return f("error","Device code expired or invalid, please restart the authorization process.");if(m.includes("429")||k===429)return f("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let A=`Error polling for token: ${m}`;n("error",A),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${U(c,{url:J})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{F.off("auth-cancel",t)}}var $=384;async function He(i,e){let r=ce();try{await b.mkdir(q.dirname(r),{recursive:!0});let t=JSON.stringify(i,null,2),o=`${r}.tmp.${process.pid}.${se()}`;try{await b.writeFile(o,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await b.chmod(o,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);h.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${o} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await b.rename(o,r)}catch(n){try{await b.unlink(o)}catch{}throw n}try{D.getInstance().clearCache()}catch(n){h.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let o=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${q.dirname(r)}\` and writing to \`${r}\`. ${o}. Please check permissions.`)}}async function ae(){try{let i=ce();await b.unlink(i),h.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;h.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{D.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var Er=ae;export{te as a,Ve as b,D as c,Pe as d,xe as e,Oe as f,P as g,K as h,V as i,Ie as j,Le as k,L as l,G as m,$e as n,F as o,wr as p,$ as q,He as r,ae as s,Er as t};
18
+ /**
19
+ * @license
20
+ * Copyright 2025 Google LLC
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+ /**
24
+ * @license
25
+ * Copyright 2025 Matilda
26
+ * SPDX-License-Identifier: Apache-2.0
27
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{s as d}from"./chunk-XYA3SFGC.js";import{c as s}from"./chunk-CLUEFPSU.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();var u=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],p=new Set([...u,...s]),E=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",a="(?:0|[1-9]\\d{0,4})",c="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",f=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${a}$`),new RegExp(`^${o}-maincode\\.${c}(?:\\.${a})?$`)],l=41;function R(e){return e==="desktop"?"desktop":e===void 0||E.has(e)?"code_cli":"unknown"}function m(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function _(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>l||!f.some(n=>n.test(t))))return t}function C(e,t=process.platform){let n=R(e.getChannel?.()),r=_(e.getCliVersion?.());return{"x-matilda-reported-surface":n,"x-matilda-reported-os":m(t),"x-matilda-reported-process":n==="desktop"?"matilda-desktop":n==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":"matilda-client",...r?{"x-matilda-reported-version":r}:{}}}function O(e){return p.has(e.toLowerCase())}function g(e){let t=e??d;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function w(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&g(e.baseUrl)}export{C as a,O as b,w as c};
3
+ import{s as d}from"./chunk-XYA3SFGC.js";import{d as s}from"./chunk-XJDC3ZQZ.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();var u=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],p=new Set([...u,...s]),E=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",a="(?:0|[1-9]\\d{0,4})",c="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",f=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${a}$`),new RegExp(`^${o}-maincode\\.${c}(?:\\.${a})?$`)],l=41;function R(e){return e==="desktop"?"desktop":e===void 0||E.has(e)?"code_cli":"unknown"}function m(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function _(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>l||!f.some(n=>n.test(t))))return t}function C(e,t=process.platform){let n=R(e.getChannel?.()),r=_(e.getCliVersion?.());return{"x-matilda-reported-surface":n,"x-matilda-reported-os":m(t),"x-matilda-reported-process":n==="desktop"?"matilda-desktop":n==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":"matilda-client",...r?{"x-matilda-reported-version":r}:{}}}function O(e){return p.has(e.toLowerCase())}function g(e){let t=e??d;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function w(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&g(e.baseUrl)}export{C as a,O as b,w as c};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Matilda Team
@@ -0,0 +1,8 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{w as n}from"./chunk-UY2R3ZQ4.js";import{b as e}from"./chunk-GZPNIYVZ.js";e();import a from"node:path";function g(r,i){if(r.getApprovalMode()!=="bogan")return null;let o=a.resolve(i),s=r.getProjectRoot?.()??r.getTargetDir();if(n(o,s))return null;let t=r.getWorkspaceContext?.();if(!t||t.isPathWithinWorkspace(o))return null;let p=t.getDirectories?.()??[r.getTargetDir()];return`Refusing out-of-workspace write in BOGAN mode: ${o}. Workspace root(s): ${p.join(", ")}. This blocks path typos (e.g. writing under $HOME when the project is elsewhere). Use --include-directories to add extra roots, or a non-BOGAN approval mode for intentional external writes.`}export{g as a};
4
+ /**
5
+ * @license
6
+ * Copyright 2025 Matilda Team
7
+ * SPDX-License-Identifier: Apache-2.0
8
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as rs}from"./chunk-QCIDUZV6.js";import{a as es,b as ts,c as qt}from"./chunk-3KCDX6MY.js";import{a as ns}from"./chunk-GTR4V2PV.js";import{c as yr,f as ve}from"./chunk-S4K76QPI.js";import{a as qn,b as ot,c as Xn,x as Qn}from"./chunk-CYTN3WRM.js";import{a as Zr,e as Jn,j as Vn,o as Kn,q as zn,s as Yn,t as hr}from"./chunk-XYA3SFGC.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{a as gr,b as _r,e as Zn,m as br}from"./chunk-CLUEFPSU.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Xt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Jt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var y=class extends Error{},$=class n extends y{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:Jt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var fo=/^[a-z][a-z0-9+.-]*:/i,ss=n=>fo.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function os(n){return typeof n!="object"?{}:n??{}}function is(n){if(!n)return!0;for(let e in n)return!1;return!0}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ls=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var cs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var ds=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function po(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var mo=()=>{let n=po();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":us(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ho();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ho(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var us=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),ps,ms=()=>ps??(ps=mo());a();function hs(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function nn(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Cr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var _s=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var wr="RFC3986",on=n=>String(n),Ar={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var xr=(n,e)=>(xr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xr(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,bs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=ln){let u=o.length>=ln?o.slice(l,l+ln):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===an&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function ys(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ws={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},As=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Cs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bs,encodeValuesOnly:!1,format:wr,formatter:on,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function bo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function xs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,X=!1;for(;(U=U.get(un))!==void 0&&!X;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");X=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(bo(w)||ys(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Qr=p&&l?M.replace(/\./g,"%2E"):M,co=W(w)?typeof t=="function"?t(j,Qr):j:j+(p?"."+Qr:"["+Qr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),As(H,xs(Gn,co,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function yo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=wr;if(typeof n.format<"u"){if(!xr(Ar,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Ar[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ws?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function fn(n,e={}){let t=n,r=yo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ws[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||As(i,xs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function Rs(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Is;function gt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}var Ps;function pn(n){let e;return(Ps??(e=new globalThis.TextDecoder,Ps=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),A(this,J,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,J,Rs([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=wo(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,J,"f").subarray(0,c(this,V,"f")-1))),A(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,J,"f").subarray(0,o));r.push(i),A(this,J,c(this,J,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
3
+ import{a as ns}from"./chunk-QCIDUZV6.js";import{a as ts,b as rs,c as qt}from"./chunk-ISW2QC5B.js";import{c as yr,f as ve}from"./chunk-S4K76QPI.js";import{a as qn,b as ot,c as Xn,x as Zn}from"./chunk-DORRYU7L.js";import{a as Yn}from"./chunk-DC7LAFZZ.js";import{a as Zr,e as Jn,j as Vn,o as Kn,q as zn,s as Qn,t as hr}from"./chunk-XYA3SFGC.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as es,n as br}from"./chunk-XJDC3ZQZ.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Xt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Jt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var y=class extends Error{},$=class n extends y{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:Jt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var fo=/^[a-z][a-z0-9+.-]*:/i,ss=n=>fo.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function os(n){return typeof n!="object"?{}:n??{}}function is(n){if(!n)return!0;for(let e in n)return!1;return!0}function as(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ls=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var cs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var ds=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function po(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var mo=()=>{let n=po();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(Deno.build.os),"X-Stainless-Arch":us(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ho();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ho(){if(typeof navigator>"u"||!navigator)return null;let n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var us=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",fs=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),ps,ms=()=>ps??(ps=mo());a();function hs(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function nn(...n){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Cr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(n){if(n[Symbol.asyncIterator])return n;let e=n.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function gs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var _s=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var wr="RFC3986",on=n=>String(n),Ar={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var xr=(n,e)=>(xr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),xr(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,bs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=ln){let u=o.length>=ln?o.slice(l,l+ln):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===an&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function ys(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ws={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},As=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Cs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:bs,encodeValuesOnly:!1,format:wr,formatter:on,indices:!1,serializeDate(n){return(Cs??(Cs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function bo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function xs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,X=!1;for(;(U=U.get(un))!==void 0&&!X;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");X=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(bo(w)||ys(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Qr=p&&l?M.replace(/\./g,"%2E"):M,co=W(w)?typeof t=="function"?t(j,Qr):j:j+(p?"."+Qr:"["+Qr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),As(H,xs(Gn,co,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function yo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=wr;if(typeof n.format<"u"){if(!xr(Ar,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=Ar[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ws?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function fn(n,e={}){let t=n,r=yo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ws[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||As(i,xs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function Rs(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var Is;function gt(n){let e;return(Is??(e=new globalThis.TextEncoder,Is=e.encode.bind(e)))(n)}var Ps;function pn(n){let e;return(Ps??(e=new globalThis.TextDecoder,Ps=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),A(this,J,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,J,Rs([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=wo(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,J,"f").subarray(0,c(this,V,"f")-1))),A(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,J,"f").subarray(0,o));r.push(i),A(this,J,c(this,J,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
4
4
  `):[]}};J=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
5
5
  `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function wo(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Os(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Pr={off:0,error:200,warn:300,info:400,debug:500},dn=(n,e,t)=>{if(n){if(as(Pr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Pr))}`)}};function Kt(){}function Ir(n,e,t){return!e||Pr[n]>Pr[t]?Kt:e[n].bind(e)}var Ao={error:Kt,warn:Kt,info:Kt,debug:Kt},Ss=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Ao;let r=Ss.get(e);if(r&&r[0]===t)return r[1];let s={error:Ir("error",e,t),warn:Ir("warn",e,t),info:Ir("info",e,t),debug:Ir("debug",e,t)};return Ss.set(e,[t,s]),s}var le=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var zt,re=class n{constructor(e,t,r){this.iterator=e,zt.set(this,void 0),this.controller=t,A(this,zt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of xo(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let d;try{d=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(d&&d.error)throw new $(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Xt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new Te,u=sn(e);for await(let d of u)for(let g of l.decode(d))yield g;for(let d of l.flush())yield d}async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Xt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(zt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,zt,"f")),new n(()=>s(t),this.controller,c(this,zt,"f"))]}toReadableStream(){let e=this,t;return nn({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=gt(JSON.stringify(s)+`
6
6
  `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*xo(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new mn,r=new Te,s=sn(n.body);for await(let o of Io(s))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Io(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?gt(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=Os(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var mn=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
@@ -22,15 +22,15 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
22
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
23
23
 
24
24
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
25
- `);this.baseURL=l.baseURL,this.timeout=l.timeout??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??hs(),A(this,Vr,_s,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",no).call(this)&&r||this.baseURL,o=ss(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return is(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Jt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Xt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await gs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Jt(E).message),S=cs(U),X=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,X,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Qt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ls("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Cr(e)}:c(this,Vr,"f").call(this,{body:e,headers:r})}};Un=I,Vr=new WeakMap,Fn=new WeakSet,no=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=Er;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=Ke;I.Audio=se;I.Moderations=Ye;I.Models=ze;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Qe;I.Beta=ie;I.Batches=Le;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Pi(n){return n.toLowerCase().includes("matilda3")}function Ri(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var F=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))Zn(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=Pi(e.model)?s.messages.map(Ri):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=zn(e.model,"output"),s=Kn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Ht=class extends F{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var Oi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Oi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))!ts(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,es(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Yn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br();if(!b&&Object.keys(f).length===0)return l(d,g);p.delete(gr),p.delete(_r);for(let[C,P]of Object.entries(f))p.set(C,P);let x=p.get("x-stainless-retry-count");return p.has(gr)&&x!==null&&/^[1-9][0-9]*$/.test(x)&&p.set(_r,"retry"),l(d,{...g,headers:p})}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,d)=>!(d===s&&s!==-1||d===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Kr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Si(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Si;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?vi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Ei(i);return Kr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Ei(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
25
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??hs(),A(this,Vr,_s,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",no).call(this)&&r||this.baseURL,o=ss(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return is(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new ke(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Jt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Xt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await gs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Jt(E).message),S=cs(U),X=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,X,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Qt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ls("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ms(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Cr(e)}:c(this,Vr,"f").call(this,{body:e,headers:r})}};Un=I,Vr=new WeakMap,Fn=new WeakSet,no=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=Er;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=Ke;I.Audio=se;I.Moderations=Ye;I.Models=ze;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Qe;I.Beta=ie;I.Batches=Le;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Pi(n){return n.toLowerCase().includes("matilda3")}function Ri(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var F=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))es(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=Pi(e.model)?s.messages.map(Ri):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=zn(e.model,"output"),s=Kn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Ht=class extends F{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var Oi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Oi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))!rs(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,ts(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Qn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br();if(!b&&Object.keys(f).length===0)return l(d,g);p.delete(gr),p.delete(_r);for(let[C,P]of Object.entries(f))p.set(C,P);let x=p.get("x-stainless-retry-count");return p.has(gr)&&x!==null&&/^[1-9][0-9]*$/.test(x)&&p.set(_r,"retry"),l(d,{...g,headers:p})}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,d)=>!(d===s&&s!==-1||d===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Kr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Si(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Si;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?vi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Ei(i);return Kr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Ei(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
26
26
 
27
27
  `);return{...n,content:t}}function vi(n){let e=n,t=e.reasoning,r=t?.effort;if(typeof r!="string"||!r)return n;let s={...e};if(typeof s.reasoning_effort!="string"||!s.reasoning_effort){let o=r;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),s.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete s.reasoning;else if(t){let{effort:o,...i}=t;s.reasoning=i}return s}a();var et=class extends F{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};a();var Ti=["api.minimaxi.com","api.minimax.io"],ki=[".minimaxi.com",".minimax.io"],tt=class extends F{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return Ti.includes(t)?!0:ki.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var so="api.mistral.ai",Mi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function $i(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===so||t.endsWith(`.${so}`)}catch{return!1}}function Ni(n){if($i(n))return!0;let e=n.model?.toLowerCase()??"";return Mi.some(t=>e.includes(t))}var rt=class extends F{static isMistralProvider=Ni;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Li)}}};function Li(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Fi(n){let e=n.baseUrl??"";if(e)try{let r=new URL(e).hostname.toLowerCase();if(r==="xiaomimimo.com"||r.endsWith(".xiaomimimo.com"))return!0}catch{}return(n.model??"").toLowerCase().startsWith("mimo-")}var nt=class extends F{constructor(e,t){super(e,t)}static isMiMoProvider=Fi;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Kr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var Ui=me("STREAMING_TOOL_CALL_PARSER"),zr=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,r,s){let o=e,i=!!(r&&this.idToIndexMap.has(r));if(r)if(this.idToIndexMap.has(r))o=this.idToIndexMap.get(r);else{if(this.buffers.has(e)){let P=this.buffers.get(e),O=this.depths.get(e),w=this.toolCallMeta.get(e);if(P.trim()&&O===0&&w?.id&&w.id!==r)try{JSON.parse(P),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let P=this.buffers.get(e);if(this.depths.get(e)>0||!P.trim())o=e;else try{JSON.parse(P),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let l=this.buffers.get(o),u=this.depths.get(o);if(i&&l.trim()&&u===0)try{return JSON.parse(l),Ui.debug(`Ignoring replay chunk for completed toolCall id=${r}`),{complete:!1}}catch{}let d=this.toolCallMeta.get(o);r&&(d.id=r),s&&(d.name=s);let g=this.inStrings.get(o),p=this.escapes.get(o),b=l+t;this.buffers.set(o,b);let f=u,x=g,C=p;for(let P of t)x||(P==="{"||P==="["?f++:(P==="}"||P==="]")&&f--),P==='"'&&!C&&(x=!x),C=P==="\\"&&!C;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,C),f===0&&b.trim().length>0)try{return{complete:!0,value:JSON.parse(b)}}catch(P){if(x)try{return{complete:!0,value:JSON.parse(b+'"'),repaired:!0}}catch{}return{complete:!1,error:P instanceof Error?P:new Error(String(P))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[],t=new Set;for(let[r,s]of this.buffers.entries()){let o=this.toolCallMeta.get(r);if(o?.name&&s.trim()){if(o.id){if(t.has(o.id))continue;t.add(o.id)}let i={};try{i=JSON.parse(s)}catch{if(this.inStrings.get(r))try{i=JSON.parse(s+'"')}catch{i=Zr(s,{})}else i=Zr(s,{})}e.push({id:o.id,name:o.name,args:i,index:r})}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),r=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!r?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,r]of this.buffers.entries()){let s=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(s>0||!r.trim()))e=Math.max(e,t);else if(r.trim())try{JSON.parse(r)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e]of this.buffers.entries()){if(!this.toolCallMeta.get(e)?.name)continue;let r=this.depths.get(e)||0,s=this.inStrings.get(e)||!1;if(r>0||s)return!0}return!1}};var oo=16e3,io=`[Earlier content omitted to fit Matilda Core external API limits]
28
- `,Yr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ot.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Yr(g)}let u=ot.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Yr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Hn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=ot.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await ot.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,fr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile;if(e==="matilda-core")return!0;if(e==="matilda-code")return!1;let t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(t.endsWith("/api/v1/code"))return!1;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
28
+ `,Yr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ot.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?en(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Yr(g)}let u=ot.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Yr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Hn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=ot.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await ot.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,fr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
29
29
  `):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=oo)return r;let s=oo-io.length;return`${io}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let d=r?.[l],g=u?e.config?.[u]:void 0,p=u?t[u]:void 0;return d!==void 0?d:g!==void 0?g:p},o=(l,u,d)=>{let g=s(u,d);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Xn.getStore()?.(i),Jn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(ve(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new zr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new qn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Di=me("OPENAI_ERROR"),dr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=ve(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Di.error("OpenAI API Error:",i),o?new Error(`${i}
30
30
 
31
31
  ${this.getTimeoutTroubleshootingTips()}`):s}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e?.code,s=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||r==="ETIMEDOUT"||r==="ESOCKETTIMEDOUT"||s==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,r){let s=Math.round((Date.now()-t.startTime)/1e3);return r?`Request timeout after ${s}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
32
32
  ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
33
- `)}`}};var ao=me("OPENAI"),st=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(Wn(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new rs().calculateTokens(e)).totalTokens}}catch(t){ao.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=ve(r);throw ao.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var mr=class extends st{contentGeneratorConfig;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e}shouldSuppressErrorLogging(e,t){return lo(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.withTokenRefresh(()=>super.generateContentStream(e,t))}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t=await Qn({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh});t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[ns]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!lo(t))throw t;return await this.applyValidToken({forceRefresh:!0}),await e()}}};function lo(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function l_(n,e){let t=ji(n,e);return ae.isMatildaCompatibleProvider(n)?new mr(n,e,t):new st(n,e,t)}function ji(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new F(n,e)}export{ae as a,Ze as b,et as c,tt as d,rt as e,nt as f,pr as g,dr as h,st as i,mr as j,l_ as k,ji as l};
33
+ `)}`}};var ao=me("OPENAI"),st=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(Wn(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new ns().calculateTokens(e)).totalTokens}}catch(t){ao.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=ve(r);throw ao.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var mr=class extends st{contentGeneratorConfig;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e}shouldSuppressErrorLogging(e,t){return lo(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.withTokenRefresh(()=>super.generateContentStream(e,t))}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t=await Zn({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh});t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[Yn]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!lo(t))throw t;return await this.applyValidToken({forceRefresh:!0}),await e()}}};function lo(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function l_(n,e){let t=ji(n,e);return ae.isMatildaCompatibleProvider(n)?new mr(n,e,t):new st(n,e,t)}function ji(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):Ze.isDeepSeekProvider(t)?new Ze(n,e):nt.isMiMoProvider(t)?new nt(n,e):et.isOpenRouterProvider(t)?new et(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):tt.isMiniMaxProvider(t)?new tt(n,e):rt.isMistralProvider(t)?new rt(n,e):new F(n,e)}export{ae as a,Ze as b,et as c,tt as d,rt as e,nt as f,pr as g,dr as h,st as i,mr as j,l_ as k,ji as l};
34
34
  /**
35
35
  * @license
36
36
  * Copyright 2025 Matilda