@maincode-ai/matilda-code 0.20.0 → 0.20.1

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 (63) hide show
  1. package/bundled/mainy/docs/features/headless.md +37 -0
  2. package/bundled/mainy/docs/features/mcp.md +3 -3
  3. package/chunks/{agent-N5H7ZVZN.js → agent-CE34X462.js} +1 -1
  4. package/chunks/{agent-headless-LBLAX66M.js → agent-headless-CNI7H4BU.js} +1 -1
  5. package/chunks/{anthropicContentGenerator-DKMAJXYA.js → anthropicContentGenerator-ATLOKYPR.js} +1 -1
  6. package/chunks/chunk-3YLXGE6T.js +8 -0
  7. package/chunks/{chunk-GTR4V2PV.js → chunk-DC7LAFZZ.js} +1 -1
  8. package/chunks/chunk-DHBNZZZO.js +95 -0
  9. package/chunks/{chunk-KP6BLFQS.js → chunk-GIIMOLLN.js} +1 -1
  10. package/chunks/chunk-IMYUVCF7.js +27 -0
  11. package/chunks/{chunk-3KCDX6MY.js → chunk-ISW2QC5B.js} +1 -1
  12. package/chunks/{chunk-RO6LKQPB.js → chunk-J56KRT6Z.js} +458 -458
  13. package/chunks/chunk-OCXGNAAT.js +8 -0
  14. package/chunks/{chunk-Z7OHKQ7V.js → chunk-OQVITNHW.js} +1 -1
  15. package/chunks/{chunk-QT4UNNZ4.js → chunk-SKBC2YV2.js} +4 -4
  16. package/chunks/{chunk-XXZH7C44.js → chunk-SS5WUOSJ.js} +1 -1
  17. package/chunks/chunk-T75X5DJI.js +101 -0
  18. package/chunks/{chunk-TRM7SXZ5.js → chunk-WUQZ3WFM.js} +1 -1
  19. package/chunks/chunk-XJDC3ZQZ.js +8 -0
  20. package/chunks/{computer-use-LG4QQFMP.js → computer-use-4533FJAL.js} +1 -1
  21. package/chunks/contextCommand-M7LA5BRD.js +3 -0
  22. package/chunks/edit-U4P4JWQ6.js +38 -0
  23. package/chunks/{enter-worktree-OIP2B3NM.js → enter-worktree-CUDNIQNH.js} +1 -1
  24. package/chunks/enterPlanMode-SUTLQUZO.js +18 -0
  25. package/chunks/{exit-worktree-VN5I5XWV.js → exit-worktree-72O3N4X4.js} +1 -1
  26. package/chunks/{exitPlanMode-HE6EEGTO.js → exitPlanMode-ZP75YCUK.js} +14 -14
  27. package/chunks/geminiContentGenerator-KPR5Q3XX.js +8 -0
  28. package/chunks/{glob-EGOAJNOQ.js → glob-V7YUXA6Z.js} +1 -1
  29. package/chunks/{grep-JYHW6SSG.js → grep-WOVNDJPG.js} +1 -1
  30. package/chunks/{matildaAgentContentGenerator-AKNRQW6A.js → matildaAgentContentGenerator-Y5CHD2WJ.js} +1 -1
  31. package/chunks/matildaContentGenerator-F2DTT47Z.js +8 -0
  32. package/chunks/matildaOAuth2-LKOMJUC6.js +3 -0
  33. package/chunks/{monitor-IDNOTNUP.js → monitor-G7G765XR.js} +1 -1
  34. package/chunks/{notebook-edit-4VBYBZFJ.js → notebook-edit-QK7K5ALF.js} +1 -1
  35. package/chunks/{openaiContentGenerator-WTRQK5RJ.js → openaiContentGenerator-XLDE2S4K.js} +1 -1
  36. package/chunks/ripGrep-W5JZVWA4.js +3 -0
  37. package/chunks/{scheduler-AOKJEAXJ.js → scheduler-C7N3Q67S.js} +1 -1
  38. package/chunks/{serve-2JJY265V.js → serve-WDV5Q7R4.js} +1 -1
  39. package/chunks/shell-IEGVNM6S.js +3 -0
  40. package/chunks/src-Y3JZTLKR.js +3 -0
  41. package/chunks/{team-create-Z6636NPD.js → team-create-OPP7B3G2.js} +1 -1
  42. package/chunks/{update-goal-DH2TEYYU.js → update-goal-6WDBMJ2I.js} +1 -1
  43. package/chunks/{web-fetch-5F7C7MXU.js → web-fetch-QP42GV23.js} +1 -1
  44. package/chunks/{web-search-W2FYCGK5.js → web-search-FURCBRRK.js} +1 -1
  45. package/chunks/{workflow-M7KXXDO6.js → workflow-B3DRPVNT.js} +2 -2
  46. package/chunks/write-file-T7MBHX53.js +11 -0
  47. package/cli.js +476 -456
  48. package/package.json +2 -2
  49. package/chunks/chunk-7VGUNT5L.js +0 -8
  50. package/chunks/chunk-CLUEFPSU.js +0 -8
  51. package/chunks/chunk-CYTN3WRM.js +0 -101
  52. package/chunks/chunk-IB7TWUWM.js +0 -90
  53. package/chunks/chunk-LLQVLTPB.js +0 -27
  54. package/chunks/contextCommand-7KHYFQ6G.js +0 -3
  55. package/chunks/edit-U4PMKZYZ.js +0 -38
  56. package/chunks/enterPlanMode-6LZSSWFT.js +0 -17
  57. package/chunks/geminiContentGenerator-GWGLIDJJ.js +0 -8
  58. package/chunks/matildaContentGenerator-MXP3V2UQ.js +0 -8
  59. package/chunks/matildaOAuth2-2IUZAZEO.js +0 -3
  60. package/chunks/ripGrep-DOB57AMM.js +0 -3
  61. package/chunks/shell-WFONAKPV.js +0 -3
  62. package/chunks/src-IHYMMU26.js +0 -3
  63. package/chunks/write-file-O4DJX4LP.js +0 -11
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as c}from"./chunk-4F4DA5UI.js";import{j as i}from"./chunk-CLUEFPSU.js";import{e as l}from"./chunk-5U3A6KMU.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function C(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
3
+ import{a as c}from"./chunk-4F4DA5UI.js";import{k as i}from"./chunk-XJDC3ZQZ.js";import{e as l}from"./chunk-5U3A6KMU.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function C(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
4
4
 
