@maincode-ai/matilda-code 0.21.11-nightly.20261020.022e2cc37 → 0.21.11-preview.0

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 (96) hide show
  1. package/chunks/agent-BU623AHW.js +3 -0
  2. package/chunks/agent-headless-T24DLERB.js +3 -0
  3. package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-VKFTAIU3.js} +1 -1
  4. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-2QI4NSFJ.js} +1 -1
  5. package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
  6. package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
  7. package/chunks/{chunk-2HQMJ2IU.js → chunk-2MOGYHWM.js} +1 -1
  8. package/chunks/{chunk-7R2762AQ.js → chunk-3WBC3IIX.js} +546 -544
  9. package/chunks/{chunk-T4P4KEDW.js → chunk-6E766NPX.js} +1 -1
  10. package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
  11. package/chunks/{chunk-BBFEZFSW.js → chunk-6RCVKDFR.js} +1 -1
  12. package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
  13. package/chunks/{chunk-FMT6S22S.js → chunk-AQQOBDEP.js} +11 -11
  14. package/chunks/{chunk-SNLH42QJ.js → chunk-CZGZ3KK7.js} +1 -1
  15. package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
  16. package/chunks/{chunk-XCFLI3OC.js → chunk-ET7ZXQ3A.js} +1 -1
  17. package/chunks/{chunk-QXOH5UM2.js → chunk-F62NM4KX.js} +1 -1
  18. package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
  19. package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
  20. package/chunks/{chunk-QGU4TQKH.js → chunk-I5H6ZXLS.js} +10 -10
  21. package/chunks/{chunk-25NCTG5H.js → chunk-JA43M5MZ.js} +53 -51
  22. package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
  23. package/chunks/{chunk-QYVJEL6C.js → chunk-KLWMEGO4.js} +1 -1
  24. package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
  25. package/chunks/{chunk-5427BPR2.js → chunk-MCQUPLRE.js} +1 -1
  26. package/chunks/{chunk-QN6WSWMM.js → chunk-MO2HXJG5.js} +1 -1
  27. package/chunks/{chunk-MP6D7B5B.js → chunk-P3G4HEXP.js} +2 -2
  28. package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
  29. package/chunks/{chunk-Y7O6DI35.js → chunk-PW3LFA6D.js} +1 -1
  30. package/chunks/{chunk-W5CGKUM4.js → chunk-S3CWEVTS.js} +1 -1
  31. package/chunks/{chunk-YMIF2DMT.js → chunk-VTGICC67.js} +1 -1
  32. package/chunks/{chunk-SPW5DXX4.js → chunk-WV3IUPZS.js} +1 -1
  33. package/chunks/chunk-WXCEBLRE.js +56 -0
  34. package/chunks/{chunk-WHG6N5X2.js → chunk-YRQP3SLC.js} +1 -1
  35. package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
  36. package/chunks/chunk-ZYCVL46M.js +27 -0
  37. package/chunks/{computer-use-HDAHXM46.js → computer-use-2UBC2SKZ.js} +1 -1
  38. package/chunks/contextCommand-CRHIC6JS.js +3 -0
  39. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-FMTLQJXE.js} +1 -1
  40. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-LWKY3QSE.js} +1 -1
  41. package/chunks/{cron-list-YYAXNHB6.js → cron-list-DJTIFK2L.js} +1 -1
  42. package/chunks/edit-MR52FAWW.js +43 -0
  43. package/chunks/{enter-worktree-YI7BKDPH.js → enter-worktree-HFTCLHRB.js} +1 -1
  44. package/chunks/{enterPlanMode-SZ3D3XRT.js → enterPlanMode-R54IR74J.js} +1 -1
  45. package/chunks/{exit-worktree-L6OTJIBF.js → exit-worktree-NK6IMLGE.js} +1 -1
  46. package/chunks/{exitPlanMode-PSXDKAXV.js → exitPlanMode-X2M6ZV3X.js} +1 -1
  47. package/chunks/{geminiContentGenerator-UWXILFM2.js → geminiContentGenerator-KKK5RWAE.js} +1 -1
  48. package/chunks/{glob-5DANZVAI.js → glob-RKSORKHR.js} +1 -1
  49. package/chunks/{goal-tools-AIYULJ6L.js → goal-tools-RSICRXWC.js} +1 -1
  50. package/chunks/{grep-B4KG4R5T.js → grep-7O4QFORW.js} +1 -1
  51. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
  52. package/chunks/{ls-YWZU3FYL.js → ls-JYJXFSXN.js} +1 -1
  53. package/chunks/{lsp-4CJDKEEC.js → lsp-DYDK6XCS.js} +1 -1
  54. package/chunks/{matildaAgentContentGenerator-EC6EONBZ.js → matildaAgentContentGenerator-JRJ35MC7.js} +1 -1
  55. package/chunks/{matildaContentGenerator-TGMDURRB.js → matildaContentGenerator-3EXH3FBK.js} +1 -1
  56. package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-XE7AHBSI.js} +1 -1
  57. package/chunks/{monitor-D7TU3DUW.js → monitor-7O2YTGFR.js} +1 -1
  58. package/chunks/{notebook-edit-V5XE473Y.js → notebook-edit-6SCNZBO3.js} +1 -1
  59. package/chunks/{openaiContentGenerator-PYFTHLLU.js → openaiContentGenerator-5SBB3YKW.js} +1 -1
  60. package/chunks/read-file-DZTYS4MO.js +3 -0
  61. package/chunks/ripGrep-LVBZPZPH.js +3 -0
  62. package/chunks/{scheduler-B54AG3CC.js → scheduler-NPTZJ56A.js} +1 -1
  63. package/chunks/{send-message-OO2HAKCC.js → send-message-P3SMWNEE.js} +1 -1
  64. package/chunks/{serve-YRXZONLX.js → serve-3VNHJIGD.js} +1 -1
  65. package/chunks/shell-SXPNBWTX.js +3 -0
  66. package/chunks/{skill-6JH5WZFP.js → skill-OQVVXONF.js} +1 -1
  67. package/chunks/src-PJF3I6FQ.js +3 -0
  68. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-EAIZPWN7.js} +1 -1
  69. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-432LXITX.js} +1 -1
  70. package/chunks/task-create-Z3QRCMX4.js +3 -0
  71. package/chunks/{task-detach-I67ZE5MX.js → task-detach-XMSJ3HBM.js} +1 -1
  72. package/chunks/{task-list-5BGX4G5N.js → task-list-MNHMRJN3.js} +1 -1
  73. package/chunks/{task-stop-ERI5X4AO.js → task-stop-NTS62FLG.js} +1 -1
  74. package/chunks/{task-update-CD3W556L.js → task-update-DA5K2V7E.js} +1 -1
  75. package/chunks/{team-create-RBYPBWMT.js → team-create-AATX26NE.js} +1 -1
  76. package/chunks/{team-delete-5U3GBFKJ.js → team-delete-RRYZ6KMB.js} +1 -1
  77. package/chunks/todoWrite-Y6RP55AO.js +3 -0
  78. package/chunks/{tool-search-JFCD5W5M.js → tool-search-EZAYWDKE.js} +1 -1
  79. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-ZTPXSREL.js} +1 -1
  80. package/chunks/{web-search-OX2DPEVN.js → web-search-XQUIZARL.js} +1 -1
  81. package/chunks/{workflow-AVVQMK4O.js → workflow-J6YT6B4V.js} +2 -2
  82. package/chunks/{write-file-CCYKY44V.js → write-file-MO5WWZWG.js} +1 -1
  83. package/cli.js +396 -390
  84. package/package.json +2 -2
  85. package/chunks/agent-5PW6CQEM.js +0 -3
  86. package/chunks/agent-headless-PMTZCOCR.js +0 -3
  87. package/chunks/chunk-GV25S54K.js +0 -54
  88. package/chunks/chunk-HWOQNYAO.js +0 -27
  89. package/chunks/contextCommand-ZZLLOKVS.js +0 -3
  90. package/chunks/edit-DOPUXY2Q.js +0 -39
  91. package/chunks/read-file-6EAPS2KG.js +0 -3
  92. package/chunks/ripGrep-FOKCJ3KE.js +0 -3
  93. package/chunks/shell-NG54W6TS.js +0 -3
  94. package/chunks/src-5ZUUXCSI.js +0 -3
  95. package/chunks/task-create-EBJD55TB.js +0 -3
  96. package/chunks/todoWrite-2RIXEZK7.js +0 -3
