@maincode-ai/matilda-code 0.21.6 → 0.21.7-nightly.20260919.d953e31d2

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 (110) hide show
  1. package/chunks/agent-6WJWHK33.js +3 -0
  2. package/chunks/agent-headless-QEKAFQC2.js +3 -0
  3. package/chunks/{anthropicContentGenerator-EAQDRKHH.js → anthropicContentGenerator-SFJGSZHT.js} +1 -1
  4. package/chunks/{askUserQuestion-7II3GVHO.js → askUserQuestion-MJ4FTAOQ.js} +1 -1
  5. package/chunks/{chunk-VB4MJSMC.js → chunk-32PTAACU.js} +1 -1
  6. package/chunks/{chunk-OXHC3R2R.js → chunk-32T6RWWT.js} +1 -1
  7. package/chunks/{chunk-QF6BOPQB.js → chunk-34DXSYJZ.js} +2 -2
  8. package/chunks/{chunk-BH56I7SB.js → chunk-3ZAMYREW.js} +1 -1
  9. package/chunks/{chunk-YTGWPLEA.js → chunk-5PMMY47S.js} +1 -1
  10. package/chunks/{chunk-BGZJUBRA.js → chunk-6B5BDE7S.js} +1 -1
  11. package/chunks/{chunk-EU5CK2VJ.js → chunk-77N2Q3QZ.js} +509 -509
  12. package/chunks/{chunk-OVC5Z3EX.js → chunk-B3NVKOSU.js} +1 -1
  13. package/chunks/{chunk-X4ML2NEE.js → chunk-DCQKJTAX.js} +2 -2
  14. package/chunks/chunk-EQEQPZLQ.js +8 -0
  15. package/chunks/{chunk-LNTO3FNQ.js → chunk-FRL6KOLY.js} +1 -1
  16. package/chunks/chunk-FWIVFCKF.js +8 -0
  17. package/chunks/{chunk-AICUGYJK.js → chunk-IC3HJLOD.js} +1 -1
  18. package/chunks/chunk-INAZKGGR.js +8 -0
  19. package/chunks/{chunk-IPL3QW4D.js → chunk-JF6ED3QG.js} +1 -1
  20. package/chunks/{chunk-4Z6HQEVC.js → chunk-L6RZIQQE.js} +2 -2
  21. package/chunks/chunk-LIWYWWOK.js +8 -0
  22. package/chunks/{chunk-FQ44TPC5.js → chunk-LSDMWVW6.js} +3 -3
  23. package/chunks/chunk-Q2I3ARPJ.js +8 -0
  24. package/chunks/{chunk-XITA5WMN.js → chunk-QHA3ZBRO.js} +1 -1
  25. package/chunks/chunk-RJX7DK4Y.js +27 -0
  26. package/chunks/chunk-ROETRE5J.js +9 -0
  27. package/chunks/{chunk-O3OUYCSO.js → chunk-S7G6QPEP.js} +1 -1
  28. package/chunks/{chunk-UTS2D2OV.js → chunk-SNTDBBLK.js} +11 -11
  29. package/chunks/chunk-TI3VD43G.js +34 -0
  30. package/chunks/{chunk-C7L2FDS6.js → chunk-UY56RCKZ.js} +3 -3
  31. package/chunks/chunk-VLYRNOD3.js +36 -0
  32. package/chunks/chunk-VWWEEU4V.js +9 -0
  33. package/chunks/chunk-VYTYYCBR.js +3 -0
  34. package/chunks/chunk-XCJYORZX.js +9 -0
  35. package/chunks/{computer-use-X7US5CFC.js → computer-use-NPZQKWAA.js} +1 -1
  36. package/chunks/contextCommand-3E2GKMYJ.js +3 -0
  37. package/chunks/{cron-create-HASFXYQL.js → cron-create-BTTPO3JC.js} +1 -1
  38. package/chunks/{cron-delete-AW4S5IYT.js → cron-delete-U55RHRID.js} +1 -1
  39. package/chunks/{cron-list-U5U5GO6A.js → cron-list-J4HRR46K.js} +1 -1
  40. package/chunks/{edit-CVHLH32T.js → edit-BV6UXJHV.js} +1 -1
  41. package/chunks/{enter-worktree-DOV462JZ.js → enter-worktree-WFRS6DOO.js} +1 -1
  42. package/chunks/{enterPlanMode-4Z32XTSV.js → enterPlanMode-6XO2FCD4.js} +1 -1
  43. package/chunks/{exit-worktree-SZWLWCNF.js → exit-worktree-YRVXXUJG.js} +1 -1
  44. package/chunks/{exitPlanMode-MG7QZYZ7.js → exitPlanMode-XSANODDU.js} +1 -1
  45. package/chunks/{geminiContentGenerator-S4NNKSEQ.js → geminiContentGenerator-YT3R7XR7.js} +1 -1
  46. package/chunks/glob-72QENSN5.js +22 -0
  47. package/chunks/{grep-CB6P3VIR.js → grep-XOHANNB6.js} +1 -1
  48. package/chunks/{keychain-token-storage-5MWTIAEL.js → keychain-token-storage-HAFQQIXL.js} +1 -1
  49. package/chunks/ls-CLDNF3YS.js +15 -0
  50. package/chunks/{lsp-ELR2BGT4.js → lsp-7SKRKR5Q.js} +1 -1
  51. package/chunks/{matildaAgentContentGenerator-GHIMPOOE.js → matildaAgentContentGenerator-ZKC3SSAZ.js} +1 -1
  52. package/chunks/matildaContentGenerator-GQZIZKRP.js +8 -0
  53. package/chunks/{matildaOAuth2-5EYRIK66.js → matildaOAuth2-W2DQO2NK.js} +1 -1
  54. package/chunks/monitor-KB6FBBGO.js +32 -0
  55. package/chunks/notebook-edit-L6PI7HSF.js +17 -0
  56. package/chunks/{openaiContentGenerator-O5Q5FHFD.js → openaiContentGenerator-6K7CKWZW.js} +1 -1
  57. package/chunks/read-file-J5UBJYDO.js +3 -0
  58. package/chunks/ripGrep-INSEEE7H.js +3 -0
  59. package/chunks/scheduler-LOT5MRJN.js +8 -0
  60. package/chunks/{send-message-GFPVOTSZ.js → send-message-XXRROIL7.js} +1 -1
  61. package/chunks/{serve-VW4UWSX4.js → serve-DLXQ2XQC.js} +21 -21
  62. package/chunks/shell-VENIQ6VU.js +3 -0
  63. package/chunks/{skill-JFIJEIFA.js → skill-CZPMRNLD.js} +1 -1
  64. package/chunks/src-HILUWMHH.js +3 -0
  65. package/chunks/symbol-search-3MVTK4KV.js +19 -0
  66. package/chunks/{syntheticOutput-XKGS6F2D.js → syntheticOutput-QEUQIVQJ.js} +1 -1
  67. package/chunks/task-create-AEJQ73GE.js +3 -0
  68. package/chunks/{task-list-V27WHHHJ.js → task-list-ZEJTNZ2O.js} +1 -1
  69. package/chunks/{task-stop-NON26GAN.js → task-stop-JO3CXG2K.js} +1 -1
  70. package/chunks/{task-update-DE7CUGPY.js → task-update-3YY37VFN.js} +1 -1
  71. package/chunks/{team-create-JEC4ZSNE.js → team-create-QFMW37FS.js} +1 -1
  72. package/chunks/team-delete-4YYLUV23.js +8 -0
  73. package/chunks/{todoWrite-YIMKFWIL.js → todoWrite-7BZMVNBC.js} +1 -1
  74. package/chunks/{tool-search-HFOHXFK5.js → tool-search-OWJC3UTX.js} +1 -1
  75. package/chunks/{update-goal-IDTG4LI6.js → update-goal-CF6G57J7.js} +1 -1
  76. package/chunks/{web-fetch-EVO7GDEB.js → web-fetch-K575OWZ7.js} +1 -1
  77. package/chunks/{web-search-SJMJGGPE.js → web-search-F6JRBXFV.js} +1 -1
  78. package/chunks/{workflow-2H6H2FR4.js → workflow-YDVW6LM6.js} +2 -2
  79. package/chunks/write-file-ML7S4MKZ.js +15 -0
  80. package/cli.js +444 -441
  81. package/package.json +2 -2
  82. package/chunks/agent-OP5PDZKJ.js +0 -3
  83. package/chunks/agent-headless-GLMZVYOK.js +0 -3
  84. package/chunks/chunk-2HFKTFO5.js +0 -9
  85. package/chunks/chunk-5QAKUC2D.js +0 -14
  86. package/chunks/chunk-EPA3A73R.js +0 -56
  87. package/chunks/chunk-FW6Z25AA.js +0 -3
  88. package/chunks/chunk-L5ASITMV.js +0 -9
  89. package/chunks/chunk-MW3LAIJW.js +0 -8
  90. package/chunks/chunk-N6BOYL6K.js +0 -27
  91. package/chunks/chunk-SOKNPND5.js +0 -8
  92. package/chunks/chunk-SWEYYDZO.js +0 -8
  93. package/chunks/chunk-U3O6TMV7.js +0 -8
  94. package/chunks/chunk-UHDKX2CR.js +0 -8
  95. package/chunks/chunk-VBOVIARK.js +0 -9
  96. package/chunks/contextCommand-F34RZJU6.js +0 -3
  97. package/chunks/glob-T2SHBIJY.js +0 -22
  98. package/chunks/ls-IBIDQ5NV.js +0 -15
  99. package/chunks/matildaContentGenerator-FI2P7XPI.js +0 -8
  100. package/chunks/monitor-O46CPAVO.js +0 -32
  101. package/chunks/notebook-edit-M4XPR4X3.js +0 -17
  102. package/chunks/read-file-4TZCSTH7.js +0 -3
  103. package/chunks/ripGrep-FTFD4K7L.js +0 -3
  104. package/chunks/scheduler-PRAGNX3C.js +0 -8
  105. package/chunks/shell-YO6J22BF.js +0 -3
  106. package/chunks/src-EYWD2F72.js +0 -3
  107. package/chunks/symbol-search-ZV6W6DPK.js +0 -19
  108. package/chunks/task-create-T43QIG2F.js +0 -3
  109. package/chunks/team-delete-LIEVUGIX.js +0 -8
  110. package/chunks/write-file-6A7X7F5R.js +0 -15