5
5
  `):void 0}catch{return}}function h(t,e){return e?t===void 0?e:typeof t=="string"?`${t}
6
6
 
@@ -0,0 +1,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-XKDGRW3K.js";import{c as Q}from"./chunk-ESSYHTAZ.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-IOCF4XSR.js";import{L as S,Y as I}from"./chunk-QWBNNEV2.js";import{b as M}from"./chunk-GZPNIYVZ.js";M();import ie from"crypto";import q from"node:path";import{promises as b}from"node:fs";import{EventEmitter as De}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as ue}from"node:util";import{platform as he}from"node:os";import{resolve as Z}from"node:path";import{URL as me,fileURLToPath as fe}from"node:url";var ee=ue(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new me(i)}catch{throw new Error(`Invalid URL: ${i}`)}let o=e?["http:","https:","file:"]:["http:","https:"];if(!o.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${o.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(fe(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(i))throw new Error("URL contains invalid characters")}async function te(i,e={}){pe(i,e);let r=he(),t,o,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:we(n,i);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${ge(l)}. Falling back to the platform browser opener.`)}if(!N({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${i}`);return}switch(r){case"darwin":t="open",o=[i];break;case"win32":t="powershell.exe",o=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${i.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",o=[i];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,o,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[i]):await ee(d,[i],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${i}`);return}}async function re(i,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,o)=>{let n=de(i,e,r),s=!1;n.once("error",c=>{s||(s=!0,o(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function ge(i){return i instanceof Error?i.message:String(i)}function we(i,e){if(!i)return;let r=Ee(i);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(Y(r.command))return;let t=!1,o=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||o.push(e),{command:r.command,args:o}}function Ee(i){let e=[],r="",t;for(let s of i){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[o,...n]=e;if(o)return{command:o,args:n}}function Ve(){return N()}M();import H from"node:path";import{promises as y,unlinkSync as ke}from"node:fs";import{randomUUID as ne}from"node:crypto";var R=I("MATILDA_OAUTH"),_e="oauth_creds.json",Ce="oauth_creds.lock",ve=30*1e3,ye=35e3,Te=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var u=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function Re(i){if(!i||typeof i!="object")throw new Error("Invalid credentials format");let e=i,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var D=class i{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return i.instance||(i.instance=new i),i.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();ke(e)}catch{}},process.on("exit",this.cleanupFunction),process.on("SIGINT",this.cleanupFunction),process.on("SIGTERM",this.cleanupFunction),process.on("uncaughtException",this.cleanupFunction),process.on("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof u?t:new u("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<Te)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let o;return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),new Promise((n,s)=>{o=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new u("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),o=(await y.stat(r)).mtimeMs;o>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=o,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new u("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),o=JSON.parse(t),n=Re(o),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&R.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),o=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new u("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&R.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&R.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new u("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new u("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof P?(R.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new u("REFRESH_FAILED",s.message,s)):s instanceof u?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new u("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new u("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(o)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=H.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let o=JSON.stringify(e,null,2);try{await X(r,o,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ve}getCredentialFilePath(){return H.join(S.getGlobalMatildaDir(),_e)}getLockFilePath(){return H.join(S.getGlobalMatildaDir(),Ce)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:o}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>ye){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),R.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){R.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){R.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,o)}else throw new u("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new u("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&R.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),process.removeListener("SIGINT",this.cleanupFunction),process.removeListener("SIGTERM",this.cleanupFunction),process.removeListener("uncaughtException",this.cleanupFunction),process.removeListener("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var h=I("MATILDA_OAUTH"),J="https://chat.matilda.ai",Ae=`${J}/api/v1/oauth2/device/code`,j=`${J}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Fe=3e4,Se="oauth_creds.json";function Pe(){return ie.randomBytes(32).toString("base64url")}function xe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function Oe(){let i=Pe(),e=xe(i);return{code_verifier:i,code_challenge:e}}function B(i){return Object.keys(i).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&")}function W(i,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${U(i,{url:j})}`,{cause:i})}var P=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},K=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function V(i){return"device_code"in i}function Ie(i){return"access_token"in i&&i.access_token!==null&&i.access_token!==void 0&&typeof i.access_token=="string"&&i.access_token.length>0}function Le(i){return"status"in i&&i.status==="pending"}function L(i){return"error"in i}var G=class{credentials={};sharedManager;constructor(){this.sharedManager=D.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return h.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},o=await fetch(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let s=await o.text();throw new Error(`Device authorization failed: ${o.status} ${o.statusText}. Response: ${s}`)}let n=await o.json();if(V(n))h.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;h.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!V(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:be,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let n=await o.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${o.status} ${o.statusText}. Response: ${n}`);throw l.status=o.status,l}if(o.status===400&&s.error==="authorization_pending")return{status:"pending"};if(o.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new K({oauthError:s.error,description:s.error_description,status:o.status})}return await o.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Fe});h.debug("Refreshing access token...");try{let o;try{o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(e),signal:r})}catch(a){throw W(a,r.aborted)}if(!o.ok){let a;try{a=await o.text()}catch(d){throw W(d,r.aborted)}throw o.status===400||o.status===401?(await ae(),new P("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:o.status,response:a})):new Error(`Token refresh failed: ${o.status} ${o.statusText}. Response: ${a}`)}let n;try{n=await o.text()}catch(a){throw W(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},$e=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))($e||{}),F=new De;async function wr(i,e){let r=new G,t=D.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof u)switch(o.type){case"NO_REFRESH_TOKEN":h.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":h.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":h.warn("Network error during token refresh, trying device flow");break;default:h.warn("Token manager error:",o.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await Ue(r,i);if(!n.success){n.reason==="timeout"&&F.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ne(i){let e="Legacy OAuth Device Authorization",r=i,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(f,T)=>{if(f.startsWith("http://")||f.startsWith("https://")){let v=[];for(let O=0;O<f.length;O+=T)v.push(f.substring(O,O+T));return v}let A=f.split(" "),C=[],_="";for(let v of A)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",E="|"+" ".repeat(n-2)+"|",x="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),m=c(r,s),k="Waiting for authorization to complete...";process.stderr.write(`
4
+ `+w+`
5
+ `),process.stderr.write(E+`
6
+ `);for(let f of g)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
7
+ `);process.stderr.write(E+`
8
+ `);for(let f of m)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
9
+ `);process.stderr.write(E+`
10
+ `),process.stderr.write("| "+k+" ".repeat(s-k.length)+` |
11
+ `),process.stderr.write(E+`
12
+ `),process.stderr.write(x+`
13
+
14
+ `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};F.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return h.debug(`
15
+ `+c),F.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{F.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);h.warn(`Failed to open browser automatically: ${a}`),h.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=Oe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let E=a;throw new Error(`Device authorization failed: ${E?.error||"Unknown error"} - ${E?.error_description||"No details provided"}`)}F.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ne(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),h.debug(`Waiting for authorization...
16
+ `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let E=0;E<p;E++){let x=o();if(x)return x;try{h.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let m=g,k={access_token:m.access_token,refresh_token:m.refresh_token||void 0,token_type:m.token_type,resource_url:m.resource_url,expiry_date:m.expires_in?Date.now()+m.expires_in*1e3:void 0};return i.setCredentials(k),await He(k),n("success","Authentication successful! Access token obtained."),h.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),h.debug(`
17
+ Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${E+1}/${p})`),await new Promise(f=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),f();return}if(A>=d){clearInterval(C),f();return}},100)});let k=o();if(k)return k;continue}if(L(g)){let m=g;throw new Error(`Token polling failed: ${m?.error||"Unknown error"} - ${m?.error_description||"No details provided"}`)}}catch(g){let m=g instanceof Error?g.message:String(g),k=g instanceof Error?g.status:null,f=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(m.includes("Failed to cache credentials"))return f("error",m);if(m.includes("401")||k===401)return f("error","Device code expired or invalid, please restart the authorization process.");if(m.includes("429")||k===429)return f("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let A=`Error polling for token: ${m}`;n("error",A),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${U(c,{url:J})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{F.off("auth-cancel",t)}}var $=384;async function He(i,e){let r=ce();try{await b.mkdir(q.dirname(r),{recursive:!0});let t=JSON.stringify(i,null,2),o=`${r}.tmp.${process.pid}.${se()}`;try{await b.writeFile(o,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await b.chmod(o,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);h.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${o} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await b.rename(o,r)}catch(n){try{await b.unlink(o)}catch{}throw n}try{D.getInstance().clearCache()}catch(n){h.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let o=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${q.dirname(r)}\` and writing to \`${r}\`. ${o}. Please check permissions.`)}}async function ae(){try{let i=ce();await b.unlink(i),h.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;h.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{D.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var Er=ae;export{te as a,Ve as b,D as c,Pe as d,xe as e,Oe as f,P as g,K as h,V as i,Ie as j,Le as k,L as l,G as m,$e as n,F as o,wr as p,$ as q,He as r,ae as s,Er as t};
18
+ /**
19
+ * @license
20
+ * Copyright 2025 Google LLC
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+ /**
24
+ * @license
25
+ * Copyright 2025 Matilda
26
+ * SPDX-License-Identifier: Apache-2.0
27
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{s as d}from"./chunk-XYA3SFGC.js";import{c as s}from"./chunk-CLUEFPSU.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();var u=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],p=new Set([...u,...s]),E=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",a="(?:0|[1-9]\\d{0,4})",c="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",f=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${a}$`),new RegExp(`^${o}-maincode\\.${c}(?:\\.${a})?$`)],l=41;function R(e){return e==="desktop"?"desktop":e===void 0||E.has(e)?"code_cli":"unknown"}function m(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function _(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>l||!f.some(n=>n.test(t))))return t}function C(e,t=process.platform){let n=R(e.getChannel?.()),r=_(e.getCliVersion?.());return{"x-matilda-reported-surface":n,"x-matilda-reported-os":m(t),"x-matilda-reported-process":n==="desktop"?"matilda-desktop":n==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":"matilda-client",...r?{"x-matilda-reported-version":r}:{}}}function O(e){return p.has(e.toLowerCase())}function g(e){let t=e??d;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function w(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&g(e.baseUrl)}export{C as a,O as b,w as c};
3
+ import{s as d}from"./chunk-XYA3SFGC.js";import{d as s}from"./chunk-XJDC3ZQZ.js";import{b as i}from"./chunk-GZPNIYVZ.js";i();var u=["x-matilda-reported-surface","x-matilda-reported-os","x-matilda-reported-process","x-matilda-reported-sdk","x-matilda-reported-version"],p=new Set([...u,...s]),E=new Set(["VSCode","ACP","SDK","CI"]),o="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",a="(?:0|[1-9]\\d{0,4})",c="20\\d{2}(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\\d|3[01])",f=[new RegExp(`^${o}$`),new RegExp(`^${o}-preview\\.${a}$`),new RegExp(`^${o}-maincode\\.${c}(?:\\.${a})?$`)],l=41;function R(e){return e==="desktop"?"desktop":e===void 0||E.has(e)?"code_cli":"unknown"}function m(e){return e==="android"?"android":e==="darwin"?"macos":e==="win32"?"windows":e==="linux"?"linux":"unknown"}function _(e){if(typeof e!="string")return;let t=e.trim();if(!(t.length>l||!f.some(n=>n.test(t))))return t}function C(e,t=process.platform){let n=R(e.getChannel?.()),r=_(e.getCliVersion?.());return{"x-matilda-reported-surface":n,"x-matilda-reported-os":m(t),"x-matilda-reported-process":n==="desktop"?"matilda-desktop":n==="code_cli"?"matilda-code":"unknown","x-matilda-reported-sdk":"matilda-client",...r?{"x-matilda-reported-version":r}:{}}}function O(e){return p.has(e.toLowerCase())}function g(e){let t=e??d;try{let n=new URL(t);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let r=n.hostname.toLowerCase();return r==="matilda.maincode.com"||r.endsWith(".matilda.maincode.com")||r==="core-api.matilda"}catch{return!1}}function w(e,t=e.apiKey){return e.authType==="matilda-oauth"?!0:e.authType==="openai"&&!!t&&g(e.baseUrl)}export{C as a,O as b,w as c};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Matilda Team