@@ -0,0 +1,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-ET7ZXQ3A.js";import{c as Q}from"./chunk-VI74YQQO.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-LUNDTQ3G.js";import{Q as S,ba as I}from"./chunk-27Q5KW3A.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 Re}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as he}from"node:util";import{platform as ue}from"node:os";import{resolve as Z}from"node:path";import{URL as fe,fileURLToPath as me}from"node:url";var ee=he(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new fe(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(me(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=ue(),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=ke(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 ke(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 Ee}from"node:fs";import{randomUUID as ne}from"node:crypto";var D=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 h=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function De(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 R=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();Ee(e)}catch{}},process.on("exit",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 h?t:new h("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 h("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 h("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=De(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")&&D.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 h("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&D.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&&D.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new h("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new h("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 F?(D.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new h("REFRESH_FAILED",s.message,s)):s instanceof h?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new h("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new h("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 h("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 h("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),D.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){D.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){D.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 h("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new h("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"&&D.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),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 u=I("MATILDA_OAUTH"),G="https://chat.matilda.ai",Ae=`${G}/api/v1/oauth2/device/code`,K=`${G}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Pe=3e4,Se="oauth_creds.json";function Fe(){return ie.randomBytes(32).toString("base64url")}function Oe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function xe(){let i=Fe(),e=Oe(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:K})}`,{cause:i})}var F=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},j=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 J=class{credentials={};sharedManager;constructor(){this.sharedManager=R.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 u.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))u.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;u.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(K,{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 j({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:Pe});u.debug("Refreshing access token...");try{let o;try{o=await fetch(K,{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 F("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||{}),P=new Re;async function wr(i,e){let r=new J,t=R.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof h)switch(o.type){case"NO_REFRESH_TOKEN":u.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":u.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":u.warn("Network error during token refresh, trying device flow");break;default:u.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"&&P.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=(m,T)=>{if(m.startsWith("http://")||m.startsWith("https://")){let v=[];for(let x=0;x<m.length;x+=T)v.push(m.substring(x,x+T));return v}let A=m.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)+"+",k="|"+" ".repeat(n-2)+"|",O="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),f=c(r,s),E="Waiting for authorization to complete...";process.stderr.write(`
4
+ `+w+`
5
+ `),process.stderr.write(k+`
6
+ `);for(let m of g)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
7
+ `);process.stderr.write(k+`
8
+ `);for(let m of f)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
9
+ `);process.stderr.write(k+`
10
+ `),process.stderr.write("| "+E+" ".repeat(s-E.length)+` |
11
+ `),process.stderr.write(k+`
12
+ `),process.stderr.write(O+`
13
+
14
+ `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};P.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return u.debug(`
15
+ `+c),P.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{P.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);u.warn(`Failed to open browser automatically: ${a}`),u.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=xe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let k=a;throw new Error(`Device authorization failed: ${k?.error||"Unknown error"} - ${k?.error_description||"No details provided"}`)}P.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..."),u.debug(`Waiting for authorization...
16
+ `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let k=0;k<p;k++){let O=o();if(O)return O;try{u.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let f=g,E={access_token:f.access_token,refresh_token:f.refresh_token||void 0,token_type:f.token_type,resource_url:f.resource_url,expiry_date:f.expires_in?Date.now()+f.expires_in*1e3:void 0};return i.setCredentials(E),await He(E),n("success","Authentication successful! Access token obtained."),u.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),u.debug(`
17
+ Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${k+1}/${p})`),await new Promise(m=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),m();return}if(A>=d){clearInterval(C),m();return}},100)});let E=o();if(E)return E;continue}if(L(g)){let f=g;throw new Error(`Token polling failed: ${f?.error||"Unknown error"} - ${f?.error_description||"No details provided"}`)}}catch(g){let f=g instanceof Error?g.message:String(g),E=g instanceof Error?g.status:null,m=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(f.includes("Failed to cache credentials"))return m("error",f);if(f.includes("401")||E===401)return m("error","Device code expired or invalid, please restart the authorization process.");if(f.includes("429")||E===429)return m("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: ${f}`;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:G})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{P.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)}`);u.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{R.getInstance().clearCache()}catch(n){u.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),u.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;u.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{R.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var kr=ae;export{te as a,Ve as b,R as c,Fe as d,Oe as e,xe as f,F as g,j as h,V as i,Ie as j,Le as k,L as l,J as m,$e as n,P as o,wr as p,$ as q,He as r,ae as s,kr 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{Af as H,Cf as K,Le as x,Oi as V}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{i as S}from"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as G,i as X}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as we}from"node:os";d();import{join as R}from"node:path";import{homedir as E}from"node:os";var l="0.5.2",me="https://matilda.maincode.com/assets/computer-use",he="https://github.com/trycua/cua/releases/download";function U(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function N(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ye(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs/v${o}/${e}`),r.push(`${he}/cua-driver-rs-v${o}/${e}`),r}function Y(e=process.env,t=l){return N("checksums.txt",e,t)}var fe="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function J(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Q(e,t=process.env){let o=J(t[fe]);return o!==void 0?o:J(e)}function ge(e=E()){return R(e,".matilda","computer-use")}function M(e=E(),t=l){return R(ge(e),`cua-driver-rs-${t}`)}function u(e=E(),t=process.platform,o=process.arch,r=l){let i=U(t,o,r);return R(M(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ye(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(we())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new K({command:this.binary,args:["mcp"],env:x()}),i=new H({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Z(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Z(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Z(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var j=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
3
+ import{Df as H,Ff as K,Ne as x,Si as V}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{i as S}from"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as G,i as X}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as d}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";d();d();d();import{homedir as we}from"node:os";d();import{join as R}from"node:path";import{homedir as E}from"node:os";var l="0.5.2",me="https://matilda.maincode.com/assets/computer-use",he="https://github.com/trycua/cua/releases/download";function U(e=process.platform,t=process.arch,o=l){let r=o;if(e==="darwin"){let n=`cua-driver-rs-${r}-${t==="arm64"?"darwin-arm64":"darwin-x86_64"}`;return{asset:`${n}.tar.gz`,extractDir:n,binaryRelPath:"CuaDriver.app/Contents/MacOS/cua-driver",hasApp:!0}}if(e==="linux"){if(t!=="x64")throw new Error(`Computer Use: unsupported Linux arch '${t}' (only x64).`);return{asset:`cua-driver-rs-${r}-linux-x86_64-binary.tar.gz`,extractDir:".",binaryRelPath:"cua-driver",hasApp:!1}}if(e==="win32"){let n=`cua-driver-rs-${r}-${t==="arm64"?"windows-arm64":"windows-x86_64"}`;return{asset:`${n}.zip`,extractDir:n,binaryRelPath:"cua-driver.exe",hasApp:!1}}throw new Error(`Computer Use: unsupported platform '${e}'.`)}function N(e,t=process.env,o=l){let r=[],i=t.MATILDA_COMPUTER_USE_DOWNLOAD_HOST;return i&&r.push(`${ye(i)}/cua-driver-rs/v${o}/${e}`),r.push(`${me}/cua-driver-rs/v${o}/${e}`),r.push(`${he}/cua-driver-rs-v${o}/${e}`),r}function Y(e=process.env,t=l){return N("checksums.txt",e,t)}var fe="MATILDA_COMPUTER_USE_MAX_IMAGE_DIMENSION";function J(e){if(e===void 0||typeof e=="string"&&e.trim()==="")return;let t=typeof e=="number"?e:Number(e);if(!(!Number.isInteger(t)||t<0))return t}function Q(e,t=process.env){let o=J(t[fe]);return o!==void 0?o:J(e)}function ge(e=E()){return R(e,".matilda","computer-use")}function M(e=E(),t=l){return R(ge(e),`cua-driver-rs-${t}`)}function u(e=E(),t=process.platform,o=process.arch,r=l){let i=U(t,o,r);return R(M(e,r),i.extractDir,i.binaryRelPath)}function h(e=l){return`cua-driver-rs@${e}`}function ye(e){return e.endsWith("/")?e.slice(0,-1):e}var f=class e{static singleton;binary;onProgress;maxImageDimension;client;startPromise;constructor(t){this.binary=t.binary,this.onProgress=t.onProgress??(()=>{}),this.maxImageDimension=t.maxImageDimension}setMaxImageDimension(t){this.maxImageDimension=t}static shared(){return e.singleton||(e.singleton=new e({binary:u(we())})),e.singleton}static setSharedForTest(t){e.singleton=t}isStarted(){return this.client!==void 0}async start(t){if(!this.client)return this.startPromise?this.startPromise:(this.startPromise=this.doStart(t).finally(()=>{this.startPromise=void 0}),this.startPromise)}async doStart(t){let o=t??this.onProgress;o("Starting Computer Use driver...");let r=new K({command:this.binary,args:["mcp"],env:x()}),i=new H({name:"matilda-code-computer-use",version:"1.0.0"},{capabilities:{}});await i.connect(r),this.client=i,await this.applyRuntimeConfig(i,o)}async applyRuntimeConfig(t,o){if(this.maxImageDimension!==void 0)try{await t.callTool({name:"set_config",arguments:{max_image_dimension:this.maxImageDimension}})}catch(r){let i=r instanceof Error?r.message:String(r);o(`Computer Use: could not apply max_image_dimension=${this.maxImageDimension} (${i}); using driver default.`)}}async listTools(){if(!this.client)throw new Error("ComputerUseClient not started");return this.client.listTools()}async callTool(t,o){if(!this.client)throw new Error("ComputerUseClient not started");try{return await this.client.callTool({name:t,arguments:o})}catch(r){if(!Z(r))throw r;let i=r;for(let n=0;n<3;n++){if(await this.stop(),await this.start(),!this.client)throw new Error("ComputerUseClient reconnect failed");try{return await this.client.callTool({name:t,arguments:o})}catch(s){if(!Z(s))throw s;i=s,await new Promise(a=>setTimeout(a,1e3))}}throw i}}async stop(){let t=this.client;if(this.client=void 0,t)try{await t.close()}catch{}}};function Z(e){let t=e instanceof Error?e.message:String(e);return/connection closed|not connected|connection refused|daemon transport error|os error 61/i.test(t)}d();var j=["bring_to_front","check_for_update","check_permissions","click","double_click","drag","end_session","get_accessibility_tree","get_agent_cursor_state","get_config","get_cursor_position","get_recording_state","get_screen_size","get_window_state","hotkey","kill_app","launch_app","list_apps","list_windows","move_cursor","page","press_key","replay_trajectory","right_click","scroll","set_agent_cursor_enabled","set_agent_cursor_motion","set_agent_cursor_style","set_config","set_value","start_recording","start_session","stop_recording","type_text","zoom"],g={bring_to_front:{description:'Activate a window so subsequent input tools with `dispatch:"foreground"` land on it without a per-call SetForegroundWindow flash. **Windows-only:** on macOS this tool returns an error pointing to the platform-native `NSRunningApplication.activate` (which the macOS input tools don\'t need because CGEvent.postToPid reaches backgrounded windows). On Linux this tool also stubs out; use `wmctrl -a` or `xdotool windowactivate` if you need explicit activation.',parameterSchema:{additionalProperties:!1,properties:{pid:{type:"integer"},window_id:{type:"integer"}},required:["pid"],type:"object"}},check_for_update:{description:"Check whether a newer cua-driver-rs release is available on GitHub. Returns the current and latest versions, an `update_available` boolean, the install one-liner, and the release notes URL. Read-only \u2014 never installs. Mirror of `cua-driver check-update --json`.",parameterSchema:{additionalProperties:!1,properties:{},type:"object"}},check_permissions:{description:"Report TCC permission status for Accessibility and Screen Recording. By default also raises the system permission dialogs for any missing grants \u2014 Apple's request APIs are no-ops when the grant is already active, so this is safe to call repeatedly. Pass {\"prompt\": false} for a purely read-only status check.\n\nReturns: `accessibility` + `screen_recording` (booleans from the TCC preflight APIs), `screen_recording_capturable` (a live ScreenCaptureKit probe \u2014 if it disagrees with `screen_recording`, the preflight grant belongs to a different process), and `source` (which TCC identity the booleans reflect: the CuaDriver daemon vs the launching terminal/IDE). macOS attributes grants to the responsible process, so a standalone call from a terminal reports the terminal's grants, not the driver's.",parameterSchema:{additionalProperties:!1,properties:{prompt:{description:"Raise the system permission prompts for missing grants. Default true.",type:"boolean"}},type:"object"}},click:{description:`Left-click against a target pid. **Prefer \`element_index\` over pixel coordinates** \u2014 element_index works on backgrounded / minimized / hidden / off-Space windows, surfaces a stable handle that survives rebuilds, and tells you what you're clicking via the cached element's role + label. Reach for \`x, y\` only when the target is a canvas / video / WebGL / custom-drawn surface that doesn't appear in the AX tree.
4
4
 
5
5
  Two addressing modes:
6
6
 
@@ -0,0 +1,3 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as a,d as b,e as c}from"./chunk-KLWMEGO4.js";import"./chunk-6RCVKDFR.js";import"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as collectContextData,c as contextCommand,b as formatContextUsageText};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as n}from"./chunk-NYEWHSBL.js";import"./chunk-TISQNFB5.js";import{g as m,i as c,p as d,q as h}from"./chunk-T4P4KEDW.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as u}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";u();var i=class extends m{constructor(e,t){super(t);this.config=e}getDescription(){return`${this.params.cron}: ${this.params.prompt}`}async getDefaultPermission(){return"ask"}async execute(){let e=this.config.getCronScheduler(),t=this.params.recurring!==!1,s=this.params.durable===!0;try{p(this.params.cron),f(this.params.cron,new Date);let r=s?await e.createDurable(this.params.cron,this.params.prompt,t):e.create(this.params.cron,this.params.prompt,t),o=y(r.cronExpr),w=`Scheduled ${r.id} (${o})${s?" [durable]":""}`,l=s?`Persisted to ${n}`:"Session-only (not written to disk, dies when Matilda exits)";return{llmContent:t?`Scheduled recurring job ${r.id} (${r.cronExpr}). ${l}. Auto-expires after 7 days. Use CronDelete to cancel sooner.`:`Scheduled one-shot task ${r.id} (${r.cronExpr}). ${l}. It will fire once then auto-delete.`,returnDisplay:w}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error creating cron job: ${o}`,returnDisplay:o,error:{message:o}}}}},g=class a extends c{constructor(e){super(a.Name,h.CRON_CREATE,`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.
3
+ import{a as p,c as f}from"./chunk-TXMXCR7D.js";import{a as y}from"./chunk-YULUB745.js";import{a as n}from"./chunk-2HTPVSGT.js";import"./chunk-TISQNFB5.js";import{g as m,i as c,p as d,q as h}from"./chunk-6E766NPX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as u}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";u();var i=class extends m{constructor(e,t){super(t);this.config=e}getDescription(){return`${this.params.cron}: ${this.params.prompt}`}async getDefaultPermission(){return"ask"}async execute(){let e=this.config.getCronScheduler(),t=this.params.recurring!==!1,s=this.params.durable===!0;try{p(this.params.cron),f(this.params.cron,new Date);let r=s?await e.createDurable(this.params.cron,this.params.prompt,t):e.create(this.params.cron,this.params.prompt,t),o=y(r.cronExpr),w=`Scheduled ${r.id} (${o})${s?" [durable]":""}`,l=s?`Persisted to ${n}`:"Session-only (not written to disk, dies when Matilda exits)";return{llmContent:t?`Scheduled recurring job ${r.id} (${r.cronExpr}). ${l}. Auto-expires after 7 days. Use CronDelete to cancel sooner.`:`Scheduled one-shot task ${r.id} (${r.cronExpr}). ${l}. It will fire once then auto-delete.`,returnDisplay:w}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error creating cron job: ${o}`,returnDisplay:o,error:{message:o}}}}},g=class a extends c{constructor(e){super(a.Name,h.CRON_CREATE,`Schedule a prompt to be enqueued at a future time. Use for both recurring schedules and one-shot reminders.
4
4
 
5
5
  Uses standard 5-field cron in the user's local timezone: minute hour day-of-month month day-of-week. "0 9 * * *" means 9am local \u2014 no timezone conversion needed.
6
6
 
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as d,f as u}from"./chunk-NYEWHSBL.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p as m,q as p}from"./chunk-T4P4KEDW.js";import"./chunk-GO2GA2GY.js";import{d as n}from"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";i();var s=class extends l{constructor(r,o){super(o);this.config=r}getDescription(){return this.params.id}async execute(){let r=this.config.getCronScheduler(),o;try{o=await r.delete(this.params.id),o||(o=await u(this.config.getProjectRoot(),[this.params.id])>0)}catch(e){let t=`Failed to cancel job ${this.params.id}: ${n(e)}`;return{llmContent:t,returnDisplay:t,error:{message:t}}}if(o){let e=`Cancelled job ${this.params.id}.`,t=`Cancelled ${this.params.id}`;return{llmContent:e,returnDisplay:t}}else{let e=`Job ${this.params.id} not found.`;return{llmContent:e,returnDisplay:e,error:{message:e}}}}},f=class a extends c{constructor(r){super(a.Name,p.CRON_DELETE,`Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store or from ${d} (durable jobs).`,"other",{type:"object",properties:{id:{type:"string",description:"Job ID returned by CronCreate."}},required:["id"],additionalProperties:!1},!0,!1,!0,!1,"cron delete cancel remove");this.config=r}static Name=m.CRON_DELETE;createInvocation(r){return new s(this.config,r)}};export{f as CronDeleteTool};
3
+ import{a as d,f as u}from"./chunk-2HTPVSGT.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p as m,q as p}from"./chunk-6E766NPX.js";import"./chunk-LUNDTQ3G.js";import{d as n}from"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as i}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";i();var s=class extends l{constructor(r,o){super(o);this.config=r}getDescription(){return this.params.id}async execute(){let r=this.config.getCronScheduler(),o;try{o=await r.delete(this.params.id),o||(o=await u(this.config.getProjectRoot(),[this.params.id])>0)}catch(e){let t=`Failed to cancel job ${this.params.id}: ${n(e)}`;return{llmContent:t,returnDisplay:t,error:{message:t}}}if(o){let e=`Cancelled job ${this.params.id}.`,t=`Cancelled ${this.params.id}`;return{llmContent:e,returnDisplay:t}}else{let e=`Job ${this.params.id} not found.`;return{llmContent:e,returnDisplay:e,error:{message:e}}}}},f=class a extends c{constructor(r){super(a.Name,p.CRON_DELETE,`Cancel a cron job previously scheduled with CronCreate. Removes it from the in-memory session store or from ${d} (durable jobs).`,"other",{type:"object",properties:{id:{type:"string",description:"Job ID returned by CronCreate."}},required:["id"],additionalProperties:!1},!0,!1,!0,!1,"cron delete cancel remove");this.config=r}static Name=m.CRON_DELETE;createInvocation(r){return new s(this.config,r)}};export{f as CronDeleteTool};
@@ -1,5 +1,5 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-NYEWHSBL.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p,q as u}from"./chunk-T4P4KEDW.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var s=class extends l{constructor(e,t){super(t);this.config=e}getDescription(){return""}async execute(){let e=this.config.getCronScheduler(),t;try{t=await g(this.config.getProjectRoot())}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error listing cron jobs: ${o}`,returnDisplay:o,error:{message:o}}}let n=[...t.map(r=>({id:r.id,cron:r.cron,prompt:r.prompt,recurring:r.recurring,durable:!0})),...e.list().filter(r=>!r.durable).map(r=>({id:r.id,cron:r.cronExpr,prompt:r.prompt,recurring:r.recurring,durable:!1}))];if(n.length===0){let r="No active cron jobs.";return{llmContent:r,returnDisplay:r}}let y=n.map(r=>{let o=r.recurring?"recurring":"one-shot",h=r.durable?"durable":"session-only";return`${r.id} \u2014 ${r.cron} (${o}) [${h}]: ${r.prompt}`}).join(`
3
+ import{a as m}from"./chunk-YULUB745.js";import{a as d,c as g}from"./chunk-2HTPVSGT.js";import"./chunk-TISQNFB5.js";import{g as l,i as c,p,q as u}from"./chunk-6E766NPX.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var s=class extends l{constructor(e,t){super(t);this.config=e}getDescription(){return""}async execute(){let e=this.config.getCronScheduler(),t;try{t=await g(this.config.getProjectRoot())}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error listing cron jobs: ${o}`,returnDisplay:o,error:{message:o}}}let n=[...t.map(r=>({id:r.id,cron:r.cron,prompt:r.prompt,recurring:r.recurring,durable:!0})),...e.list().filter(r=>!r.durable).map(r=>({id:r.id,cron:r.cronExpr,prompt:r.prompt,recurring:r.recurring,durable:!1}))];if(n.length===0){let r="No active cron jobs.";return{llmContent:r,returnDisplay:r}}let y=n.map(r=>{let o=r.recurring?"recurring":"one-shot",h=r.durable?"durable":"session-only";return`${r.id} \u2014 ${r.cron} (${o}) [${h}]: ${r.prompt}`}).join(`
4
4
  `),T=n.map(r=>`${r.id} ${m(r.cron)} [${r.durable?"durable":"session-only"}]`).join(`
5
5
  `);return{llmContent:y,returnDisplay:T}}},f=class i extends c{constructor(e){super(i.Name,u.CRON_LIST,`List all cron jobs scheduled via CronCreate, both session-only and durable (${d}).`,"other",{type:"object",properties:{},additionalProperties:!1},!0,!1,!0,!1,"cron list scheduled jobs");this.config=e}static Name=p.CRON_LIST;createInvocation(e){return new s(this.config,e)}};export{f as CronListTool};
@@ -0,0 +1,43 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as C}from"./chunk-6T2GIM76.js";import{Ce as G,Dc as X,Se as R,Te as S,Ze as K,_e as V,bf as Q,ef as Y,ha as D,ue as L,ve as q}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{Mb as j,Pa as H,ca as U,dd as B,ia as P,wc as A}from"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{w as z}from"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{i as k,p as F,q as W}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{D as T,E as I,G as v,b as x,ba as $}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";b();import*as _ from"node:fs";import*as p from"node:path";b();var re={"\u2010":"-","\u2011":"-","\u2012":"-","\u2013":"-","\u2014":"-","\u2015":"-","\u2212":"-","\u2018":"'","\u2019":"'","\u201A":"'","\u201B":"'","\u201C":'"',"\u201D":'"',"\u201E":'"',"\u201F":'"',"\xA0":" ","\u2002":" ","\u2003":" ","\u2004":" ","\u2005":" ","\u2006":" ","\u2007":" ","\u2008":" ","\u2009":" ","\u200A":" ","\u202F":" ","\u205F":" ","\u3000":" "},ue=new RegExp(`[${Object.keys(re).join("")}]`,"g");function w(n){return n.replace(ue,t=>re[t])}var he=[n=>n,n=>n.trimEnd()];function pe(n){return w(n).trimEnd()}function J(n,t,i){if(t.length===0)return 0;if(t.length>n.length)return null;e:for(let e=0;e<=n.length-t.length;e++){for(let r=0;r<t.length;r++)if(i(n[e+r])!==i(t[r]))continue e;return e}return null}function me(n){let t=n.split(`
4
+ `),i=new Array(t.length+1),e=0;for(let r=0;r<t.length;r++)i[r]=e,e+=t[r].length,r<t.length-1&&(e+=1);return i[t.length]=n.length,{lines:t,offsets:i}}function Z(n,t,i,e,r,o){if(r===0)return o?`
5
+ `:"";let l=t[e]??0,s=e+r-1,f=(t[s]??0)+(i[s]?.length??0);if(o){let g=t[e+r];g!==void 0?f=g:n.endsWith(`
6
+ `)&&(f=n.length)}return n.slice(l,f)}function _e(n,t){let{lines:i,offsets:e}=me(n),r=t.split(`
7
+ `),o=t.endsWith(`
8
+ `);if(r.length===0)return null;let l=c=>{for(let f of he){let g=J(i,c,f);if(g!==null)return g}return J(i,c,pe)},s=l(r);if(s!==null)return{slice:Z(n,e,i,s,r.length,o),removedTrailingFinalEmptyLine:!1};if(r.at(-1)===""){let c=r.slice(0,-1);if(c.length===0)return null;if(s=l(c),s!==null)return{slice:Z(n,e,i,s,c.length,!1),removedTrailingFinalEmptyLine:!0}}return null}function we(n,t){if(t==="")return null;let i=n.indexOf(t);if(i!==-1)return{slice:n.slice(i,i+t.length),removedTrailingFinalEmptyLine:!1};let e=w(n),r=w(t),o=e.indexOf(r);return o!==-1?{slice:n.slice(o,o+t.length),removedTrailingFinalEmptyLine:!1}:_e(n,t)}function Ee(n){return n.endsWith(`\r
9
+ `)?n.slice(0,-2):n.endsWith(`
10
+ `)||n.endsWith("\r")?n.slice(0,-1):n}function ye(n,t){return t?Ee(n):n}function oe(n,t,i){if(n===null||t==="")return{oldString:t,newString:i};let e=we(n,t);return e!==null?{oldString:e.slice,newString:ye(i,e.removedTrailingFinalEmptyLine)}:{oldString:t,newString:i}}function se(n,t,i){if(n===null||t===""||i!==""||t.endsWith(`
11
+ `))return t;let e=`${t}
12
+ `;return n.includes(e)?e:t}function le(n,t){if(t==="")return 0;let i=0,e=n.indexOf(t);for(;e!==-1;)i++,e=n.indexOf(t,e+t.length);return i}var Te=12,ee=300,Ce=2e6,be=4e6;function ae(n,t){if(n.length>Ce||t.trim()==="")return;let i=n.split(`
13
+ `);return xe(n,i,t)??Ne(i,t)}function te(n){return w(n).replace(/\s+/g," ").trim()}function xe(n,t,i){let e=te(i),r=te(n),o=r.indexOf(e);if(e===""||o===-1)return;let[l,s]=Se(n,[ne(r,o),ne(r,o+e.length-1)]);return[`The text is in the file, but with different whitespace (indentation, tabs or spaces, or line breaks), at lines ${l+1}-${s+1}:`,...ce(t,l,s),"Copy the whitespace exactly as shown (\u2192 is a tab, \xB7 is a leading or trailing space)."].join(`
14
+ `)}function ne(n,t){let i=0;for(let e=0;e<t;e++)n.charCodeAt(e)!==32&&i++;return i}function Se(n,t){let i=[],e=0,r=0;for(let o=0;o<n.length&&i.length<t.length;o++){let l=n.charCodeAt(o);if(l===10&&e++,!(l<128?l===32||l>=9&&l<=13:/\s/.test(n[o]))){for(;i.length<t.length&&t[i.length]===r;)i.push(e);r++}}return i}function Ne(n,t){let i=d=>w(d).trim(),e=t.trim().split(`
15
+ `).map(i),r=e.length;if(r>n.length||r*n.length>be)return;let o=new Map,l=e.map(d=>d===""?-1:(o.has(d)||o.set(d,o.size),o.get(d))),s=new Set(e.map(d=>d.length)),c=n.map(d=>{let h=d.trim();return s.has(h.length)?o.get(w(h))??-2:-2}),f=-1,g=0;for(let d=0;d+r<=c.length;d++){let h=0;for(let a=0;a<r;a++)c[d+a]===l[a]&&h++;h>g&&(g=h,f=d)}if(f===-1||g*2<r)return;let m=f+r-1;return[`The closest match is at lines ${f+1}-${m+1}, where ${g} of ${r} lines agree once leading and trailing whitespace is ignored:`,...ce(n,Math.max(0,f-1),Math.min(n.length-1,m+1)),"Copy the text exactly as shown (\u2192 is a tab, \xB7 is a leading or trailing space)."].join(`
16
+ `)}function ce(n,t,i){let e=Math.min(i,t+Te-1),r=[];for(let o=t;o<=e;o++)r.push(`${String(o+1).padStart(6)}|${Ie(n[o])}`);return e<i&&r.push(` \u2026| ${i-e} more lines`),r}function Ie(n){let t=n.length>ee,i=t?n.slice(0,ee):n,e=c=>c===" "||c===" ",r=0;for(;e(i[r]);)r++;let o=i.length;for(;!t&&o>r&&e(i[o-1]);)o--;let l=c=>c.replace(/\t/g,"\u2192").replace(/ /g,"\xB7"),s=l(i.slice(0,r))+i.slice(r,o).replace(/\t/g,"\u2192")+l(i.slice(o));return t?`${s}\u2026[${n.length-i.length} more characters not shown]`:s}var ie=4,Fe=1e3;function fe(n,t){let i=t.split(`
17
+ `),e=i.length;if(n===null)return{startLine:1,endLine:e,totalLines:e,content:t};if(n===t||!t)return null;let r=n.split(`
18
+ `),o=0,l=Math.min(r.length,i.length);for(;o<l&&r[o]===i[o];)o++;let s=r.length-1,c=i.length-1;for(;s>=o&&c>=o&&r[s]===i[c];)s--,c--;let f=o+1,g=c+1;if(g-f>Fe)return null;let m=Math.max(1,f-ie),d=Math.min(e,g+ie),h=i.slice(m-1,d);return{startLine:m,endLine:d,totalLines:e,content:h.join(`
19
+ `)}}var de=$("EDIT_PRIOR_READ");function ge(n,t,i,e){return e?i:n===null?t===""?i:"":t===""&&!e?n:G(n,t,i)}var Pe=["filePath","filepath","path","file","filename"],Ae=["oldString","oldText","old_text","previous_string","previousString"],De=["newString","newText","new_text","content"];function Le(n){if(!(typeof n.file_path=="string"&&n.file_path.trim()))for(let t of Pe){let i=n[t];if(typeof i=="string"&&i.trim()){n.file_path=i,delete n[t];break}}if(n.old_string===void 0||n.old_string===null){for(let t of Ae)if(n[t]!==void 0&&n[t]!==null){n.old_string=n[t],delete n[t];break}}if(n.new_string===void 0||n.new_string===null){for(let t of De)if(n[t]!==void 0&&n[t]!==null){n.new_string=n[t],delete n[t];break}}(n.old_string===void 0||n.old_string===null)&&typeof n.new_string=="string"&&typeof n.file_path=="string"&&n.file_path.trim()&&(n.old_string="",n.full_file_replace=!0)}var M=class{constructor(t,i){this.config=t;this.params=i}toolLocations(){return[{path:this.params.file_path}]}async calculateEdit(t){let i=t.replace_all??!1,e=null,r=await P(t.file_path),o=!1,l=t.new_string,s=t.old_string,c=0,f,g=!1,m="utf-8",d="lf";if(!this.config.getFileReadCacheDisabled()){let a=await S(this.config.getFileReadCache(),t.file_path,"editing");if(!a.ok)return{currentContent:null,newContent:"",occurrences:0,error:{display:a.displayMessage,raw:a.rawMessage,type:a.type},isNewFile:!1,encoding:"utf-8",bom:!1,lineEnding:"lf"}}if(r)try{let a=await this.config.getFileSystemService().readTextFile({path:t.file_path});a._meta?.bom!==void 0?g=a._meta.bom:g=a.content.length>0&&a.content.codePointAt(0)===65279,m=a._meta?.encoding||"utf-8",d=Q(a.content),e=a.content.replace(/\r\n/g,`
20
+ `),r=!0}catch(a){if(!x(a)||a.code!=="ENOENT")throw a;r=!1}if(r&&!this.config.getFileReadCacheDisabled()){let a=await S(this.config.getFileReadCache(),t.file_path,"editing",{expectExisting:!0});if(!a.ok)return de.warn("post-read TOCTOU rejection",{path:t.file_path,reason:a.type}),{currentContent:null,newContent:"",occurrences:0,error:{display:a.displayMessage,raw:a.rawMessage,type:a.type},isNewFile:!1,encoding:"utf-8",bom:!1,lineEnding:"lf"}}if(t.full_file_replace)o=!r,r&&e!==null?(c=1,s=e,l=t.new_string):r||(s="",l=t.new_string);else{let a=oe(e,s,l);if(s=a.oldString,l=a.newString,s===""&&!r)o=!0;else if(!r)f={display:"File not found. Cannot apply edit. Use an empty old_string to create a new file.",raw:`File not found: ${t.file_path}`,type:"file_not_found"};else if(e!==null)if(s=se(e,s,l),c=le(e,s),t.old_string==="")f={display:"Failed to edit. Attempted to create a file that already exists.",raw:`File already exists, cannot create: ${t.file_path}`,type:"attempt_to_create_existing_file"};else if(c===0){let E=ae(e,s);f={display:"Failed to edit, could not find the string to replace.",raw:`Failed to edit, 0 occurrences found for old_string in ${t.file_path}. No edits made. ${E??`The exact text in old_string was not found. Ensure you're not escaping content incorrectly and check whitespace, indentation, and context. Use ${A.Name} tool to verify.`}`,type:"edit_no_occurrence_found"}}else!i&&c>1?f={display:"Failed to edit because the text matches multiple locations. Provide more context or set replace_all to true.",raw:`Failed to edit. Found ${c} occurrences for old_string in ${t.file_path} but replace_all was not enabled.`,type:"edit_expected_occurrence_mismatch"}:s===l&&(f={display:"No changes to apply. The old_string and new_string are identical.",raw:`No changes to apply. The old_string and new_string are identical in file: ${t.file_path}`,type:"edit_no_change"});else f={display:"Failed to read content of file.",raw:`Failed to read content of existing file: ${t.file_path}`,type:"read_content_failure"}}let h=f?e??"":t.full_file_replace?t.new_string:ge(e,s,l,o);return!f&&r&&e===h&&(f={display:"No changes to apply. The new content is identical to the current content.",raw:`No changes to apply. The new content is identical to the current content in file: ${t.file_path}`,type:"edit_no_change"}),{currentContent:e,newContent:h,occurrences:c,error:f,isNewFile:o,bom:g,encoding:m,lineEnding:d}}async getDefaultPermission(){let t=this.config.getProjectRoot();return z(p.resolve(this.params.file_path),t)?"allow":"ask"}async getConfirmationDetails(t){let i=C(this.config,this.params.file_path);if(i)throw new R(i,"path_not_in_workspace");let e;try{e=await this.calculateEdit(this.params)}catch(s){if(t.aborted)throw s;let c=s instanceof Error?s.message:String(s);throw new Error(`Error preparing edit: ${c}`)}if(e.error)throw new R(e.error.raw,e.error.type);let r=p.basename(this.params.file_path),o=D(r,e.currentContent??"",e.newContent,"Current","Proposed",L);return{type:"edit",title:`Confirm Edit: ${T(I(this.params.file_path,this.config.getTargetDir()))}`,fileName:r,filePath:this.params.file_path,fileDiff:o,originalContent:e.currentContent,newContent:e.newContent,onConfirm:async s=>{s==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}getDescription(){let t=I(this.params.file_path,this.config.getTargetDir());return this.params.old_string===""?`Create ${T(t)}`:this.params.old_string===this.params.new_string?`No file changes to ${T(t)}`:T(t)}async execute(t){let i=C(this.config,this.params.file_path);if(i)return{llmContent:i,returnDisplay:i,error:{message:i,type:"path_not_in_workspace"}};let e;try{e=await this.calculateEdit(this.params)}catch(r){if(t.aborted)throw r;let o=r instanceof Error?r.message:String(r);return{llmContent:`Error preparing edit: ${o}`,returnDisplay:`Error preparing edit: ${o}`,error:{message:o,type:"edit_preparation_failure"}}}if(e.error)return{llmContent:e.error.raw,returnDisplay:`Error: ${e.error.display}`,error:{message:e.error.raw,type:e.error.type}};try{try{await this.config.getFileHistoryService().trackEdit(this.params.file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){let u=await S(this.config.getFileReadCache(),this.params.file_path,"editing",{expectExisting:!e.isNewFile});if(!u.ok)return de.warn("pre-write TOCTOU rejection",{path:this.params.file_path,reason:u.type}),{llmContent:u.rawMessage,returnDisplay:`Error: ${u.displayMessage}`,error:{message:u.rawMessage,type:u.type}}}let r=C(this.config,this.params.file_path);if(r)return{llmContent:r,returnDisplay:r,error:{message:r,type:"path_not_in_workspace"}};this.ensureParentDirectoriesExist(this.params.file_path);let o=C(this.config,this.params.file_path);if(o)return{llmContent:o,returnDisplay:o,error:{message:o,type:"path_not_in_workspace"}};if(e.isNewFile){let u=this.config.getDefaultFileEncoding(),N=!1;u===K.UTF8_BOM?N=!0:u===void 0&&(N=V(this.params.file_path)),await this.config.getFileSystemService().writeTextFile({path:this.params.file_path,content:e.newContent,_meta:{bom:N}})}else await this.config.getFileSystemService().writeTextFile({path:this.params.file_path,content:e.newContent,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}});this.params.modified_by_user||X.getInstance().recordEdit(this.params.file_path,e.currentContent,e.newContent);try{let u=_.statSync(this.params.file_path);this.config.getFileReadCache().recordWrite(this.params.file_path,u)}catch{}let l=p.basename(this.params.file_path),s=this.params.ai_proposed_content||e.newContent,c=q(l,e.currentContent??"",s,e.newContent),g={fileDiff:D(l,e.currentContent??"",e.newContent,"Current","Proposed",L),fileName:l,originalContent:e.currentContent,newContent:e.newContent,diffStat:c},m=U(this.params.file_path),d=H(this.params.file_path),h=p.extname(this.params.file_path),a=e.isNewFile?"create":"update";j(this.config,new B(O.Name,a,e.newContent.split(`
21
+ `).length,m,h,d));let E=[e.isNewFile?`Created new file: ${this.params.file_path} with provided content.`:`The file: ${this.params.file_path} has been updated.`],y=fe(e.currentContent,e.newContent);if(y){let u=`Showing lines ${y.startLine}-${y.endLine} of ${y.totalLines} from the edited file:
22
+
23
+ ---
24
+
25
+ ${y.content}`;E.push(u)}try{let u=await Y(this.config,this.params.file_path);u&&E.push(`
26
+
27
+ ${u}`)}catch{}return{llmContent:E.join(" "),returnDisplay:g}}catch(r){let o=r instanceof Error?r.message:String(r);return{llmContent:`Error executing edit: ${o}`,returnDisplay:`Error writing file: ${o}`,error:{message:o,type:"file_write_failure"}}}}ensureParentDirectoriesExist(t){let i=p.dirname(t);_.existsSync(i)||_.mkdirSync(i,{recursive:!0})}},O=class n extends k{constructor(i){super(n.Name,W.EDIT,`Replaces text within a file. By default, replaces a single occurrence. Set \`replace_all\` to true when you intend to modify every instance of \`old_string\`. This tool requires providing significant context around the change to ensure precise targeting. Always use the ${A.Name} tool to examine the file's current content before attempting a text replacement.
28
+
29
+ The user has the ability to modify the \`new_string\` content. If modified, this will be stated in the response.
30
+
31
+ Expectation for required parameters:
32
+ 1. \`file_path\` MUST be an absolute path; otherwise an error will be thrown.
33
+ 2. \`old_string\` MUST be the exact literal text to replace (including all whitespace, indentation, newlines, and surrounding code etc.). For a full-file rewrite prefer \`${F.WRITE_FILE}\`; if you omit \`old_string\` and only pass \`new_string\`, the tool overwrites the entire file.
34
+ 3. \`new_string\` MUST be the exact literal text to replace \`old_string\` with (also including all whitespace, indentation, newlines, and surrounding code etc.). Ensure the resulting code is correct and idiomatic.
35
+ 4. NEVER escape \`old_string\` or \`new_string\`, that would break the exact literal text requirement.
36
+ **Important:** If ANY of the above are not satisfied, the tool will fail. CRITICAL for \`old_string\`: Must uniquely identify the single instance to change. Include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string matches multiple locations, or does not match exactly, the tool will fail.
37
+ **Multiple replacements:** Set \`replace_all\` to true when you want to replace every occurrence that matches \`old_string\`.
38
+ **New files:** Pass an empty \`old_string\` to create a file that does not exist yet.`,"edit",{properties:{file_path:{description:"The absolute path to the file to modify. Must start with '/'.",type:"string"},old_string:{description:"The exact literal text to replace, preferably unescaped. For single replacements (default), include at least 3 lines of context BEFORE and AFTER the target text, matching whitespace and indentation precisely. If this string is not the exact literal text (i.e. you escaped it) or does not match exactly, the tool will fail. Omit only when intentionally overwriting the entire file with new_string (prefer write_file for that). Empty string creates a new file when the path does not exist.",type:"string"},new_string:{description:"The exact literal text to replace `old_string` with, preferably unescaped. Provide the EXACT text. Ensure the resulting code is correct and idiomatic.",type:"string"},replace_all:{type:"boolean",description:"Replace all occurrences of old_string (default false)."}},required:["file_path","old_string","new_string"],type:"object"});this.config=i}static Name=F.EDIT;validateToolParams(i){return Le(i),super.validateToolParams(i)}validateToolParamValues(i){return i.file_path=v(i.file_path.trim()),i.file_path?p.isAbsolute(i.file_path)?typeof i.new_string!="string"?"The 'new_string' parameter must be a string.":null:`File path must be absolute: ${i.file_path}`:"The 'file_path' parameter must be non-empty."}createInvocation(i){return new M(this.config,i)}toAutoClassifierInput(i){let e=i.old_string??"",r=i.new_string??"";return{file_path:i.file_path,old_string_preview:e.slice(0,300),new_string_preview:r.slice(0,300),old_string_truncated:e.length>300,new_string_truncated:r.length>300,lines_changed:(r.match(/\n/g)?.length??0)-(e.match(/\n/g)?.length??0)}}getModifyContext(i){return{getFilePath:e=>e.file_path,getCurrentContent:async e=>{if(await P(e.file_path))try{let{content:o}=await this.config.getFileSystemService().readTextFile({path:e.file_path});return o}catch(o){if(!x(o)||o.code!=="ENOENT")throw o;return""}else return""},getProposedContent:async e=>{if(e.full_file_replace)return e.new_string;if(_.existsSync(e.file_path))try{let{content:r}=await this.config.getFileSystemService().readTextFile({path:e.file_path});return ge(r,e.old_string,e.new_string,e.old_string===""&&r==="")}catch(r){if(!x(r)||r.code!=="ENOENT")throw r;return""}else return""},createUpdatedParams:(e,r,o)=>({...o,ai_proposed_content:e,old_string:e,new_string:r,modified_by_user:!0})}}};export{O as EditTool,ge as applyReplacement,Le as normalizeEditToolParams};
39
+ /**
40
+ * @license
41
+ * Copyright 2025 Google LLC
42
+ * SPDX-License-Identifier: Apache-2.0
43
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Yf as W,bk as T,eg as s}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as $,i as E,p as m,q as R}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{ba as b}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
3
+ import{ag as W,fk as T,ig as s}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as $,i as E,p as m,q as R}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{ba as b}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();var o=b("ENTER_WORKTREE"),P=`Creates an isolated git worktree at \`<projectRoot>/.matilda/worktrees/<slug>\` and returns its absolute path so subsequent file edits, shell commands, and other tools can operate inside it.
4
4
 
5
5
  ## When to Use
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{si as r}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as m,i as u,p as d,q as c}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{ba as p}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as l}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";l();var y=p("ENTER_PLAN_MODE"),g=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
3
+ import{wi as r}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as m,i as u,p as d,q as c}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{ba as p}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as l}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";l();var y=p("ENTER_PLAN_MODE"),g=`Use this tool to lower into plan mode before doing uncertain or complex work. Entering plan mode is a privilege reduction, so it does not require user confirmation.
4
4
 
5
5
  ## When to Use This Tool
6
6
  Use this tool when the task is not yet clear enough to safely execute, for example when it requires multi-file changes, design choices, investigation before a plan can be summarized, or when requirements are ambiguous. While investigating, if complexity rises or you find yourself repeatedly needing to ask the user, enter plan mode and consolidate a plan.
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Wf as k,Zf as W,ak as C,ck as x,eg as l}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as E,i as R,p as c,q as T}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{b as $,ba as b}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
3
+ import{_f as k,bg as W,ek as C,gk as x,ig as l}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as E,i as R,p as c,q as T}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{b as $,ba as b}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as y}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";y();import*as S from"node:fs/promises";var h=b("EXIT_WORKTREE"),O=`Exits a worktree previously created by ${c.ENTER_WORKTREE}.
4
4
 
5
5
  ## Behavior
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as S}from"./chunk-ILBTI4K5.js";import{$j as O,Mf as D,pg as F,si as b}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import{a as $}from"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as x,i as R,p as M,q as C}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{ba as y}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();v();v();var G=y("GATE_REVIEW_AGENTS");function ee(e){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
3
+ import{a as S}from"./chunk-ILBTI4K5.js";import{Pf as D,dk as O,tg as F,wi as b}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import{a as $}from"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as x,i as R,p as M,q as C}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{ba as y}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();v();v();var G=y("GATE_REVIEW_AGENTS");function ee(e){return`You are a Plan Design Reviewer for the Plan Approval Gate. Review the plan across three dimensions:
4
4
 
5
5
  1. **Request Fit** \u2014 Does the plan fulfill every part of the user's original request and respect all explicit constraints? Does it do anything the user explicitly asked NOT to do?
6
6
  2. **System Fit** \u2014 Does the plan align with the codebase structure, file paths, function names, permission model, and integration boundaries found during investigation?
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as g}from"./chunk-QH7736R5.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as d}from"./chunk-SDTWBD62.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.21.11-nightly.20261020.022e2cc37 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let f=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${f}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new p({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{p as GeminiContentGenerator,T as createGeminiContentGenerator};
3
+ import{a as g}from"./chunk-6EQMZNIY.js";import{g as u}from"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{f as d}from"./chunk-SDTWBD62.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as m}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";m();m();var p=class{googleGenAI;contentGeneratorConfig;constructor(e,t){let r=t?.customHeaders,n=r?(()=>{let i=e.httpOptions,s=i?.headers??{},l=Object.fromEntries(Object.entries(r).filter(([a])=>!d(a)));return{...e,httpOptions:{...i??{},headers:{...s,...l}}}})():e;this.googleGenAI=new u(n),this.contentGeneratorConfig=t}buildGenerateContentConfig(e){let t=this.contentGeneratorConfig?.samplingParams,r=e.config||{},n=(i,s,l)=>{let a=r[s];return i!==void 0?i:a!==void 0?a:l};return{...r,temperature:n(t?.temperature,"temperature",1),topP:n(t?.top_p,"topP",.95),topK:n(t?.top_k,"topK",64),maxOutputTokens:n(t?.max_tokens,"maxOutputTokens"),presencePenalty:n(t?.presence_penalty,"presencePenalty"),frequencyPenalty:n(t?.frequency_penalty,"frequencyPenalty"),thinkingConfig:n(this.buildThinkingConfig(),"thinkingConfig",{includeThoughts:!0,thinkingLevel:"THINKING_LEVEL_UNSPECIFIED"})}}buildThinkingConfig(){let e=this.contentGeneratorConfig?.reasoning;if(e===!1)return{includeThoughts:!1};if(e)return{includeThoughts:!0,thinkingLevel:e.effort==="low"?"LOW":e.effort==="high"||e.effort==="max"?"HIGH":"THINKING_LEVEL_UNSPECIFIED"}}async generateContent(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContent(r)}async generateContentStream(e,t){let r={...e,contents:this.stripUnsupportedFields(e.contents),config:this.buildGenerateContentConfig(e)};return this.googleGenAI.models.generateContentStream(r)}stripUnsupportedFields(e){return!e||typeof e=="string"?e:Array.isArray(e)?e.map(t=>this.stripContentFields(t)):this.stripContentFields(e)}stripContentFields(e){if(typeof e=="string")return e;if(!("role"in e)&&!("parts"in e))return this.stripPartFields(e);let t=e;return t.parts?{...t,parts:t.parts.map(r=>this.stripPartFields(r))}:t}stripPartFields(e){if(typeof e=="string")return e;let t={...e};if(t.inlineData){let{displayName:r,...n}=t.inlineData;t.inlineData=n}if(t.fileData){let{displayName:r,...n}=t.fileData;t.fileData=n}if(t.functionResponse?.parts){let r=t.functionResponse.parts.map(n=>{let i=this.convertUnsupportedMediaToText(n);return this.stripPartFields(i)});t.functionResponse={...t.functionResponse,parts:r}}return t}convertUnsupportedMediaToText(e){if(typeof e=="string")return e;let t=e.inlineData?.mimeType||"",r=e.fileData?.mimeType||"";if(t.startsWith("audio/")||t.startsWith("video/")){let n=e.inlineData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${t}${i}.`}}if(r.startsWith("audio/")||r.startsWith("video/")){let n=e.fileData?.displayName,i=n?` (${n})`:"";return{text:`Unsupported media type for Gemini: ${r}${i}.`}}return e}async countTokens(e){return this.googleGenAI.models.countTokens(e)}async embedContent(e){return this.googleGenAI.models.embedContent(e)}useSummarizedThinking(){return!0}};function T(o,e){let i={...{"User-Agent":o.userAgent||`MatildaCode/0.21.11-preview.0 (${process.platform}; ${process.arch})`}};if(e?.getUsageStatisticsEnabled()){let f=new g().getInstallationId();i={...i,"x-gemini-api-privileged-user-id":`${f}`}}let s=o.baseUrl?{headers:i,baseUrl:o.baseUrl}:{headers:i};return new p({apiKey:o.apiKey===""?void 0:o.apiKey,vertexai:o.vertexai,httpOptions:s},o)}export{p as GeminiContentGenerator,T as createGeminiContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Te as _,Ue as j}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as M,i as C,p as N,q as A}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{G as $,J as O,O as v,ba as R,d as x}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
3
+ import{We as _,Xe as j}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as M,i as C,p as N,q as A}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{G as $,J as O,O as v,ba as R,d as x}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as L}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";L();import z from"node:fs";import T from"node:path";var V=R("GLOB"),Y=100,B=2e4,W=15e3,q=500;function K(u,g,t){let e=[...u];return e.sort((r,s)=>{let c=r.mtimeMs??0,a=s.mtimeMs??0,o=g-c<t,l=g-a<t;return o&&l?a-c:o?-1:l?1:r.fullpath().localeCompare(s.fullpath())}),e}var S=class extends M{constructor(t,e){super(e);this.config=t;this.fileService=t.getFileService()}fileService;getDescription(){let t=`'${this.params.pattern}'`;return this.params.path&&(t+=` in path '${this.params.path}'`),t}async getDefaultPermission(){if(!this.params.path)return"allow";let t=this.config.getWorkspaceContext(),e=T.resolve(this.config.getTargetDir(),this.params.path);return t.isPathWithinWorkspace(e)||O(k(),e)?"allow":"ask"}async globInDirectory(t,e,r){let s=e,c=T.join(t,s);z.existsSync(c)&&(s=_(s));let a=j(s,{cwd:t,withFileTypes:!0,nodir:!0,stat:!0,nocase:!0,dot:!0,ignore:this.config.getFileExclusions().getGlobExcludes(),follow:!1,signal:r}),o=[],l=Date.now(),p=null;for await(let n of a){if(o.push(n),o.length>=B){p="count";break}if(Date.now()-l>W){p="time";break}o.length%q===0&&await new Promise(b=>setImmediate(b))}p&&a.destroy?.();let d=this.config.getTargetDir(),P=o.map(n=>T.relative(d,n.fullpath())),{filteredPaths:m}=this.fileService.filterFilesWithReport(P,this.getFileFilteringOptions()),h=n=>process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n,f=new Set(m.map(n=>h(T.resolve(d,n))));return{entries:o.filter(n=>f.has(h(n.fullpath()))),limited:p}}async execute(t){try{let e=[],r;if(this.params.path){let i=v(this.config,this.params.path,{allowExternalPaths:!0});e.push(i),r=`within ${i}`}else{let i=this.config.getWorkspaceContext().getDirectories();e.push(...i),r=i.length>1?`across ${i.length} workspace directories`:"in the workspace directory"}let s=this.params.pattern,c=[],a=new Set,o=null;for(let i of e){let{entries:F,limited:E}=await this.globInDirectory(i,s,t);E&&(o=E);for(let G of F){let I=G.fullpath();a.has(I)||(a.add(I),c.push(G))}}let l=c,p=o==="time"?`
4
4
 
5
5
  [Search stopped after ${W/1e3}s before scanning the whole tree. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:o==="count"?`
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as h,ea as k,f as b,fa as f,x as w}from"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-HYVP4472.js";import"./chunk-JXUDKX6D.js";import"./chunk-4F4DA5UI.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{g as c,i as d,p as m,q as p}from"./chunk-T4P4KEDW.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as P}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";P();function l(o,a){return typeof o!="object"||o===null||!a.some(e=>e in o)?o:Object.fromEntries(Object.entries(o).filter(([e])=>!a.includes(e)))}var G=class extends c{constructor(e,t,r,i){super(e);this.runtime=t;this.permit=r;this.lastGoal=i}getDescription(){return"Read the current goal"}async execute(e){if(!this.runtime||!this.permit)return E(this.lastGoal);let t=await x(this.runtime,this.permit,e);e.throwIfAborted();let r=y(this.runtime,this.permit);if(t.goalId!==this.permit.goalId||t.revision!==this.permit.revision)throw u();let i=C(t,r);return{llmContent:JSON.stringify(i),returnDisplay:`Active goal \xB7 revision ${t.revision}`}}},R=class o extends d{constructor(e){super(o.Name,p.GET_GOAL,`Read the current Goal: its objective, status, budget figures, and any verifier feedback. Read-only; never changes Goal state.
3
+ import{a as h,f as b,ua as k,va as f,x as w}from"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-HYVP4472.js";import"./chunk-DE3HKC2W.js";import"./chunk-4F4DA5UI.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{g as c,i as d,p as m,q as p}from"./chunk-6E766NPX.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as P}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";P();function l(o,a){return typeof o!="object"||o===null||!a.some(e=>e in o)?o:Object.fromEntries(Object.entries(o).filter(([e])=>!a.includes(e)))}var G=class extends c{constructor(e,t,r,i){super(e);this.runtime=t;this.permit=r;this.lastGoal=i}getDescription(){return"Read the current goal"}async execute(e){if(!this.runtime||!this.permit)return E(this.lastGoal);let t=await x(this.runtime,this.permit,e);e.throwIfAborted();let r=y(this.runtime,this.permit);if(t.goalId!==this.permit.goalId||t.revision!==this.permit.revision)throw u();let i=C(t,r);return{llmContent:JSON.stringify(i),returnDisplay:`Active goal \xB7 revision ${t.revision}`}}},R=class o extends d{constructor(e){super(o.Name,p.GET_GOAL,`Read the current Goal: its objective, status, budget figures, and any verifier feedback. Read-only; never changes Goal state.
4
4
 
5
5
  Outside a Goal turn it returns "active": false with "lastGoal", a summary of the session's most recent Goal. Use the result silently; do not mention the retrieval to the user.`,"read",{type:"object",properties:{},additionalProperties:!1},!0,!1,!1);this.config=e}static Name=m.GET_GOAL;build(e){return super.build(l(e,["view"]))}validateToolParams(e){return super.validateToolParams(l(e,["view"]))}createInvocation(e){let t=h.getStore(),r=t?structuredClone(t):void 0,i=r?this.config.getGoalRuntime():void 0;return new G(e,i,r,r?void 0:this.lastGoal())}lastGoal(){let e;try{e=this.config.getGoalRuntime()}catch{return}if(typeof e?.getSnapshot!="function")return;let t=e.getSnapshot().goal;if(t)return{goalId:t.goalId,revision:t.revision,status:t.status,turnCount:t.turnCount,activeTimeMs:t.activeTimeMs,tokensUsed:t.tokensUsed,...t.tokenBudget===void 0?{}:{tokenBudget:t.tokenBudget},...t.turnBudget===void 0?{}:{turnBudget:t.turnBudget},...t.activeTimeBudgetMs===void 0?{}:{activeTimeBudgetMs:t.activeTimeBudgetMs},...t.lastReason===void 0?{}:{lastReason:t.lastReason}}}};function E(o){return o?{llmContent:JSON.stringify({active:!1,lastGoal:o}),returnDisplay:`No Goal turn is permitted \xB7 last Goal ${o.status} after ${o.turnCount} ${o.turnCount===1?"turn":"turns"}`}:{llmContent:JSON.stringify({active:!1}),returnDisplay:"No active Goal is available for this turn."}}var v=class extends c{constructor(e,t,r){super(e);this.runtime=t;this.permit=r}getDescription(){return`Propose that the Goal is ${this.params.status} for this permitted turn`}async execute(e){if(!this.runtime||!this.permit)throw new Error("No active Goal is available for this turn");let t=this.permit,r=await x(this.runtime,t,e);if(e.throwIfAborted(),y(this.runtime,t),r.goalId!==this.permit.goalId||r.revision!==this.permit.revision)throw u();let i={status:this.params.status,reason:this.params.reason.trim(),...this.params.blockerKind?{blockerKind:this.params.blockerKind}:{}};e.throwIfAborted();let n=F(this.runtime,this.permit,i),T=y(this.runtime,this.permit),A={proposalRecorded:n.recorded,readyForVerification:n.readyForVerification,goalLifecycleChanged:!1,nextAction:n.readyForVerification?"End this turn without user-facing text. Do not claim the Goal is complete or blocked. The Goal status card will report the independent verification result.":"Continue this turn without claiming the Goal is complete or blocked. A repeated-blocker audit requires the same blocker mode and exact same reason text across three consecutive Goal turns, each of which must show the blocker in its own tool results."},s;return n.recorded?n.readyForVerification&&T.goal?.status==="active"?s="Proposal queued for independent verification at the turn boundary; no terminal lifecycle change was committed.":T.goal?.status==="paused"?s="Proposal recorded while the Goal is paused; no terminal lifecycle change was committed.":s="Proposal recorded for blocker audit; it is not yet ready for independent verification and no terminal lifecycle change was committed.":s="A Goal proposal is already recorded for this turn; no terminal lifecycle change was committed.",{llmContent:JSON.stringify(A),returnDisplay:s}}},S=class o extends d{constructor(e){super(o.Name,p.UPDATE_GOAL,`Propose that the current Goal is complete or blocked; an independent verifier decides and this tool never changes the Goal's status.
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{N as Y,Qj as Z,Rj as tt,Sj as et,Tj as rt,Ue as Q,Uj as st,fd as k}from"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as X}from"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import{g as J,i as q,p as z,q as K}from"./chunk-T4P4KEDW.js";import"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{G as _,J as H,N as U,O as N,b as j,ba as V,d as w}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as W}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";W();import it from"node:fs/promises";import E from"node:path";import{EOL as lt}from"node:os";import{spawn as nt}from"node:child_process";var L=V("GREP"),D=class extends J{constructor(s,i){super(i);this.config=s;this.fileExclusions=s.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let s=this.config.getWorkspaceContext(),i=E.resolve(this.config.getTargetDir(),this.params.path);return s.isPathWithinWorkspace(i)||H(X(),i)||U(this.config,i)?"allow":"ask"}async execute(s){try{let i=[],o;if(this.params.path){let t=N(this.config,this.params.path,{allowFiles:!0,allowExternalPaths:!0});i.push(t),o=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();i.push(...t),o=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let a=[];for(let t of i){let e=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:s});if(i.length>1)for(let n of e)E.isAbsolute(n.filePath)||(n.filePath=E.resolve(t,n.filePath));a.push(...e)}if(i.length>1){let t=new Set;a=a.filter(e=>{let n=`${e.filePath}:${e.lineNumber}`;return t.has(n)?!1:(t.add(n),!0)})}let c=this.params.glob?` (filter: "${this.params.glob}")`:"";if(a.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${o}${c}.`,returnDisplay:"No matches found"};let p=this.config.getTruncateToolOutputThreshold(),u=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),x=!1,h=a;a.length>u&&(h=a.slice(0,u),x=!0);let $=a.length,G=$===1?"match":"matches",v=`Found ${$} ${G} for pattern "${this.params.pattern}" ${o}${c}:
3
+ import{O as Y,Uj as Z,Vj as tt,Wj as et,Xe as Q,Xj as rt,Yj as st,hd as k}from"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as X}from"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import{g as J,i as q,p as z,q as K}from"./chunk-6E766NPX.js";import"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{G as _,J as H,N as U,O as N,b as j,ba as V,d as w}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as W}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";W();import it from"node:fs/promises";import E from"node:path";import{EOL as lt}from"node:os";import{spawn as nt}from"node:child_process";var L=V("GREP"),D=class extends J{constructor(s,i){super(i);this.config=s;this.fileExclusions=s.getFileExclusions()}fileExclusions;async getDefaultPermission(){if(!this.params.path)return"allow";let s=this.config.getWorkspaceContext(),i=E.resolve(this.config.getTargetDir(),this.params.path);return s.isPathWithinWorkspace(i)||H(X(),i)||U(this.config,i)?"allow":"ask"}async execute(s){try{let i=[],o;if(this.params.path){let t=N(this.config,this.params.path,{allowFiles:!0,allowExternalPaths:!0});i.push(t),o=`in path "${this.params.path}"`}else{let t=this.config.getWorkspaceContext().getDirectories();i.push(...t),o=t.length>1?`across ${t.length} workspace directories`:"in the workspace directory"}let a=[];for(let t of i){let e=await this.performGrepSearch({pattern:this.params.pattern,path:t,glob:this.params.glob,signal:s});if(i.length>1)for(let n of e)E.isAbsolute(n.filePath)||(n.filePath=E.resolve(t,n.filePath));a.push(...e)}if(i.length>1){let t=new Set;a=a.filter(e=>{let n=`${e.filePath}:${e.lineNumber}`;return t.has(n)?!1:(t.add(n),!0)})}let c=this.params.glob?` (filter: "${this.params.glob}")`:"";if(a.length===0)return{llmContent:`No matches found for pattern "${this.params.pattern}" ${o}${c}.`,returnDisplay:"No matches found"};let p=this.config.getTruncateToolOutputThreshold(),u=Math.min(this.config.getTruncateToolOutputLines(),this.params.limit??Number.POSITIVE_INFINITY),x=!1,h=a;a.length>u&&(h=a.slice(0,u),x=!0);let $=a.length,G=$===1?"match":"matches",v=`Found ${$} ${G} for pattern "${this.params.pattern}" ${o}${c}:
4
4
  ---
5
5
  `,T=h.reduce((t,e)=>{let n=e.filePath;return t[n]||(t[n]=[]),t[n].push(e),t[n].sort((y,F)=>y.lineNumber-F.lineNumber),t},{}),P="",M=[],C=!1,g=(t,e)=>Number.isFinite(p)&&P.length+t.length>p?(P+=t.slice(0,Math.max(p-P.length,0)),P+="...",e&&M.push(e),C=!0,!1):(P+=t,e&&M.push(e),!0);for(let t in T){if(!g(`File: ${t}
6
6
  `))break;let e=!1;for(let n of T[t]){let y=n.line.length>et?n.range??st(n.line,this.params.pattern):void 0,F=rt(n.line,y?.[0]??0,y?.[1]??0).trim();if(!g(`L${n.lineNumber}: ${F}
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as a}from"./chunk-FFFZ2QMG.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as KeychainTokenStorage};
3
+ import{b as a}from"./chunk-GTVCJCHR.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as KeychainTokenStorage};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as d}from"./chunk-RNKDFE2S.js";import{g as N}from"./chunk-ELH4YHJR.js";import{g as C,i as x,p as w,q as F}from"./chunk-T4P4KEDW.js";import{D as E,E as I,G as S,J as u,K as L,Q as R,ba as O}from"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();import y from"node:fs/promises";import s from"node:path";var A=O("LS"),U=100,T=class extends C{constructor(t,e){super(e);this.config=t}shouldIgnore(t,e){if(!e||e.length===0)return!1;for(let i of e){let a=i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");if(new RegExp(`^${a}$`).test(t))return!0}return!1}getDescription(){let t=I(this.params.path,this.config.getTargetDir());return E(t)}async getDefaultPermission(){let t=s.resolve(this.params.path),e=this.config.getWorkspaceContext(),i=this.config.storage.getUserSkillsDirs(),a=R.getUserExtensionsDir();return e.isPathWithinWorkspace(t)||L(i,t)||u(a,t)||u(N(),t)?"allow":"ask"}errorResult(t,e,i){return{llmContent:t,returnDisplay:`Error: ${e}`,error:{message:t,type:i}}}async execute(t){try{let e=await y.stat(this.params.path);if(!e)return this.errorResult(`Error: Directory not found or inaccessible: ${this.params.path}`,"Directory not found or inaccessible.","file_not_found");if(!e.isDirectory())return this.errorResult(`Error: Path is not a directory: ${this.params.path}`,"Path is not a directory.","path_is_not_a_directory");let i=await y.readdir(this.params.path);if(i.length===0)return{llmContent:`Directory ${this.params.path} is empty.`,returnDisplay:"Directory is empty."};let a=i.map(r=>s.relative(this.config.getTargetDir(),s.join(this.params.path,r))),_=this.config.getFileService(),{filteredPaths:k,gitIgnoredCount:P,matildaIgnoredCount:b}=_.filterFilesWithReport(a,{respectGitIgnore:this.params.file_filtering_options?.respect_git_ignore??this.config.getFileFilteringOptions().respectGitIgnore??d.respectGitIgnore,respectMatildaIgnore:this.params.file_filtering_options?.respect_matilda_ignore??this.config.getFileFilteringOptions().respectMatildaIgnore??d.respectMatildaIgnore}),l=[];for(let r of k){let o=s.resolve(this.config.getTargetDir(),r);if(!this.shouldIgnore(s.basename(o),this.params.ignore))try{let c=await y.stat(o),$=c.isDirectory();l.push({name:s.basename(o),path:o,isDirectory:$,size:$?0:c.size,modifiedTime:c.mtime})}catch(c){A.warn(`Error accessing ${o}: ${c}`)}}l.sort((r,o)=>r.isDirectory&&!o.isDirectory?-1:!r.isDirectory&&o.isDirectory?1:r.name.localeCompare(o.name));let p=l.length,g=Math.min(U,this.config.getTruncateToolOutputLines()),m=p>g,W=(m?l.slice(0,g):l).map(r=>`${r.isDirectory?"[DIR] ":""}${r.name}`).join(`
3
+ import{b as d}from"./chunk-RNKDFE2S.js";import{g as N}from"./chunk-PGXQZVLX.js";import{g as C,i as x,p as w,q as F}from"./chunk-6E766NPX.js";import{D as E,E as I,G as S,J as u,K as L,Q as R,ba as O}from"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as v}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";v();import y from"node:fs/promises";import s from"node:path";var A=O("LS"),U=100,T=class extends C{constructor(t,e){super(e);this.config=t}shouldIgnore(t,e){if(!e||e.length===0)return!1;for(let i of e){let a=i.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");if(new RegExp(`^${a}$`).test(t))return!0}return!1}getDescription(){let t=I(this.params.path,this.config.getTargetDir());return E(t)}async getDefaultPermission(){let t=s.resolve(this.params.path),e=this.config.getWorkspaceContext(),i=this.config.storage.getUserSkillsDirs(),a=R.getUserExtensionsDir();return e.isPathWithinWorkspace(t)||L(i,t)||u(a,t)||u(N(),t)?"allow":"ask"}errorResult(t,e,i){return{llmContent:t,returnDisplay:`Error: ${e}`,error:{message:t,type:i}}}async execute(t){try{let e=await y.stat(this.params.path);if(!e)return this.errorResult(`Error: Directory not found or inaccessible: ${this.params.path}`,"Directory not found or inaccessible.","file_not_found");if(!e.isDirectory())return this.errorResult(`Error: Path is not a directory: ${this.params.path}`,"Path is not a directory.","path_is_not_a_directory");let i=await y.readdir(this.params.path);if(i.length===0)return{llmContent:`Directory ${this.params.path} is empty.`,returnDisplay:"Directory is empty."};let a=i.map(r=>s.relative(this.config.getTargetDir(),s.join(this.params.path,r))),_=this.config.getFileService(),{filteredPaths:k,gitIgnoredCount:P,matildaIgnoredCount:b}=_.filterFilesWithReport(a,{respectGitIgnore:this.params.file_filtering_options?.respect_git_ignore??this.config.getFileFilteringOptions().respectGitIgnore??d.respectGitIgnore,respectMatildaIgnore:this.params.file_filtering_options?.respect_matilda_ignore??this.config.getFileFilteringOptions().respectMatildaIgnore??d.respectMatildaIgnore}),l=[];for(let r of k){let o=s.resolve(this.config.getTargetDir(),r);if(!this.shouldIgnore(s.basename(o),this.params.ignore))try{let c=await y.stat(o),$=c.isDirectory();l.push({name:s.basename(o),path:o,isDirectory:$,size:$?0:c.size,modifiedTime:c.mtime})}catch(c){A.warn(`Error accessing ${o}: ${c}`)}}l.sort((r,o)=>r.isDirectory&&!o.isDirectory?-1:!r.isDirectory&&o.isDirectory?1:r.name.localeCompare(o.name));let p=l.length,g=Math.min(U,this.config.getTruncateToolOutputLines()),m=p>g,W=(m?l.slice(0,g):l).map(r=>`${r.isDirectory?"[DIR] ":""}${r.name}`).join(`
4
4
  `),h=`Listed ${p} item(s) in ${this.params.path}:
5
5
  ---
6
6
  ${W}`;if(m){let r=p-g;h+=`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{g as b,i as D,p as R,q as N}from"./chunk-T4P4KEDW.js";import{G as P}from"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import{b as S}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";S();import $ from"node:path";import{fileURLToPath as L,pathToFileURL as q}from"node:url";var O=new Set(["goToDefinition","findReferences","hover","goToImplementation","prepareCallHierarchy"]),A=new Set(["documentSymbol","diagnostics"]),E=new Set(["workspaceSymbol"]),U=new Set(["incomingCalls","outgoingCalls"]),W=new Set(["codeActions"]),C=class extends b{constructor(t,e){super(e);this.config=t}getDescription(){let t=this.getOperationLabel();return this.params.operation==="workspaceSymbol"?`LSP ${t} for "${this.params.query??""}"`:this.params.operation==="documentSymbol"?this.params.filePath?`LSP ${t} for ${this.params.filePath}`:`LSP ${t}`:this.params.operation==="incomingCalls"||this.params.operation==="outgoingCalls"?`LSP ${t} for ${this.describeCallHierarchyItemShort()}`:this.params.filePath&&this.params.line!==void 0?`LSP ${t} at ${this.params.filePath}:${this.params.line}:${this.params.character??1}`:this.params.filePath?`LSP ${t} for ${this.params.filePath}`:`LSP ${t}`}async execute(t){let e=this.config.getLspClient();if(!e||!this.config.isLspEnabled()){let r=`LSP ${this.getOperationLabel()} is unavailable (LSP disabled or not initialized).`;return{llmContent:r,returnDisplay:r}}switch(this.params.operation){case"goToDefinition":return this.executeDefinitions(e);case"findReferences":return this.executeReferences(e);case"hover":return this.executeHover(e);case"documentSymbol":return this.executeDocumentSymbols(e);case"workspaceSymbol":return this.executeWorkspaceSymbols(e);case"goToImplementation":return this.executeImplementations(e);case"prepareCallHierarchy":return this.executePrepareCallHierarchy(e);case"incomingCalls":return this.executeIncomingCalls(e);case"outgoingCalls":return this.executeOutgoingCalls(e);case"diagnostics":return this.executeDiagnostics(e);case"workspaceDiagnostics":return this.executeWorkspaceDiagnostics(e);case"codeActions":return this.executeCodeActions(e);default:{let r=`Unsupported LSP operation: ${this.params.operation}`;return{llmContent:r,returnDisplay:r}}}}async executeDefinitions(t){let e=this.resolveLocationTarget();if("error"in e)return{llmContent:e.error,returnDisplay:e.error};let r=this.params.limit??20,i=[];try{i=await t.definitions(e.location,this.params.serverName,r)}catch(n){let c=`LSP go-to-definition failed: ${n?.message||String(n)}`;return{llmContent:c,returnDisplay:c}}if(!i.length){let n=`No definitions found for ${e.description}.`;return{llmContent:n,returnDisplay:n}}let s=this.config.getProjectRoot(),a=i.slice(0,r).map((n,c)=>`${c+1}. ${this.formatLocationWithServer(n,s)}`);return{llmContent:[`Definitions for ${e.description}:`,...a].join(`
3
+ import{g as b,i as D,p as R,q as N}from"./chunk-6E766NPX.js";import{G as P}from"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import{b as S}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";S();import $ from"node:path";import{fileURLToPath as L,pathToFileURL as q}from"node:url";var O=new Set(["goToDefinition","findReferences","hover","goToImplementation","prepareCallHierarchy"]),A=new Set(["documentSymbol","diagnostics"]),E=new Set(["workspaceSymbol"]),U=new Set(["incomingCalls","outgoingCalls"]),W=new Set(["codeActions"]),C=class extends b{constructor(t,e){super(e);this.config=t}getDescription(){let t=this.getOperationLabel();return this.params.operation==="workspaceSymbol"?`LSP ${t} for "${this.params.query??""}"`:this.params.operation==="documentSymbol"?this.params.filePath?`LSP ${t} for ${this.params.filePath}`:`LSP ${t}`:this.params.operation==="incomingCalls"||this.params.operation==="outgoingCalls"?`LSP ${t} for ${this.describeCallHierarchyItemShort()}`:this.params.filePath&&this.params.line!==void 0?`LSP ${t} at ${this.params.filePath}:${this.params.line}:${this.params.character??1}`:this.params.filePath?`LSP ${t} for ${this.params.filePath}`:`LSP ${t}`}async execute(t){let e=this.config.getLspClient();if(!e||!this.config.isLspEnabled()){let r=`LSP ${this.getOperationLabel()} is unavailable (LSP disabled or not initialized).`;return{llmContent:r,returnDisplay:r}}switch(this.params.operation){case"goToDefinition":return this.executeDefinitions(e);case"findReferences":return this.executeReferences(e);case"hover":return this.executeHover(e);case"documentSymbol":return this.executeDocumentSymbols(e);case"workspaceSymbol":return this.executeWorkspaceSymbols(e);case"goToImplementation":return this.executeImplementations(e);case"prepareCallHierarchy":return this.executePrepareCallHierarchy(e);case"incomingCalls":return this.executeIncomingCalls(e);case"outgoingCalls":return this.executeOutgoingCalls(e);case"diagnostics":return this.executeDiagnostics(e);case"workspaceDiagnostics":return this.executeWorkspaceDiagnostics(e);case"codeActions":return this.executeCodeActions(e);default:{let r=`Unsupported LSP operation: ${this.params.operation}`;return{llmContent:r,returnDisplay:r}}}}async executeDefinitions(t){let e=this.resolveLocationTarget();if("error"in e)return{llmContent:e.error,returnDisplay:e.error};let r=this.params.limit??20,i=[];try{i=await t.definitions(e.location,this.params.serverName,r)}catch(n){let c=`LSP go-to-definition failed: ${n?.message||String(n)}`;return{llmContent:c,returnDisplay:c}}if(!i.length){let n=`No definitions found for ${e.description}.`;return{llmContent:n,returnDisplay:n}}let s=this.config.getProjectRoot(),a=i.slice(0,r).map((n,c)=>`${c+1}. ${this.formatLocationWithServer(n,s)}`);return{llmContent:[`Definitions for ${e.description}:`,...a].join(`
4
4
  `),returnDisplay:a.join(`
5
5
  `)}}async executeImplementations(t){let e=this.resolveLocationTarget();if("error"in e)return{llmContent:e.error,returnDisplay:e.error};let r=this.params.limit??20,i=[];try{i=await t.implementations(e.location,this.params.serverName,r)}catch(n){let c=`LSP go-to-implementation failed: ${n?.message||String(n)}`;return{llmContent:c,returnDisplay:c}}if(!i.length){let n=`No implementations found for ${e.description}.`;return{llmContent:n,returnDisplay:n}}let s=this.config.getProjectRoot(),a=i.slice(0,r).map((n,c)=>`${c+1}. ${this.formatLocationWithServer(n,s)}`);return{llmContent:[`Implementations for ${e.description}:`,...a].join(`
6
6
  `),returnDisplay:a.join(`
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as t}from"./chunk-FMT6S22S.js";import"./chunk-MP6D7B5B.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import"./chunk-T4P4KEDW.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as n}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";n();function a(e,o){return new t(e,o)}export{t as MatildaAgentContentGenerator,a as createMatildaAgentContentGenerator};
3
+ import{b as t}from"./chunk-AQQOBDEP.js";import"./chunk-P3G4HEXP.js";import"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as n}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";n();function a(e,o){return new t(e,o)}export{t as MatildaAgentContentGenerator,a as createMatildaAgentContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as l,i as p}from"./chunk-QXOH5UM2.js";import"./chunk-ODZOYHIC.js";import"./chunk-7R2762AQ.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-NYEWHSBL.js";import"./chunk-QN6WSWMM.js";import"./chunk-2HQMJ2IU.js";import"./chunk-W5CGKUM4.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-SPW5DXX4.js";import"./chunk-RNKDFE2S.js";import"./chunk-GV25S54K.js";import"./chunk-5427BPR2.js";import"./chunk-47XR7IMP.js";import"./chunk-FFFZ2QMG.js";import"./chunk-SNLH42QJ.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-QH7736R5.js";import"./chunk-Y7O6DI35.js";import"./chunk-JXUDKX6D.js";import"./chunk-FMT6S22S.js";import"./chunk-GUFIMKF5.js";import"./chunk-MP6D7B5B.js";import{d as u}from"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-SUH3UUWZ.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as c}from"./chunk-SDTWBD62.js";import"./chunk-25NCTG5H.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-ELH4YHJR.js";import"./chunk-WHG6N5X2.js";import"./chunk-T4P4KEDW.js";import{c as h}from"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import{ba as d,s as i,t as a}from"./chunk-MH2P4YXC.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as s}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";s();var m=class extends p{debugLogger=d("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,n){let r=new l(t,n);super(t,n,r),this.matildaClient=e,this.sharedManager=h.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||u,n="/v1",r=t.startsWith("http")?t:`https://${t}`;return r.endsWith(n)||r.endsWith("/api/v1")||r.endsWith("/api/v1/code")?r:`${r}${n}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:n,endpoint:r}=await this.getValidToken();this.pipeline.client.apiKey=n,this.pipeline.client.baseURL=r;try{return await e()}catch(o){throw a(o)?new i:o}};try{return await t()}catch(n){if(this.isAuthError(n))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await c("retry",t);throw n}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=await this.executeWithCredentialManagement(()=>super.generateContentStream(e,t));return async function*(){try{yield*n}catch(r){throw a(r)?new i:r}}()}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e||a(e))return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),n=e,r=n?.status||n?.code;return Number(r)===403?!1:r===401||r==="401"||t.includes("unauthorized")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{m as MatildaContentGenerator};
3
+ import{a as l,i as p}from"./chunk-F62NM4KX.js";import"./chunk-GOJCMVJJ.js";import"./chunk-3WBC3IIX.js";import"./chunk-M53RP3YP.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-2HTPVSGT.js";import"./chunk-MO2HXJG5.js";import"./chunk-2MOGYHWM.js";import"./chunk-S3CWEVTS.js";import"./chunk-TISQNFB5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-WV3IUPZS.js";import"./chunk-RNKDFE2S.js";import"./chunk-WXCEBLRE.js";import"./chunk-MCQUPLRE.js";import"./chunk-47XR7IMP.js";import"./chunk-GTVCJCHR.js";import"./chunk-CZGZ3KK7.js";import"./chunk-HYVP4472.js";import"./chunk-QKYGQLWC.js";import"./chunk-6EQMZNIY.js";import"./chunk-PW3LFA6D.js";import"./chunk-DE3HKC2W.js";import"./chunk-AQQOBDEP.js";import"./chunk-YV3PUOBU.js";import"./chunk-P3G4HEXP.js";import{d as u}from"./chunk-DC7LAFZZ.js";import"./chunk-4F4DA5UI.js";import"./chunk-JCE3JAVC.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as c}from"./chunk-SDTWBD62.js";import"./chunk-JA43M5MZ.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-PGXQZVLX.js";import"./chunk-YRQP3SLC.js";import"./chunk-6E766NPX.js";import{c as h}from"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import{ba as d,s as i,t as a}from"./chunk-27Q5KW3A.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as s}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";s();var m=class extends p{debugLogger=d("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,n){let r=new l(t,n);super(t,n,r),this.matildaClient=e,this.sharedManager=h.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||u,n="/v1",r=t.startsWith("http")?t:`https://${t}`;return r.endsWith(n)||r.endsWith("/api/v1")||r.endsWith("/api/v1/code")?r:`${r}${n}`}shouldSuppressErrorLogging(e,t){return this.isAuthError(e)}async getValidToken(){try{let e=await this.sharedManager.getValidCredentials(this.matildaClient);if(!e.access_token)throw new Error("No access token available");return{token:e.access_token,endpoint:this.getCurrentEndpoint(e.resource_url)}}catch(e){throw this.isAuthError(e)?e:(this.debugLogger.warn("Failed to get token from shared manager:",e),new Error("Failed to obtain a valid legacy OAuth access token. Please re-authenticate with Matilda."))}}async executeWithCredentialManagement(e){let t=async()=>{let{token:n,endpoint:r}=await this.getValidToken();this.pipeline.client.apiKey=n,this.pipeline.client.baseURL=r;try{return await e()}catch(o){throw a(o)?new i:o}};try{return await t()}catch(n){if(this.isAuthError(n))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await c("retry",t);throw n}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){let n=await this.executeWithCredentialManagement(()=>super.generateContentStream(e,t));return async function*(){try{yield*n}catch(r){throw a(r)?new i:r}}()}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e||a(e))return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),n=e,r=n?.status||n?.code;return Number(r)===403?!1:r===401||r==="401"||t.includes("unauthorized")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("token")&&t.includes("expired")}getCurrentToken(){return this.currentToken?this.currentToken:this.sharedManager.getCurrentCredentials()?.access_token||null}clearToken(){this.currentToken=void 0,this.sharedManager.clearCache()}};export{m as MatildaContentGenerator};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i,m as j,n as k,o as l,p as m,q as n,r as o,s as p,t as q}from"./chunk-HWOQNYAO.js";import"./chunk-XCFLI3OC.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-GO2GA2GY.js";import"./chunk-MH2P4YXC.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{d as CredentialsClearRequiredError,n as MATILDA_CREDENTIAL_FILE_MODE,j as MatildaOAuth2Client,k as MatildaOAuth2Event,e as MatildaOAuthPollError,o as cacheMatildaCredentials,q as clearCachedCredentialFile,p as clearMatildaCredentials,b as generateCodeChallenge,a as generateCodeVerifier,c as generatePKCEPair,m as getMatildaOAuthClient,f as isDeviceAuthorizationSuccess,h as isDeviceTokenPending,g as isDeviceTokenSuccess,i as isErrorResponse,l as matildaOAuth2Events};
3
+ import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,k as h,l as i,m as j,n as k,o as l,p as m,q as n,r as o,s as p,t as q}from"./chunk-ZYCVL46M.js";import"./chunk-ET7ZXQ3A.js";import"./chunk-VI74YQQO.js";import"./chunk-3YLXGE6T.js";import"./chunk-LUNDTQ3G.js";import"./chunk-27Q5KW3A.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{d as CredentialsClearRequiredError,n as MATILDA_CREDENTIAL_FILE_MODE,j as MatildaOAuth2Client,k as MatildaOAuth2Event,e as MatildaOAuthPollError,o as cacheMatildaCredentials,q as clearCachedCredentialFile,p as clearMatildaCredentials,b as generateCodeChallenge,a as generateCodeVerifier,c as generatePKCEPair,m as getMatildaOAuthClient,f as isDeviceAuthorizationSuccess,h as isDeviceTokenPending,g as isDeviceTokenSuccess,i as isErrorResponse,l as matildaOAuth2Events};