@@ -0,0 +1,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-XCJYORZX.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-EQEQPZLQ.js";import{P as S,aa as I}from"./chunk-VLYRNOD3.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
+ */
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as h,f as g}from"./chunk-DCQKJTAX.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-EQEQPZLQ.js";import{aa as b,b as c}from"./chunk-VLYRNOD3.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
+ `,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Matilda
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Z as te}from"./chunk-5QAKUC2D.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
3
+ import{aa as te}from"./chunk-VLYRNOD3.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
4
4
  +`.includes(t)}function P(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function q(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var $=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,F=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function K(t){return`,[]/{}
5
5
  +`.includes(t)}function J(t){return E(t)||Ke.test(t)}var Ke=/^[[{\w-]$/;function le(t){return t===`
6
6
  `||t==="\r"||t===" "||t==="\b"||t==="\f"}function C(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function me(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function fe(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function E(t){return Q(t)||L(t)}function Q(t){return t==='"'||t==="\u201C"||t==="\u201D"}function z(t){return t==='"'}function L(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function G(t){return t==="'"}function B(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function h(t,e){let n=t.length;if(!C(t,n-1))return t+e;for(;C(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function pe(t,e,n){return t.substring(0,e)+t.substring(e+n)}function de(t){return/[,\n][ \t\r]*$/.test(t)}var Je={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Qe={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
@@ -1,30 +1,30 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{M as F,N as U,O as D,g as x,la as _}from"./chunk-4Z6HQEVC.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as O,n as I}from"./chunk-SDTWBD62.js";import{p as b,r as $}from"./chunk-5QAKUC2D.js";import{b as G}from"./chunk-GZPNIYVZ.js";G();var H="2026-06-23",J="auto",V="instant",X=12e4,h=18e4,K=5e4,R=16e3,S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},z=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),Y=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function Q(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var Z="Your message was blocked by our content safety system.";function q(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:Z;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function L(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
3
+ import{M as D,N as L,O as j,g as I,la as _}from"./chunk-L6RZIQQE.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as F,n as U}from"./chunk-SDTWBD62.js";import{q as b,s as $,t as x,u as O}from"./chunk-VLYRNOD3.js";import{b as G}from"./chunk-GZPNIYVZ.js";G();var V="2026-06-23",X="auto",K="instant",z=12e4,h=18e4,Y=5e4,R=16e3,S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},Q=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),Z=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function q(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var ee="Your message was blocked by our content safety system.";function te(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:ee;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function W(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
4
  `):""}function f(n,e){if(n.length<=e)return n;let t=`
5
5
  [...omitted to fit Matilda native agent context...]
6
- `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function ee(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function te(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function ne(n){if(C(n)<=h)return n;let e=`
6
+ `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function ne(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function se(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function oe(n){if(C(n)<=h)return n;let e=`
7
7
  [...omitted to fit Matilda native request limit...]
8
- `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function se(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function oe(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function ae(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function ie(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function j(n){let e=T("",n);return e.matildaReplace=!0,e}function re(n){return n.matildaReplace===!0}function W(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*le(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
- `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:M,value:p}=await t.read();if(M||d)break;a(),o+=s.decode(p,{stream:!0});let E=o.split(`
10
- `);o=E.pop()??"";for(let k of E){let v=k.endsWith("\r")?k.slice(0,-1):k;if(v.length===0){let N=g();N&&(yield N)}else v.startsWith("event:")?i=v.slice(6).trim():v.startsWith("data:")&&r.push(v.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let M of o.split(`
11
- `)){let p=M.endsWith("\r")?M.slice(0,-1):M;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var B=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){re(a)?o="":o+=ee(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of le(s,X))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=oe(a);l&&(i=!0,yield ae(l,t))}else if(a.event==="client_tool_call"){let l=se(a);l&&(i=!0,yield ie(l,t))}else if(a.event==="usage")d=te(a.data)??d;else if(a.event==="replace")yield j(t);else if(a.event==="safety_replace"){yield j(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield W(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield W(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw new b(r instanceof Error?r.message:String(r))}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await O("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${Q(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===422){let o=q(t);if(o)throw new $(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new Error(s)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":H,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!U(s)&&(t[s]=o);return D(this.contentGeneratorConfig,e)&&Object.assign(t,F(this.cliConfig),I()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),ne(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
8
+ `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function ae(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function ie(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function re(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function le(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function B(n){let e=T("",n);return e.matildaReplace=!0,e}function ce(n){return n.matildaReplace===!0}function H(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*de(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
+ `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:v,value:p}=await t.read();if(v||d)break;a(),o+=s.decode(p,{stream:!0});let E=o.split(`
10
+ `);o=E.pop()??"";for(let k of E){let M=k.endsWith("\r")?k.slice(0,-1):k;if(M.length===0){let N=g();N&&(yield N)}else M.startsWith("event:")?i=M.slice(6).trim():M.startsWith("data:")&&r.push(M.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let v of o.split(`
11
+ `)){let p=v.endsWith("\r")?v.slice(0,-1):v;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var J=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){ce(a)?o="":o+=ne(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of de(s,z))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=ie(a);l&&(i=!0,yield re(l,t))}else if(a.event==="client_tool_call"){let l=ae(a);l&&(i=!0,yield le(l,t))}else if(a.event==="usage")d=se(a.data)??d;else if(a.event==="replace")yield B(t);else if(a.event==="safety_replace"){yield B(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield H(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield H(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw new b(r instanceof Error?r.message:String(r))}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await F("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${q(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===403){let o;try{o=JSON.parse(t)}catch{}if(x(o))throw new $}if(e.status===422){let o=te(t);if(o)throw new O(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new Error(s)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":V,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!L(s)&&(t[s]=o);return j(this.contentGeneratorConfig,e)&&Object.assign(t,D(this.cliConfig),U()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),oe(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
12
12
  (empty prompt)`});let r=i[i.length-1];return r?.role!=="user"?i.push({role:"user",content:`${this.purposeLabel(t)}:
13
13
  Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
14
14
  `)||(i[i.length-1]={...r,content:`${this.purposeLabel(t)}:
15
15
  ${r.content}`}),i}buildSystemContext(e,t){let s=["Agent: Matilda Code",t==="code"?`Routing intent:
16
- ${z}`:void 0,`Instructions:
16
+ ${Q}`:void 0,`Instructions:
17
17
  ${this.instructionsFromRequest(e)}`].filter(o=>!!o);return f(s.join(`
18
18
 
19
- `),K)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?V:e==="analysis"?"deep":J}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[Y,...t,this.localAgentContext()].join(`
19
+ `),Y)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?K:e==="analysis"?"deep":X}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[Z,...t,this.localAgentContext()].join(`
20
20
 
21
21
  `)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let s=this.cliConfig.getApprovalMode?.();s&&e.push(`- Approval mode: ${s}`);let o=this.cliConfig.getSandbox?.();e.push(o?`- Sandbox: ${o.command} (${o.image}).`:"- Sandbox: disabled.");let i=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,g]of i)g.length>0&&e.push(`- Permission ${l} rules: ${g.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let a=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return a.length>0&&e.push(`- Local tools available through the CLI loop: ${a.join(", ")}`),e.join(`
22
- `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>L(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return x.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
- ${f(L(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
22
+ `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>W(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return I.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
+ ${f(W(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
24
24
  `):"";return`Assistant:
25
25
  ${f([t,s].filter(Boolean).join(`
26
26
  `),R)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
27
- ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{re as a,B as b};
27
+ ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{ce as a,J as b};
28
28
  /**
29
29
  * @license
30
30
  * Copyright 2026 Matilda Team
@@ -0,0 +1,34 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as be}from"./chunk-LIWYWWOK.js";import{c as q,f as O}from"./chunk-QHA3ZBRO.js";import{M as pe,N as ce,O as k,Q as me,R as W,S as de,a as re,g as P,h as ie,la as ge}from"./chunk-L6RZIQQE.js";import{a as he}from"./chunk-DC7LAFZZ.js";import{a as oe,g as ae,k as se,l as D,o as ue,t as fe,v as Ce}from"./chunk-S7G6QPEP.js";import{e as ne}from"./chunk-4J6DC24J.js";import{b as H,c as N,f as le,n as j}from"./chunk-SDTWBD62.js";import{b as z}from"./chunk-ESSYHTAZ.js";import{a as U,aa as A,c as ee,q as J,s as te,t as K}from"./chunk-VLYRNOD3.js";import{b as p}from"./chunk-GZPNIYVZ.js";p();p();p();p();p();function Re(i){return i.toLowerCase().includes("matilda3")}function Ie(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?i:{...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:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))le(o)||(r[o]=a);return r}buildClient(){let{apiKey:e,baseUrl:t,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=q("openai",this.cliConfig.getProxy());return new U({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{}})}buildRequest(e,t){let n=this.contentGeneratorConfig.extra_body,r=this.applyOutputTokenLimit(e),o=Re(e.model)?r.messages.map(Ie):r.messages;return{...r,messages:o,...n||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,n=Ce(e.model,"output"),r=fe(e.model),o;if(t!=null)r?o=Math.min(t,n):o=t;else{let a=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,s=a?parseInt(a,10):NaN;!isNaN(s)&&s>0?o=r?Math.min(s,n):s:o=Math.min(n,8e3)}return{...e,max_tokens:o}}};var w=class extends f{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let n=super.buildRequest(e,t);return n.stream||delete n.stream_options,n}};p();var Me=A("MatildaOpenAICompatibleProvider"),b=class i extends f{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:n}=e;if(t==="matilda-oauth"||!n)return!0;let r=n.endsWith("/")?n.slice(0,-1):n,o=null;try{o=new URL(r).hostname.toLowerCase()}catch{o=null}let a=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"),s=D?.endsWith("/")?D.slice(0,-1):D,l=!!(s&&r.toLowerCase()===s.toLowerCase());return s&&!a&&!l&&Me.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),a||l}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:n}=this.contentGeneratorConfig,r={"User-Agent":t};for(let[o,a]of Object.entries(n??{}))!ce(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(r[o]=a);return k(this.contentGeneratorConfig)&&Object.assign(r,pe(this.cliConfig)),r}buildClient(){let{apiKey:e,baseUrl:t=se,timeout:n=6e5,maxRetries:r=3}=this.contentGeneratorConfig,o=this.buildHeaders(),a=q("openai",this.cliConfig.getProxy()),s=a?.fetch??globalThis.fetch,l=k(this.contentGeneratorConfig)?async(c,m)=>{let d=new Headers(c instanceof Request?c.headers:void 0);new Headers(m?.headers).forEach((C,u)=>{d.set(u,C)});let g=d.has(H)||d.has(N),h=j(),y=g||Object.keys(h).length>0;if(y){d.delete(H),d.delete(N);for(let[u,G]of Object.entries(h))d.set(u,G);let C=d.get("x-stainless-retry-count");d.has(H)&&C!==null&&/^[1-9][0-9]*$/.test(C)&&d.set(N,"retry")}this.cliConfig.getChannel()===void 0&&me({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let C=await s(c,y?{...m,headers:d}:m);return de({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),C}catch(C){throw W(C,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),C}}:void 0;return new U({apiKey:e,baseURL:t,timeout:n,maxRetries:r,defaultHeaders:o,...a||{},...l?{fetch:l}:{}})}buildRequest(e,t){let n=e.messages,r=e.tools;if(this.shouldEnableCacheControl()){let{messages:s,tools:l}=this.addCacheControl(e,e.stream?"all":"system_only");n=s,r=l}let o=this.applyOutputTokenLimit(e),a=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...a||{}}:{...o,messages:n,...r?{tools:r}:{},...this.buildMetadata(t)||{},...a||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let n=e.messages,r=n.findIndex(l=>l.role==="system"),o=n.length-1,a=n.length===0?n:n.map((l,c)=>!(c===r&&r!==-1||c===o&&t==="all")||!("content"in l)||l.content===null||l.content===void 0?l:{...l,content:this.addCacheControlToContent(l.content)}),s=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:a,tools:s}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],n=e.length-1;return t[n]={...t[n],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(i.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let n of i.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(n))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};p();p();function F(i){if(i.role!=="assistant")return i;let e=i;return typeof e.reasoning_content=="string"?i:{...e,reasoning_content:""}}function E(i){let e=i.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 Te(i){return E(i)?!0:(i.model??"").toLowerCase().includes("deepseek")}var R=class extends f{constructor(e,t){super(e,t)}static isDeepSeekProvider=Te;static isDeepSeekHostname=E;buildRequest(e,t){let n=super.buildRequest(e,t),r=E(this.contentGeneratorConfig)?ve(n):n;if(!r.messages?.length)return r;let o=r.messages.map(a=>{let s=xe(a);return F(s)});return{...r,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function xe(i){if(!("content"in i))return i;let{content:e}=i;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return i;let t=e.map(n=>typeof n=="string"?n:n.type==="text"?n.text??"":`[Unsupported content type: ${n.type}]`).join(`
4
+
5
+ `);return{...i,content:t}}function ve(i){let e=i,t=e.reasoning,n=t?.effort;if(typeof n!="string"||!n)return i;let r={...e};if(typeof r.reasoning_effort!="string"||!r.reasoning_effort){let o=n;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),r.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete r.reasoning;else if(t){let{effort:o,...a}=t;r.reasoning=a}return r}p();var I=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"}}};p();var we=["api.minimaxi.com","api.minimax.io"],Ge=[".minimaxi.com",".minimax.io"],M=class extends f{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return we.includes(t)?!0:Ge.some(n=>t.endsWith(n))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};p();var ye="api.mistral.ai",ke=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ee(i){let e=i.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===ye||t.endsWith(`.${ye}`)}catch{return!1}}function _e(i){if(Ee(i))return!0;let e=i.model?.toLowerCase()??"";return ke.some(t=>e.includes(t))}var T=class extends f{static isMistralProvider=_e;buildRequest(e,t){let n=super.buildRequest(e,t);return{...n,messages:n.messages.map(Se)}}};function Se(i){if(!("reasoning_content"in i))return i;let e={...i};return delete e.reasoning_content,e}p();function Le(i){let e=i.baseUrl??"";if(e)try{let n=new URL(e).hostname.toLowerCase();if(n==="xiaomimimo.com"||n.endsWith(".xiaomimimo.com"))return!0}catch{}return(i.model??"").toLowerCase().startsWith("mimo-")}var x=class extends f{constructor(e,t){super(e,t)}static isMiMoProvider=Le;buildRequest(e,t){let n=super.buildRequest(e,t);return n.messages?.length?{...n,messages:n.messages.map(F)}:n}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};p();p();var Ue=A("STREAMING_TOOL_CALL_PARSER"),V=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,n,r){let o=e,a=!!(n&&this.idToIndexMap.has(n));if(n)if(this.idToIndexMap.has(n))o=this.idToIndexMap.get(n);else{if(this.buffers.has(e)){let u=this.buffers.get(e),G=this.depths.get(e),Z=this.toolCallMeta.get(e);if(u.trim()&&G===0&&Z?.id&&Z.id!==n)try{JSON.parse(u),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(n,o)}else if(this.buffers.has(e)){let u=this.buffers.get(e);if(this.depths.get(e)>0||!u.trim())o=e;else try{JSON.parse(u),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 s=this.buffers.get(o),l=this.depths.get(o);if(a&&s.trim()&&l===0)try{return JSON.parse(s),Ue.debug(`Ignoring replay chunk for completed toolCall id=${n}`),{complete:!1}}catch{}let c=this.toolCallMeta.get(o);n&&(c.id=n),r&&(c.name=r);let m=this.inStrings.get(o),d=this.escapes.get(o),g=s+t;this.buffers.set(o,g);let h=l,y=m,C=d;for(let u of t)y||(u==="{"||u==="["?h++:(u==="}"||u==="]")&&h--),u==='"'&&!C&&(y=!y),C=u==="\\"&&!C;if(this.depths.set(o,h),this.inStrings.set(o,y),this.escapes.set(o,C),h===0&&g.trim().length>0)try{return{complete:!0,value:JSON.parse(g)}}catch(u){if(y)try{return{complete:!0,value:JSON.parse(g+'"'),repaired:!0}}catch{}return{complete:!1,error:u instanceof Error?u:new Error(String(u))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!0})}getStrictCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!1})}collectCompletedToolCalls({allowJsonRepair:e}){let t=[],n=new Set;for(let[r,o]of this.buffers.entries()){let a=this.toolCallMeta.get(r);if(a?.name){let s=this.depths.get(r)||0,l=this.inStrings.get(r)||!1;if(s>0||l)continue;if(a.id){if(n.has(a.id))continue;n.add(a.id)}let c;if(!o.trim())c={};else try{c=JSON.parse(o)}catch{if(!e)continue;let m=oe(o,null);if(!m||typeof m!="object")continue;c=m}t.push({id:a.id,name:a.name,args:c,index:r})}}return t}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),n=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!n?.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,n]of this.buffers.entries()){let r=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(r>0||!n.trim()))e=Math.max(e,t);else if(n.trim())try{JSON.parse(n)}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,t]of this.buffers.entries()){let n=this.toolCallMeta.get(e),r=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(r>0||o)return!0;if(!n?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var Ae=16e3,Pe=`[Earlier content omitted to fit Matilda Core external API limits]
6
+ `,B=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},_=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(n,r)=>{let o=e.config?.abortSignal,a=o?z(o):void 0,s=this.reportedOperationHeaders();try{let l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}});return P.convertOpenAIResponseToGemini(l,r)}finally{a?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(n,r)=>{let o=e.config?.abortSignal,a=o?z(o):void 0,s=this.reportedOperationHeaders(),l;try{l=await this.client.chat.completions.create(n,{signal:a?.signal,...s?{headers:s}:{}})}catch(g){throw a?.abort(),g}if(!a)return this.processStreamWithLogging(l,r,e);let c=a,m=this.processStreamWithLogging(l,r,e);async function*d(){try{yield*m}finally{c.abort()}}return d()})}reportedOperationHeaders(){if(!k(this.contentGeneratorConfig))return;let e=j();return Object.keys(e).length>0?e:void 0}async*processStreamWithLogging(e,t,n){let r=[],o=null,a=!1;try{for await(let s of e){if(s.choices?.[0]?.finish_reason==="error_finish"){let m=s.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new B(m)}let l=P.convertOpenAIChunkToGemini(s,t);if(l.candidates?.[0]?.content?.parts?.length===0&&!l.candidates?.[0]?.finishReason&&!l.usageMetadata)continue;if(a){if(l.usageMetadata){let m=o;m&&(m.usageMetadata=l.usageMetadata)}r.push(l);continue}this.handleChunkMerging(l,r,m=>{o=m})&&(o?(yield o,a=!0):yield l)}if(!o&&!a){let s=P.flushOpenAIStreamToGemini(t);s&&(yield s,a=!0)}o&&!a&&(yield o)}catch(s){if(s instanceof B)throw O(s);await this.handleError(s,t,n)}}handleChunkMerging(e,t,n){let r=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(r){if(o){let a=t[t.length-1];e.usageMetadata&&(a.usageMetadata=e.usageMetadata),n(a)}else t.push(e),n(e);return!1}else if(o){let a=t[t.length-1],s=new ne;return s.candidates=a.candidates,e.usageMetadata?s.usageMetadata=e.usageMetadata:s.usageMetadata=a.usageMetadata,s.responseId=e.responseId,s.createTime=e.createTime,s.modelVersion=e.modelVersion,s.promptFeedback=e.promptFeedback,t[t.length-1]=s,n(s),!0}return t.push(e),!0}async buildRequest(e,t,n,r){let o=P.convertGeminiRequestToOpenAI(e,n),a=this.shouldUseMatildaCoreRequestProfile(),s=a?this.toMatildaCoreUserMessages(o):o,l={model:n.model,messages:s,...this.buildGenerateContentConfig(e)};r?(l.stream=!0,l.stream_options={include_usage:!0}):l.stream=!1,!a&&e.config?.tools&&e.config.tools.length>0&&(l.tools=await P.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let c=this.config.provider.buildRequest(l,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let d=c,g=(n.model??"").toLowerCase();if(b.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(g.startsWith("matilda")||g==="coder-model")){d.enable_thinking=!1;let h=d.chat_template_kwargs;typeof h=="object"&&h!==null&&"enable_thinking"in h&&(d.chat_template_kwargs={...h,enable_thinking:!1})}"reasoning"in d&&delete d.reasoning,"reasoning_effort"in d&&delete d.reasoning_effort,E(this.contentGeneratorConfig)&&(d.thinking={type:"disabled"})}return c}toMatildaCoreUserMessages(e){let t=e.filter(n=>n.role==="user").map(n=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(n.content))})).filter(n=>n.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 n=this.contentGeneratorConfig.customHeaders??{};return Object.entries(n).some(([o,a])=>o.toLowerCase()==="x-matilda-client"&&a.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(`
7
+ `):""}sanitizeMatildaUserContent(e){let n=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(n.length<=Ae)return n;let r=Ae-Pe.length;return`${Pe}${n.slice(-r)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),n=this.contentGeneratorConfig.samplingParams,r=(s,l)=>{let c=n?.[s],m=l?e.config?.[l]:void 0,d=l?t[l]:void 0;return c!==void 0?c:m!==void 0?m:d},o=(s,l,c)=>{let m=r(l,c);return m!==void 0?{[s]:m}:{}};if(n!==void 0){let s=e.config?.maxOutputTokens;return{...n,...s!==void 0&&n.max_tokens!==void 0?{max_tokens:s}:{}}}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,n,r){let o=this.createRequestContext(e,n);try{let a=await this.buildRequest(e,t,o,n);return ie.getStore()?.(a),ae.recordOpenAIWireRequest(a),await r(a,o)}catch(a){return await this.handleError(a,o,e)}}async handleError(e,t,n){this.config.errorHandler.handle(O(e),t,n)}createRequestContext(e,t){let n=e.model||this.contentGeneratorConfig.model,r=this.config.provider.getRequestContextOverrides?.()??{},o=t?new V:void 0,a=this.config.provider.getResponseParsingOptions?.(),s=t&&a?.taggedThinkingTags?new re:void 0;return{model:n,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:r.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...a?{responseParsingOptions:a}:{},...s?{taggedThinkingParser:s}:{}}}};p();var De=A("OPENAI_ERROR"),S=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,n){let r=O(e),o=this.isTimeoutError(r),a=this.buildErrorMessage(r,t,o);throw this.shouldSuppressErrorLogging(r,n)||De.error("OpenAI API Error:",a),o?new Error(`${a}
8
+
9
+ ${this.getTimeoutTroubleshootingTips()}`):r}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(),n=e?.code,r=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")||n==="ETIMEDOUT"||n==="ESOCKETTIMEDOUT"||r==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,n){let r=Math.round((Date.now()-t.startTime)/1e3);return n?`Request timeout after ${r}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
10
+ ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`
11
+ `)}`}};var Oe=A("OPENAI"),v=class{pipeline;constructor(e,t,n){let r={cliConfig:t,provider:n,contentGeneratorConfig:e,errorHandler:new S((o,a)=>this.shouldSuppressErrorLogging(o,a))};this.pipeline=new _(r)}shouldSuppressErrorLogging(e,t){return!!(ee(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 be().calculateTokens(e)).totalTokens}}catch(t){Oe.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let n=JSON.stringify(e.contents);return{totalTokens:Math.ceil(n.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(n=>typeof n=="string"?n:"parts"in n&&n.parts?n.parts.map(r=>typeof r=="string"?r:"text"in r&&r.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(n=>typeof n=="string"?n:"text"in n?n.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(n){let r=O(n);throw Oe.error("OpenAI API Embedding Error:",r),new Error(`OpenAI API error: ${r instanceof Error?r.message:String(r)}`)}}useSummarizedThinking(){return!1}};p();var L=class extends v{contentGeneratorConfig;cliConfig;channel;constructor(e,t,n){super(e,t,n),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return X(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=()=>super.generateContentStream(e,t),r=await this.withTokenRefresh(n);return this.iterateWithAuthRetry(r,n)}async*iterateWithAuthRetry(e,t){let n=!1;try{for await(let r of e)n||=(r.candidates??[]).some(o=>!!(o.finishReason||o.content?.parts?.length)),yield r;return}catch(r){if(!X(r))throw $(r);if(n)throw new J("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0});try{yield*await t()}catch(o){throw $(o)}}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await ge({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(n){throw W(n,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),n}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[he]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!X(t))throw $(t);await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(n){throw $(n)}}}};function $(i){return K(i)?new te:X(i)?new J("Matilda session expired and could not be refreshed. Run /auth to reconnect."):i}function X(i){if(!i||K(i))return!1;let e=i instanceof Error?i.message.toLowerCase():String(i).toLowerCase(),t=i,n=Number(t.status??t.statusCode??t.code);return n>=400&&n<600?n===401:e.includes("unauthorized")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("token")&&e.includes("expired")}function In(i,e){let t=He(i,e);return b.isMatildaCompatibleProvider(i)?new L(i,e,t):new v(i,e,t)}function He(i,e){let t=i||e.getContentGeneratorConfig();return b.isMatildaCompatibleProvider(t)?new b(i,e):R.isDeepSeekProvider(t)?new R(i,e):x.isMiMoProvider(t)?new x(i,e):I.isOpenRouterProvider(t)?new I(i,e):w.isModelScopeProvider(t)?new w(i,e):M.isMiniMaxProvider(t)?new M(i,e):T.isMistralProvider(t)?new T(i,e):new f(i,e)}export{b as a,R as b,I as c,M as d,T as e,x as f,_ as g,S as h,v as i,L as j,In as k,He as l};
12
+ /**
13
+ * @license
14
+ * Copyright 2025 Matilda
15
+ * SPDX-License-Identifier: Apache-2.0
16
+ */
17
+ /**
18
+ * @license
19
+ * Copyright 2026 Maincode
20
+ * SPDX-License-Identifier: Apache-2.0
21
+ *
22
+ * OpenAI-compat Matilda Code path (settings selectedType=openai + MATILDA_API_KEY).
23
+ *
24
+ * Emulates Grok Build's automatic credential refresh
25
+ * (docs: "Automatic Credential Refresh"):
26
+ * 1. Before each request: ensure a fresh access token (re-read disk; refresh
27
+ * when within the early-invalidation window / already expired).
28
+ * 2. On 401 Unauthorized: force-refresh and retry the request once.
29
+ * 3. When refresh fails (invalid_grant): surface re-auth; do not loop.
30
+ *
31
+ * Plain OpenAIContentGenerator only hydrated MATILDA_API_KEY once at
32
+ * createContentGenerator time, so idle sessions past access-token expiry
33
+ * failed every turn with `API Error: 401 "Unauthorized"` until restart//auth.
34
+ */