@maincode-ai/matilda-code 0.21.5 → 0.21.6-nightly.20260910.566d96d64

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 (111) hide show
  1. package/chunks/agent-JCBLO7B5.js +3 -0
  2. package/chunks/agent-headless-P6ZOVAC4.js +3 -0
  3. package/chunks/{anthropicContentGenerator-EAQDRKHH.js → anthropicContentGenerator-SFJGSZHT.js} +1 -1
  4. package/chunks/{askUserQuestion-7II3GVHO.js → askUserQuestion-MJ4FTAOQ.js} +1 -1
  5. package/chunks/{chunk-VB4MJSMC.js → chunk-32PTAACU.js} +1 -1
  6. package/chunks/{chunk-OXHC3R2R.js → chunk-32T6RWWT.js} +1 -1
  7. package/chunks/{chunk-X4ML2NEE.js → chunk-5OY5RZSF.js} +1 -1
  8. package/chunks/{chunk-YTGWPLEA.js → chunk-5PMMY47S.js} +1 -1
  9. package/chunks/{chunk-BGZJUBRA.js → chunk-6B5BDE7S.js} +1 -1
  10. package/chunks/{chunk-OVC5Z3EX.js → chunk-B3NVKOSU.js} +1 -1
  11. package/chunks/{chunk-BH56I7SB.js → chunk-CG7MWHAI.js} +1 -1
  12. package/chunks/{chunk-743LSI67.js → chunk-CM3HWOOK.js} +11 -11
  13. package/chunks/chunk-EQEQPZLQ.js +8 -0
  14. package/chunks/{chunk-LNTO3FNQ.js → chunk-FRL6KOLY.js} +1 -1
  15. package/chunks/chunk-FWIVFCKF.js +8 -0
  16. package/chunks/{chunk-7LZNA4VT.js → chunk-J4OZJXSD.js} +1 -1
  17. package/chunks/{chunk-AMO6HY3T.js → chunk-KIQWWC46.js} +595 -594
  18. package/chunks/{chunk-JELJNWOF.js → chunk-KKQGIF54.js} +2 -2
  19. package/chunks/chunk-LIWYWWOK.js +8 -0
  20. package/chunks/{chunk-FQ44TPC5.js → chunk-LSDMWVW6.js} +3 -3
  21. package/chunks/chunk-LZYLZZNI.js +34 -0
  22. package/chunks/chunk-MLQWXTK6.js +34 -0
  23. package/chunks/chunk-Q2I3ARPJ.js +8 -0
  24. package/chunks/{chunk-XITA5WMN.js → chunk-QHA3ZBRO.js} +1 -1
  25. package/chunks/chunk-RJX7DK4Y.js +27 -0
  26. package/chunks/{chunk-O3OUYCSO.js → chunk-S7G6QPEP.js} +1 -1
  27. package/chunks/{chunk-46QIOR55.js → chunk-SQFBYP6N.js} +1 -1
  28. package/chunks/chunk-VLYRNOD3.js +36 -0
  29. package/chunks/chunk-VVTGOEZG.js +9 -0
  30. package/chunks/chunk-VWWEEU4V.js +9 -0
  31. package/chunks/{chunk-QZWBA3NL.js → chunk-WMPQ67GO.js} +3 -3
  32. package/chunks/chunk-XBIUAUEW.js +8 -0
  33. package/chunks/chunk-XCJYORZX.js +9 -0
  34. package/chunks/chunk-ZPQ7BBR2.js +3 -0
  35. package/chunks/{computer-use-Y37T64HM.js → computer-use-L3TVVLPW.js} +1 -1
  36. package/chunks/contextCommand-RG42M24B.js +3 -0
  37. package/chunks/{cron-create-HASFXYQL.js → cron-create-KKBZ2TLF.js} +1 -1
  38. package/chunks/{cron-delete-AW4S5IYT.js → cron-delete-PIS2HJAO.js} +1 -1
  39. package/chunks/{cron-list-U5U5GO6A.js → cron-list-STI7ZA3D.js} +1 -1
  40. package/chunks/{edit-UNGTXCQO.js → edit-DRT3G2PC.js} +1 -1
  41. package/chunks/{enter-worktree-3TAVEEPT.js → enter-worktree-CIRH2A63.js} +1 -1
  42. package/chunks/{enterPlanMode-YXMV3Y43.js → enterPlanMode-Q7KHPF7E.js} +1 -1
  43. package/chunks/{exit-worktree-NSBJWQOO.js → exit-worktree-DYLJVU2A.js} +1 -1
  44. package/chunks/{exitPlanMode-QZBHXDLX.js → exitPlanMode-S5FL2NSZ.js} +1 -1
  45. package/chunks/{geminiContentGenerator-MWV3AGI5.js → geminiContentGenerator-EEOIPEJI.js} +1 -1
  46. package/chunks/glob-NACXQ5JR.js +22 -0
  47. package/chunks/{grep-C6J3EAKZ.js → grep-BDZLAGX5.js} +1 -1
  48. package/chunks/{keychain-token-storage-5MWTIAEL.js → keychain-token-storage-HAFQQIXL.js} +1 -1
  49. package/chunks/ls-CLDNF3YS.js +15 -0
  50. package/chunks/{lsp-ELR2BGT4.js → lsp-7SKRKR5Q.js} +1 -1
  51. package/chunks/{matildaAgentContentGenerator-2E676SBT.js → matildaAgentContentGenerator-GFREHNII.js} +1 -1
  52. package/chunks/matildaContentGenerator-XZAO5ZIZ.js +8 -0
  53. package/chunks/{matildaOAuth2-5EYRIK66.js → matildaOAuth2-W2DQO2NK.js} +1 -1
  54. package/chunks/monitor-73553SNY.js +32 -0
  55. package/chunks/notebook-edit-ACVY7GLS.js +17 -0
  56. package/chunks/{openaiContentGenerator-4WFRCSV4.js → openaiContentGenerator-ZPAZTRZ3.js} +1 -1
  57. package/chunks/read-file-J5UBJYDO.js +3 -0
  58. package/chunks/ripGrep-GSG2XKMV.js +3 -0
  59. package/chunks/scheduler-RIVUK5YG.js +8 -0
  60. package/chunks/{send-message-GFPVOTSZ.js → send-message-XXRROIL7.js} +1 -1
  61. package/chunks/{serve-YVF7UBR3.js → serve-X5DL5ZWF.js} +1 -1
  62. package/chunks/shell-EVKDQKQB.js +3 -0
  63. package/chunks/{skill-6HSCMWQ4.js → skill-K2A5F5X3.js} +1 -1
  64. package/chunks/src-4B52VAKV.js +3 -0
  65. package/chunks/symbol-search-3MVTK4KV.js +19 -0
  66. package/chunks/{syntheticOutput-XKGS6F2D.js → syntheticOutput-QEUQIVQJ.js} +1 -1
  67. package/chunks/task-create-A267CAOE.js +3 -0
  68. package/chunks/{task-list-V27WHHHJ.js → task-list-OWWQLPBL.js} +1 -1
  69. package/chunks/{task-stop-NON26GAN.js → task-stop-JO3CXG2K.js} +1 -1
  70. package/chunks/{task-update-DE7CUGPY.js → task-update-TIVEADJ5.js} +1 -1
  71. package/chunks/{team-create-WNVHF2H6.js → team-create-HUK4PWDT.js} +1 -1
  72. package/chunks/team-delete-2GF5JTRL.js +8 -0
  73. package/chunks/{todoWrite-YIMKFWIL.js → todoWrite-7BZMVNBC.js} +1 -1
  74. package/chunks/{tool-search-HFOHXFK5.js → tool-search-OWJC3UTX.js} +1 -1
  75. package/chunks/{update-goal-2ZJ53Q3T.js → update-goal-6YARVWV6.js} +2 -2
  76. package/chunks/{web-fetch-EVO7GDEB.js → web-fetch-K575OWZ7.js} +1 -1
  77. package/chunks/{web-search-SJMJGGPE.js → web-search-F6JRBXFV.js} +1 -1
  78. package/chunks/{workflow-Q2MVABFH.js → workflow-JQQ3XVVE.js} +2 -2
  79. package/chunks/write-file-SBL2KGCB.js +15 -0
  80. package/cli.js +399 -396
  81. package/package.json +2 -2
  82. package/chunks/agent-3BUOSY5Q.js +0 -3
  83. package/chunks/agent-headless-NYPWOHZH.js +0 -3
  84. package/chunks/chunk-2HFKTFO5.js +0 -9
  85. package/chunks/chunk-5QAKUC2D.js +0 -14
  86. package/chunks/chunk-FW6Z25AA.js +0 -3
  87. package/chunks/chunk-KAOSSAJ7.js +0 -56
  88. package/chunks/chunk-L5ASITMV.js +0 -9
  89. package/chunks/chunk-MW3LAIJW.js +0 -8
  90. package/chunks/chunk-N6BOYL6K.js +0 -27
  91. package/chunks/chunk-RQIV43CR.js +0 -34
  92. package/chunks/chunk-SOKNPND5.js +0 -8
  93. package/chunks/chunk-SWEYYDZO.js +0 -8
  94. package/chunks/chunk-U3O6TMV7.js +0 -8
  95. package/chunks/chunk-UHDKX2CR.js +0 -8
  96. package/chunks/chunk-VBOVIARK.js +0 -9
  97. package/chunks/contextCommand-2QR4G3UT.js +0 -3
  98. package/chunks/glob-HEEVR5Z3.js +0 -22
  99. package/chunks/ls-IBIDQ5NV.js +0 -15
  100. package/chunks/matildaContentGenerator-PV6ESWMY.js +0 -8
  101. package/chunks/monitor-G7537IPA.js +0 -32
  102. package/chunks/notebook-edit-HZSJ3P7O.js +0 -17
  103. package/chunks/read-file-4TZCSTH7.js +0 -3
  104. package/chunks/ripGrep-XIBOQFPB.js +0 -3
  105. package/chunks/scheduler-OMSSFPH3.js +0 -8
  106. package/chunks/shell-UPYPV7S3.js +0 -3
  107. package/chunks/src-UQAE4MM3.js +0 -3
  108. package/chunks/symbol-search-ZV6W6DPK.js +0 -19
  109. package/chunks/task-create-T43QIG2F.js +0 -3
  110. package/chunks/team-delete-LIEVUGIX.js +0 -8
  111. package/chunks/write-file-AT6NPYC3.js +0 -15
@@ -1,27 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{c as U}from"./chunk-VBOVIARK.js";import{c as Q}from"./chunk-ESSYHTAZ.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-SWEYYDZO.js";import{M as S,Z as I}from"./chunk-5QAKUC2D.js";import{b as M}from"./chunk-GZPNIYVZ.js";M();import ie from"crypto";import q from"node:path";import{promises as b}from"node:fs";import{EventEmitter as De}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as ue}from"node:util";import{platform as he}from"node:os";import{resolve as Z}from"node:path";import{URL as me,fileURLToPath as fe}from"node:url";var ee=ue(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new me(i)}catch{throw new Error(`Invalid URL: ${i}`)}let o=e?["http:","https:","file:"]:["http:","https:"];if(!o.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${o.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(fe(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(i))throw new Error("URL contains invalid characters")}async function te(i,e={}){pe(i,e);let r=he(),t,o,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:we(n,i);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${ge(l)}. Falling back to the platform browser opener.`)}if(!N({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${i}`);return}switch(r){case"darwin":t="open",o=[i];break;case"win32":t="powershell.exe",o=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${i.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",o=[i];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,o,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[i]):await ee(d,[i],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${i}`);return}}async function re(i,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,o)=>{let n=de(i,e,r),s=!1;n.once("error",c=>{s||(s=!0,o(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function ge(i){return i instanceof Error?i.message:String(i)}function we(i,e){if(!i)return;let r=Ee(i);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(Y(r.command))return;let t=!1,o=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||o.push(e),{command:r.command,args:o}}function Ee(i){let e=[],r="",t;for(let s of i){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[o,...n]=e;if(o)return{command:o,args:n}}function Ve(){return N()}M();import H from"node:path";import{promises as y,unlinkSync as ke}from"node:fs";import{randomUUID as ne}from"node:crypto";var R=I("MATILDA_OAUTH"),_e="oauth_creds.json",Ce="oauth_creds.lock",ve=30*1e3,ye=35e3,Te=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var u=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function Re(i){if(!i||typeof i!="object")throw new Error("Invalid credentials format");let e=i,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var D=class i{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return i.instance||(i.instance=new i),i.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();ke(e)}catch{}},process.on("exit",this.cleanupFunction),process.on("SIGINT",this.cleanupFunction),process.on("SIGTERM",this.cleanupFunction),process.on("uncaughtException",this.cleanupFunction),process.on("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof u?t:new u("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<Te)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let o;return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),new Promise((n,s)=>{o=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new u("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),o=(await y.stat(r)).mtimeMs;o>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=o,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new u("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),o=JSON.parse(t),n=Re(o),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&R.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),o=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new u("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&R.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&R.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new u("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new u("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof P?(R.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new u("REFRESH_FAILED",s.message,s)):s instanceof u?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new u("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new u("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(o)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=H.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let o=JSON.stringify(e,null,2);try{await X(r,o,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new u("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ve}getCredentialFilePath(){return H.join(S.getGlobalMatildaDir(),_e)}getLockFilePath(){return H.join(S.getGlobalMatildaDir(),Ce)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:o}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>ye){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),R.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){R.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){R.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,o)}else throw new u("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new u("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&R.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),process.removeListener("SIGINT",this.cleanupFunction),process.removeListener("SIGTERM",this.cleanupFunction),process.removeListener("uncaughtException",this.cleanupFunction),process.removeListener("unhandledRejection",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var h=I("MATILDA_OAUTH"),J="https://chat.matilda.ai",Ae=`${J}/api/v1/oauth2/device/code`,j=`${J}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Fe=3e4,Se="oauth_creds.json";function Pe(){return ie.randomBytes(32).toString("base64url")}function xe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function Oe(){let i=Pe(),e=xe(i);return{code_verifier:i,code_challenge:e}}function B(i){return Object.keys(i).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&")}function W(i,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${U(i,{url:j})}`,{cause:i})}var P=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},K=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function V(i){return"device_code"in i}function Ie(i){return"access_token"in i&&i.access_token!==null&&i.access_token!==void 0&&typeof i.access_token=="string"&&i.access_token.length>0}function Le(i){return"status"in i&&i.status==="pending"}function L(i){return"error"in i}var G=class{credentials={};sharedManager;constructor(){this.sharedManager=D.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return h.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},o=await fetch(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let s=await o.text();throw new Error(`Device authorization failed: ${o.status} ${o.statusText}. Response: ${s}`)}let n=await o.json();if(V(n))h.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;h.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!V(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:be,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let n=await o.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${o.status} ${o.statusText}. Response: ${n}`);throw l.status=o.status,l}if(o.status===400&&s.error==="authorization_pending")return{status:"pending"};if(o.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new K({oauthError:s.error,description:s.error_description,status:o.status})}return await o.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Fe});h.debug("Refreshing access token...");try{let o;try{o=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(e),signal:r})}catch(a){throw W(a,r.aborted)}if(!o.ok){let a;try{a=await o.text()}catch(d){throw W(d,r.aborted)}throw o.status===400||o.status===401?(await ae(),new P("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:o.status,response:a})):new Error(`Token refresh failed: ${o.status} ${o.statusText}. Response: ${a}`)}let n;try{n=await o.text()}catch(a){throw W(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},$e=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))($e||{}),F=new De;async function wr(i,e){let r=new G,t=D.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof u)switch(o.type){case"NO_REFRESH_TOKEN":h.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":h.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":h.warn("Network error during token refresh, trying device flow");break;default:h.warn("Token manager error:",o.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await Ue(r,i);if(!n.success){n.reason==="timeout"&&F.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ne(i){let e="Legacy OAuth Device Authorization",r=i,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(f,T)=>{if(f.startsWith("http://")||f.startsWith("https://")){let v=[];for(let O=0;O<f.length;O+=T)v.push(f.substring(O,O+T));return v}let A=f.split(" "),C=[],_="";for(let v of A)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",E="|"+" ".repeat(n-2)+"|",x="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),m=c(r,s),k="Waiting for authorization to complete...";process.stderr.write(`
4
- `+w+`
5
- `),process.stderr.write(E+`
6
- `);for(let f of g)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
7
- `);process.stderr.write(E+`
8
- `);for(let f of m)process.stderr.write("| "+f+" ".repeat(s-f.length)+` |
9
- `);process.stderr.write(E+`
10
- `),process.stderr.write("| "+k+" ".repeat(s-k.length)+` |
11
- `),process.stderr.write(E+`
12
- `),process.stderr.write(x+`
13
-
14
- `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};F.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return h.debug(`
15
- `+c),F.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{F.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);h.warn(`Failed to open browser automatically: ${a}`),h.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=Oe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let E=a;throw new Error(`Device authorization failed: ${E?.error||"Unknown error"} - ${E?.error_description||"No details provided"}`)}F.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ne(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),h.debug(`Waiting for authorization...
16
- `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let E=0;E<p;E++){let x=o();if(x)return x;try{h.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let m=g,k={access_token:m.access_token,refresh_token:m.refresh_token||void 0,token_type:m.token_type,resource_url:m.resource_url,expiry_date:m.expires_in?Date.now()+m.expires_in*1e3:void 0};return i.setCredentials(k),await He(k),n("success","Authentication successful! Access token obtained."),h.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),h.debug(`
17
- Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${E+1}/${p})`),await new Promise(f=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),f();return}if(A>=d){clearInterval(C),f();return}},100)});let k=o();if(k)return k;continue}if(L(g)){let m=g;throw new Error(`Token polling failed: ${m?.error||"Unknown error"} - ${m?.error_description||"No details provided"}`)}}catch(g){let m=g instanceof Error?g.message:String(g),k=g instanceof Error?g.status:null,f=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(m.includes("Failed to cache credentials"))return f("error",m);if(m.includes("401")||k===401)return f("error","Device code expired or invalid, please restart the authorization process.");if(m.includes("429")||k===429)return f("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let A=`Error polling for token: ${m}`;n("error",A),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${U(c,{url:J})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{F.off("auth-cancel",t)}}var $=384;async function He(i,e){let r=ce();try{await b.mkdir(q.dirname(r),{recursive:!0});let t=JSON.stringify(i,null,2),o=`${r}.tmp.${process.pid}.${se()}`;try{await b.writeFile(o,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await b.chmod(o,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);h.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${o} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await b.rename(o,r)}catch(n){try{await b.unlink(o)}catch{}throw n}try{D.getInstance().clearCache()}catch(n){h.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let o=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${q.dirname(r)}\` and writing to \`${r}\`. ${o}. Please check permissions.`)}}async function ae(){try{let i=ce();await b.unlink(i),h.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;h.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{D.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var Er=ae;export{te as a,Ve as b,D as c,Pe as d,xe as e,Oe as f,P as g,K as h,V as i,Ie as j,Le as k,L as l,G as m,$e as n,F as o,wr as p,$ as q,He as r,ae as s,Er as t};
18
- /**
19
- * @license
20
- * Copyright 2025 Google LLC
21
- * SPDX-License-Identifier: Apache-2.0
22
- */
23
- /**
24
- * @license
25
- * Copyright 2025 Matilda
26
- * SPDX-License-Identifier: Apache-2.0
27
- */
@@ -1,34 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{k as C}from"./chunk-SDTWBD62.js";import{Z as p}from"./chunk-5QAKUC2D.js";import{b as g}from"./chunk-GZPNIYVZ.js";g();var u=new Map;function ge(e,t){return e===t?!0:!e||!t?!1:_(e)===_(t)}function _(e){let t={};for(let n of Object.keys(e).sort()){let o=e[n];o!==void 0&&(t[n]=o)}return JSON.stringify(t)}function v(e){return u.get(e)}function I(e,t){u.set(e,t)}function R(e){let t=u.get(e);return u.delete(e),t}function L(e,t){let n=u.get(e);if(!n)return;let o={...n,iterations:n.iterations+1,lastReason:t};return u.set(e,o),o}function fe(e,t,n){let o=u.get(e);if(!o)return;let i={...o,status:t,statusNote:t==="active"?void 0:n?.trim()||o.statusNote};return t==="active"&&delete i.statusNote,u.set(e,i),i}function M(e){return e.status??"active"}function pe(){u.clear(),b.clear(),k.clear()}var b=new Map;function me(e,t){b.set(e,t)}function w(e){b.delete(e)}function N(e,t){K(e,t);let n=b.get(e);if(n)try{n(t)}catch{}}var k=new Map;function K(e,t){k.set(e,t)}function ye(e){return k.get(e)}function Ge(e,t){if(!t){k.delete(e);return}k.set(e,t)}g();g();var A=p("ERROR_REPORT");async function j(e,t,n,o="general"){let i;e instanceof Error?i={message:e.message,stack:e.stack}:typeof e=="object"&&e!==null&&"message"in e?i={message:String(e.message)}:i={message:String(e)};let r={error:i};n&&(r.context=n);let s=`${t} [${o}]`,c;try{c=JSON.stringify(r,null,2)}catch(l){A.error(`${s} Could not stringify report content (likely due to context):`,l,e);try{c=JSON.stringify({error:i},null,2),A.error(s,c)}catch(f){A.error(`${s} Failed to stringify minimal error report:`,f,e)}return}A.error(s,c)}var h=p("GOAL_JUDGE"),q=`You are evaluating a stop-condition hook in an autonomous coding agent.
4
- Read the conversation transcript above carefully, then judge whether the
5
- user-provided condition is satisfied.
6
-
7
- Your response MUST be a JSON object with one of these shapes:
8
- - {"ok": true, "reason": "<quote evidence from the transcript that satisfies the condition>"}
9
- - {"ok": false, "reason": "<quote what is missing or what blocks the condition>"}
10
- - {"ok": false, "impossible": true, "reason": "<explain why the condition can never be satisfied>"}
11
-
12
- Always include a "reason" field, quoting specific text from the transcript
13
- whenever possible. If the transcript does not contain clear evidence that the
14
- condition is satisfied, return {"ok": false, "reason": "insufficient evidence in transcript"}.
15
- Only use {"ok": false, "impossible": true} when the condition is genuinely
16
- unachievable in this session: for example, it is self-contradictory, depends on
17
- an unavailable resource or capability, or the assistant has exhausted reasonable
18
- approaches and the transcript confirms there is no path forward. The assistant
19
- claiming the goal is impossible is evidence, not proof; independently confirm
20
- the condition is genuinely unachievable rather than deferring to the assistant's
21
- self-assessment. Do not use it just because progress is slow or evidence is
22
- currently missing. When in doubt, return {"ok": false} without "impossible".`,Y=e=>`Based on the conversation transcript above, has the following stopping condition been satisfied? Answer based on transcript evidence only.
23
- Condition JSON string: ${JSON.stringify(e)}`;var z={type:"OBJECT",properties:{ok:{type:"BOOLEAN"},reason:{type:"STRING"},impossible:{type:"BOOLEAN"}},required:["ok","reason"],additionalProperties:!1},m="Goal judge unavailable; continue working toward the goal and run `/goal clear` to stop early.",W=240;function x(e,t){j(e,"Goal judge failed",{stage:t},`goal-judge-${t}`).catch(n=>{h.debug(`Goal judge error reporting failed: ${n instanceof Error?n.message:String(n)}`)})}var X=24,y=4e3;async function H(e,t){let n=t.condition.trim();if(!n)return{ok:!1,reason:m};if(t.signal.aborted)return{ok:!1,reason:m};let o=V(e,t.lastAssistantText);o.push({role:"user",parts:[{text:Y(n)}]});let i=e.getFastModel()??e.getModel();try{let r=e.getGeminiClient(),s=await C("unknown",()=>r.generateContent(o,{systemInstruction:q,temperature:0,responseMimeType:"application/json",responseSchema:z,thinkingConfig:{thinkingBudget:0}},t.signal,i)),c=ne(s);if(!c)return h.debug("Goal judge returned empty content; defaulting to not-met"),x(new Error("Empty judge response"),"empty-response"),{ok:!1,reason:m};let l=oe(c);return l||(h.debug(`Goal judge reply not parseable as JSON (length=${c.length})`),x(new Error("Judge response was not parseable as JSON"),"parse"),{ok:!1,reason:m})}catch(r){return h.debug(`Goal judge threw: ${r instanceof Error?r.message:String(r)}`),x(r,"generate-content"),{ok:!1,reason:m}}}function V(e,t){try{let n=e.getGeminiClient();if(!n.isInitialized())return O(t);let i=n.getHistoryTail(X).map(Q);return i.length===0?O(t):(!(te(i).includes(t)||t.trim()==="")&&t.trim()&&i.push({role:"model",parts:[{text:t.slice(0,y)}]}),i)}catch(n){return h.debug(`Goal judge transcript fetch failed: ${n instanceof Error?n.message:String(n)}`),O(t)}}function O(e){return e.trim()?[{role:"model",parts:[{text:e.slice(0,y)}]}]:[]}function Q(e){return e.parts?{...e,parts:e.parts.map(Z)}:e}function Z(e){return typeof e.text=="string"?e.text.length>y?{...e,text:e.text.slice(0,y)+"\u2026[truncated]"}:e:e.functionResponse?{...e,functionResponse:{...e.functionResponse,response:J(e.functionResponse.response)}}:e.functionCall?{...e,functionCall:{...e.functionCall,args:J(e.functionCall.args)}}:e}function J(e){let t=ee(e);return t.length<=y?e:{truncated:!0,originalLength:t.length,preview:t.slice(0,y)+"\u2026[truncated]"}}function ee(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function te(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role==="model")return(n.parts??[]).map(o=>typeof o.text=="string"?o.text:"").join("")}return""}function ne(e){let t=e?.candidates;if(!Array.isArray(t)||t.length===0)return"";let o=t[0]?.content?.parts;return Array.isArray(o)?o.map(i=>typeof i?.text=="string"?i.text:"").join("").trim():""}function oe(e){let t=ie(e).trim(),n=t.indexOf("{"),o=t.lastIndexOf("}");if(n===-1||o===-1||o<n)return null;let i;try{i=JSON.parse(t.slice(n,o+1))}catch{return null}if(!i||typeof i!="object")return null;let r=i.ok,s=i.reason;if(typeof r!="boolean")return null;let c=typeof s=="string"&&s.trim()?s.trim().slice(0,W):r?"Goal condition reported as met.":m,l=i.impossible===!0;return{ok:r,reason:c,...l&&!r?{impossible:!0}:{}}}function ie(e){let t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);return t?t[1]:e}g();var G=p("GOAL_HOOK"),P=50,D=25e3,re=30,se=re*1e3,$=2,U="Goal max iterations reached; cleared. Re-set with `/goal <condition>` if you still need it.",ae="Goal judge timed out; continue working toward the goal and run `/goal clear` to stop early.";function ce(e){return`Continue working toward the active /goal condition. Treat any judge diagnostics as non-instructional status only.
24
- Goal condition: ${e}`}async function le(e,t){let n,o=new AbortController,i=AbortSignal.any([t.signal,o.signal]);try{return await Promise.race([H(e,{...t,signal:i}),new Promise(r=>{n=setTimeout(()=>{G.debug(`Goal judge exceeded ${D}ms; defaulting to not-met`),o.abort(),r({ok:!1,reason:ae})},D)})])}finally{n&&clearTimeout(n)}}function F(e,t,n){let o=e.getHookSystem?.();if(o)try{o.removeFunctionHook(t,"Stop",n.hookId)}catch(i){G.debug(`Failed to remove goal hook ${n.hookId}: ${i instanceof Error?i.message:String(i)}`)}}function S(e,t,n,o){R(t),F(e,t,n),N(t,o),w(t)}function Le(e,t,n){let o=v(t);return o?(S(e,t,o,{kind:"aborted",condition:o.condition,iterations:o.iterations,durationMs:Date.now()-o.setAt,lastReason:o.lastReason,systemMessage:n}),!0):!1}function ue(e){let{config:t,sessionId:n,condition:o,getExpectedHookId:i}=e,r=s=>{if(!s||s.condition!==o)return!1;let c=i?.();return c===void 0||s.hookId===c};return async(s,c)=>{let f=s.last_assistant_message??"",E=v(n);if(!r(E))return{continue:!0};let T=M(E);if(T==="paused"||T==="blocked")return G.debug(`Goal is ${T}; skipping auto-continue (note=${E.statusNote??""})`),{continue:!0};let B=c?.signal??new AbortController().signal,d=await le(t,{condition:o,lastAssistantText:f,signal:B}),a=v(n);return r(a)?d.ok?(S(t,n,a,{kind:"achieved",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason}),{continue:!0}):d.impossible&&a.iterations>=$?(G.debug("Goal judge ruled impossible; clearing goal.",{reason:d.reason,iterations:a.iterations}),S(t,n,a,{kind:"failed",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason}),{continue:!0}):(d.impossible&&G.debug(`Impossible goal verdict suppressed: iterations=${a.iterations} < MIN_IMPOSSIBLE_GOAL_ITERATIONS=${$}; continuing.`),a.iterations>=P?(G.debug(`Goal exceeded MAX_GOAL_ITERATIONS=${P}; clearing.`),S(t,n,a,{kind:"aborted",condition:a.condition,iterations:a.iterations,durationMs:Date.now()-a.setAt,lastReason:d.reason||a.lastReason,systemMessage:U}),{continue:!0,systemMessage:U}):(L(n,d.reason),{decision:"block",reason:ce(o)})):{continue:!0}}}function de(e,t){let n=R(t);if(w(t),!!n)return F(e,t,n),n}function Me(e){let{config:t,sessionId:n,condition:o,tokensAtStart:i}=e,r=t.getHookSystem();if(!r)throw new Error("Hook system is not initialized; cannot register /goal");de(t,n);let s={},c=ue({config:t,sessionId:n,condition:o,getExpectedHookId:()=>s.hookId}),l=r.addFunctionHook(n,"Stop","*",c,"Goal evaluator failed",{name:"goal-stop-hook",description:`Continue until: ${o}`,statusMessage:"Checking goal\u2026",timeout:se});s.hookId=l;let f={condition:o,status:"active",iterations:Math.max(0,e.initialIterations??0),setAt:Date.now(),tokensAtStart:i,hookId:l};return I(n,f),f}export{j as a,ge as b,v as c,I as d,R as e,L as f,fe as g,M as h,pe as i,me as j,w as k,N as l,ye as m,Ge as n,H as o,P as p,re as q,se as r,Le as s,ue as t,de as u,Me as v};
25
- /**
26
- * @license
27
- * Copyright 2026 Matilda Team
28
- * SPDX-License-Identifier: Apache-2.0
29
- */
30
- /**
31
- * @license
32
- * Copyright 2025 Google LLC
33
- * SPDX-License-Identifier: Apache-2.0
34
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{e as l}from"./chunk-SWEYYDZO.js";import{M as a,Z as e}from"./chunk-5QAKUC2D.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as i from"node:fs";import{randomUUID as d}from"node:crypto";import*as s from"node:path";var m=e("INSTALLATION"),o=class{getInstallationIdPath(){return a.getInstallationIdPath()}readInstallationIdFromFile(){let t=this.getInstallationIdPath();return i.existsSync(t)&&i.readFileSync(t,"utf-8").trim()||null}writeInstallationIdToFile(t){let r=this.getInstallationIdPath(),I=s.dirname(r);i.mkdirSync(I,{recursive:!0}),l(r,t,{encoding:"utf-8"})}getInstallationId(){try{let t=this.readInstallationIdFromFile();return t||(t=d(),this.writeInstallationIdToFile(t)),t}catch(t){return m.error("Error accessing installation ID file, generating ephemeral ID:",t),"123456789"}}};export{o as a};
4
- /**
5
- * @license
6
- * Copyright 2025 Google LLC
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Z as M,a as u}from"./chunk-5QAKUC2D.js";import{b as I}from"./chunk-GZPNIYVZ.js";I();import*as P from"node:crypto";import*as n from"node:fs";import*as f from"node:fs/promises";import*as O from"node:path";var C=M("ATOMIC_WRITE");async function L(t,o,e,i,w=f.rename){for(let a=0;a<=e;a++)try{await w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;await new Promise(v=>setTimeout(v,i*2**a))}}async function $(t){let e=t;for(let w=0;w<40;w++){let a;try{a=await f.lstat(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=await f.readlink(e);if(O.isAbsolute(c))e=c;else{let l=await f.realpath(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}async function B(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??f.rename,F=i?.writeFile??f.writeFile,x=i?.open??f.open,T=i?.chmod??f.chmod,A=i?.fchmod??((d,s)=>d.chmod(s)),b=i?.unlink??f.unlink,r=e?.noFollow?t:await $(t).catch(d=>{throw N(d,t)}),S;try{S=await f.stat(r)}catch(d){if(!u(d)||d.code!=="ENOENT")throw d}let W;(!e?.forceMode||e?.mode===void 0)&&(W=S!==void 0?S.mode&4095:void 0);let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=async d=>{if(y!==void 0)try{await T(d,y)}catch(s){if(!u(s)||s.code!=="ENOSYS"&&s.code!=="ENOTSUP")throw s}},h=()=>{if(S===void 0||process.platform==="win32")return!1;let d=process.geteuid?.();return d===void 0?!1:S.uid!==d};if(S!==void 0&&S.isFile()&&h()){await f.writeFile(r,o,p),await k(r);return}let m=`${r}.${P.randomBytes(6).toString("hex")}.tmp`;try{await F(m,o,p),await k(m),await L(m,r,w,a,v)}catch(d){try{await b(m)}catch{}if(u(d)&&d.code==="EXDEV")try{if(e?.noFollow){try{await b(r)}catch(g){if(!u(g)||g.code!=="ENOENT")throw g}let s=await x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),E=!1;try{try{if(await s.writeFile(typeof o=="string"?Buffer.from(o,l):o),c&&await s.sync(),y!==void 0)try{await A(s,y)}catch(g){if(!u(g)||g.code!=="ENOSYS"&&g.code!=="ENOTSUP")throw g}E=!0}finally{await s.close()}}catch(g){if(!E)try{await b(r)}catch(R){C.debug(`orphan unlink failed for ${r}:`,R)}throw g}}else await F(r,o,p),await k(r);return}catch(s){throw N(s,r)}throw N(d,r)}}function N(t,o,e="atomicWriteFile"){return t instanceof Error&&!t.message.startsWith(`${e}(`)&&(t.message=`${e}(${JSON.stringify(o)}): ${t.message}`),t}async function X(t,o,e){await B(t,JSON.stringify(o,null,2),{encoding:"utf-8",...e})}function H(t){if(t<=0)return;let o=new SharedArrayBuffer(4),e=new Int32Array(o);Atomics.wait(e,0,0,t)}function Y(t,o,e,i,w=n.renameSync){for(let a=0;a<=e;a++)try{w(t,o);return}catch(c){if(!(u(c)&&(c.code==="EPERM"||c.code==="EACCES"))||a===e)throw c;H(i*2**a)}}function D(t){let e=t;for(let w=0;w<40;w++){let a;try{a=n.lstatSync(e)}catch(l){if(u(l)&&l.code==="ENOENT")return e;throw l}if(!a.isSymbolicLink())return e;let c=n.readlinkSync(e);if(O.isAbsolute(c))e=c;else{let l=n.realpathSync(O.dirname(e));e=O.resolve(l,c)}}let i=new Error(`ELOOP: too many levels of symbolic links, resolve '${t}'`);throw i.code="ELOOP",i}function V(t,o,e,i){let w=e?.retries??3,a=e?.delayMs??50,c=e?.flush??!0,l=e?.encoding??"utf-8",v=i?.rename??n.renameSync,F=i?.writeFile??n.writeFileSync,x=i?.open??n.openSync,T=i?.chmod??n.chmodSync,A=i?.fchmod??n.fchmodSync,b=i?.unlink??n.unlinkSync,r;if(e?.noFollow)r=t;else try{r=D(t)}catch(h){throw N(h,t,"atomicWriteFileSync")}let S=`${r}.${P.randomBytes(6).toString("hex")}.tmp`,W;if(!e?.forceMode||e?.mode===void 0)try{W=n.statSync(r).mode&4095}catch(h){if(!u(h)||h.code!=="ENOENT")throw h}let y=W??e?.mode,p={};typeof o=="string"&&(p.encoding=l),c&&(p.flush=!0),y!==void 0&&(p.mode=y);let k=h=>{if(y!==void 0)try{T(h,y)}catch(m){if(!u(m)||m.code!=="ENOSYS"&&m.code!=="ENOTSUP")throw m}};try{F(S,o,p),k(S),Y(S,r,w,a,v)}catch(h){try{b(S)}catch{}if(u(h)&&h.code==="EXDEV")try{if(e?.noFollow){try{b(r)}catch(s){if(!u(s)||s.code!=="ENOENT")throw s}let m=x(r,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL,y??438),d=!1;try{try{let s=typeof o=="string"?Buffer.from(o,l):o;if(n.writeFileSync(m,s),c&&n.fsyncSync(m),y!==void 0)try{A(m,y)}catch(E){if(!u(E)||E.code!=="ENOSYS"&&E.code!=="ENOTSUP")throw E}d=!0}finally{n.closeSync(m)}}catch(s){if(!d)try{b(r)}catch(E){C.debug(`orphan unlink failed for ${r}:`,E)}throw s}}else F(r,o,p),k(r);return}catch(m){throw N(m,r,"atomicWriteFileSync")}throw N(h,r,"atomicWriteFileSync")}}export{L as a,B as b,X as c,Y as d,V as e};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda Team
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{g as w,i as x}from"./chunk-XITA5WMN.js";import{Z as I}from"./chunk-5QAKUC2D.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();m();var p=I("IMAGE_TOKENIZER"),E=class l{static PIXELS_PER_TOKEN=28*28;static MIN_TOKENS_PER_IMAGE=4;static MAX_TOKENS_PER_IMAGE=16384;static VISION_SPECIAL_TOKENS=2;async extractImageMetadata(t,e){try{if(!x(e))return p.warn(`Unsupported image format: ${e}`),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)};let n=t.replace(/^data:[^;]+;base64,/,""),r=Buffer.from(n,"base64"),i=await this.extractDimensions(r,e);return{width:i.width,height:i.height,mimeType:e,dataSize:r.length}}catch(n){return p.warn("Failed to extract image metadata:",n),{width:512,height:512,mimeType:e,dataSize:Math.floor(t.length*.75)}}}async extractDimensions(t,e){return e.includes("png")?this.extractPngDimensions(t):e.includes("jpeg")||e.includes("jpg")?this.extractJpegDimensions(t):e.includes("webp")?this.extractWebpDimensions(t):e.includes("gif")?this.extractGifDimensions(t):e.includes("bmp")?this.extractBmpDimensions(t):e.includes("tiff")?this.extractTiffDimensions(t):e.includes("heic")?this.extractHeicDimensions(t):{width:512,height:512}}extractPngDimensions(t){if(t.length<24)throw new Error("Invalid PNG: buffer too short");let e=t.subarray(0,8),n=Buffer.from([137,80,78,71,13,10,26,10]);if(!e.equals(n))throw new Error("Invalid PNG signature");let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}extractJpegDimensions(t){if(t.length<4||t[0]!==255||t[1]!==216)throw new Error("Invalid JPEG signature");let e=2;for(;e<t.length-8;){if(t[e]!==255){e++;continue}let n=t[e+1];if(n>=192&&n<=195||n>=197&&n<=199||n>=201&&n<=203||n>=205&&n<=207){let i=t.readUInt16BE(e+5);return{width:t.readUInt16BE(e+7),height:i}}let r=t.readUInt16BE(e+2);e+=2+r}throw new Error("Could not find JPEG dimensions")}extractWebpDimensions(t){if(t.length<30)throw new Error("Invalid WebP: too short");let e=t.subarray(0,4).toString("ascii"),n=t.subarray(8,12).toString("ascii");if(e!=="RIFF"||n!=="WEBP")throw new Error("Invalid WebP signature");let r=t.subarray(12,16).toString("ascii");if(r==="VP8 "){let i=t.readUInt16LE(26)&16383,a=t.readUInt16LE(28)&16383;return{width:i,height:a}}else if(r==="VP8L"){let i=t.readUInt32LE(21),a=(i&16383)+1,s=(i>>14&16383)+1;return{width:a,height:s}}else if(r==="VP8X"){let i=(t.readUInt32LE(24)&16777215)+1,a=(t.readUInt32LE(26)&16777215)+1;return{width:i,height:a}}throw new Error("Unsupported WebP format")}extractGifDimensions(t){if(t.length<10)throw new Error("Invalid GIF: too short");let e=t.subarray(0,6).toString("ascii");if(e!=="GIF87a"&&e!=="GIF89a")throw new Error("Invalid GIF signature");let n=t.readUInt16LE(6),r=t.readUInt16LE(8);return{width:n,height:r}}calculateTokens(t){return this.calculateTokensWithScaling(t.width,t.height)}calculateTokensWithScaling(t,e){let n=Math.round(e/28)*28,r=Math.round(t/28)*28,i=l.MIN_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN,a=l.MAX_TOKENS_PER_IMAGE*l.PIXELS_PER_TOKEN;if(n*r>a){let o=Math.sqrt(e*t/a);n=Math.floor(e/o/28)*28,r=Math.floor(t/o/28)*28}else if(n*r<i){let o=Math.sqrt(i/(e*t));n=Math.ceil(e*o/28)*28,r=Math.ceil(t*o/28)*28}return Math.floor(n*r/l.PIXELS_PER_TOKEN)+l.VISION_SPECIAL_TOKENS}async calculateTokensBatch(t){let e=[];for(let{data:n,mimeType:r}of t)try{let i=await this.extractImageMetadata(n,r);e.push(this.calculateTokens(i))}catch(i){p.warn("Error calculating tokens for image:",i),e.push(l.MIN_TOKENS_PER_IMAGE+l.VISION_SPECIAL_TOKENS)}return e}extractBmpDimensions(t){if(t.length<26)throw new Error("Invalid BMP: buffer too short");if(t[0]!==66||t[1]!==77)throw new Error("Invalid BMP signature");let e=t.readUInt32LE(18),n=t.readUInt32LE(22);return{width:e,height:Math.abs(n)}}extractTiffDimensions(t){if(t.length<8)throw new Error("Invalid TIFF: buffer too short");let e=t.subarray(0,2).toString("ascii"),n=e==="II";if(!n&&!(e==="MM"))throw new Error("Invalid TIFF byte order");if((n?t.readUInt16LE(2):t.readUInt16BE(2))!==42)throw new Error("Invalid TIFF magic number");let a=n?t.readUInt32LE(4):t.readUInt32BE(4);if(a>=t.length)throw new Error("Invalid TIFF IFD offset");let s=n?t.readUInt16LE(a):t.readUInt16BE(a),o=0,h=0;for(let g=0;g<s;g++){let c=a+2+g*12;if(c+12>t.length)break;let u=n?t.readUInt16LE(c):t.readUInt16BE(c),f=(n?t.readUInt16LE(c+2):t.readUInt16BE(c+2))===3?n?t.readUInt16LE(c+8):t.readUInt16BE(c+8):n?t.readUInt32LE(c+8):t.readUInt32BE(c+8);if(u===256?o=f:u===257&&(h=f),o>0&&h>0)break}if(o===0||h===0)throw new Error("Could not find TIFF dimensions");return{width:o,height:h}}extractHeicDimensions(t){if(t.length<12)throw new Error("Invalid HEIC: buffer too short");if(t.subarray(4,8).toString("ascii")!=="ftyp")throw new Error("Invalid HEIC: missing ftyp box");let n=t.subarray(8,12).toString("ascii");if(!["heic","heix","hevc","hevx"].includes(n))throw new Error("Invalid HEIC brand");let r=0;for(;r<t.length-8;){let i=t.readUInt32BE(r);if(t.subarray(r+4,r+8).toString("ascii")==="meta"){let o=r+8+4;for(;o<r+i-8;){let h=t.readUInt32BE(o);if(t.subarray(o+4,o+8).toString("ascii")==="ispe"&&o+20<=t.length){let c=t.readUInt32BE(o+12),u=t.readUInt32BE(o+16);return{width:c,height:u}}if(h===0)break;o+=h}}if(i===0)break;r+=i}return p.warn("Could not extract HEIC dimensions, using default"),{width:512,height:512}}};var d=I("TOKENIZER"),T=class{textTokenizer;imageTokenizer;constructor(){this.textTokenizer=new w,this.imageTokenizer=new E}async calculateTokens(t){let e=performance.now();try{let{textContents:n,imageContents:r,audioContents:i,otherContents:a}=this.processAndGroupContents(t);if(n.length===0&&r.length===0&&i.length===0&&a.length===0)return{totalTokens:0,breakdown:{textTokens:0,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e};let s=await this.calculateTextTokens(n),o=await this.calculateImageTokens(r),h=await this.calculateAudioTokens(i),g=await this.calculateOtherTokens(a),c=s+o+h+g,u=performance.now()-e;return{totalTokens:c,breakdown:{textTokens:s,imageTokens:o,audioTokens:h,otherTokens:g},processingTime:u}}catch(n){d.error("Error calculating tokens:",n);let r=this.calculateFallbackTokens(t);return{totalTokens:r,breakdown:{textTokens:r,imageTokens:0,audioTokens:0,otherTokens:0},processingTime:performance.now()-e}}}async calculateTextTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating text tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}async calculateImageTokens(t){if(t.length===0)return 0;try{return(await this.imageTokenizer.calculateTokensBatch(t)).reduce((n,r)=>n+r,0)}catch(e){return d.warn("Error calculating image tokens:",e),t.length*6}}async calculateAudioTokens(t){if(t.length===0)return 0;let e=0;for(let n of t)try{let r=Math.floor(n.data.length*.75);e+=Math.max(Math.ceil(r/100),10)}catch(r){d.warn("Error calculating audio tokens:",r),e+=10}return e}async calculateOtherTokens(t){if(t.length===0)return 0;try{return await this.textTokenizer.calculateTokens(t.join(""))}catch(e){d.warn("Error calculating other content tokens:",e);let n=t.join("").length;return Math.ceil(n/4)}}calculateFallbackTokens(t){try{let e=JSON.stringify(t.contents);return Math.ceil(e.length/4)}catch(e){return d.warn("Error in fallback token calculation:",e),100}}processAndGroupContents(t){let e=[],n=[],r=[],i=[];if(!t.contents)return{textContents:e,imageContents:n,audioContents:r,otherContents:i};let a=Array.isArray(t.contents)?t.contents:[t.contents];for(let s of a)this.processContent(s,e,n,r,i);return{textContents:e,imageContents:n,audioContents:r,otherContents:i}}processContent(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("parts"in t&&t.parts){for(let a of t.parts)this.processPart(a,e,n,r,i);return}this.processPart(t,e,n,r,i)}processPart(t,e,n,r,i){if(typeof t=="string"){t.trim()&&e.push(t);return}if("text"in t&&t.text){e.push(t.text);return}if("inlineData"in t&&t.inlineData){let{data:a,mimeType:s}=t.inlineData;if(s&&s.startsWith("image/")){n.push({data:a||"",mimeType:s});return}if(s&&s.startsWith("audio/")){r.push({data:a||"",mimeType:s});return}}if("fileData"in t&&t.fileData){i.push(JSON.stringify(t.fileData));return}if("functionCall"in t&&t.functionCall){i.push(JSON.stringify(t.functionCall));return}if("functionResponse"in t&&t.functionResponse){i.push(JSON.stringify(t.functionResponse));return}try{let a=JSON.stringify(t);a&&a!=="{}"&&i.push(a)}catch(a){d.warn("Failed to serialize unknown part type:",a)}}};m();export{T as a};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{e as T,v as X}from"./chunk-X4ML2NEE.js";import{b as P}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-SWEYYDZO.js";import{Z as $,a as l}from"./chunk-5QAKUC2D.js";import{b as _}from"./chunk-GZPNIYVZ.js";import{f as W}from"./chunk-OWGSC52X.js";_();var R=W(X(),1);import*as d from"node:fs/promises";import{constants as B}from"node:fs";import*as b from"node:path";var f=$("AGENTS_TEAM_TASKS"),v=32768,A=16;function C(r){if(!r)return;let e=Buffer.byteLength(JSON.stringify(r),"utf-8");if(e>v)throw new Error(`Task metadata is too large (${e} bytes; max ${v}). Trim the payload or store the bulk content elsewhere.`)}var K={retries:{retries:30,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:r=>{f.warn("task lock compromised:",r?.message??r)}},j=new Map;function q(r){let e=j.get(r);return e||(e=new P,j.set(r,e)),e}async function h(r,e,t){return q(r).runExclusive(async()=>{let a;try{a=await R.default.lock(r,K)}catch(o){if(l(o)&&o.code==="ENOENT")return t();throw o}try{return await e()}finally{await a()}})}var z="__reciprocal__",L=new Map;function Y(r){let e=L.get(r);return e||(e=new P,L.set(r,e)),e}function G(r){if(!/^[1-9]\d*$/.test(r))throw new Error(`Invalid task ID "${r}". Task IDs must be positive integers.`)}function m(r,e){return G(e),b.join(T(r),`${e}.json`)}var O=new Set;function ie(r){return O.add(r),()=>{O.delete(r)}}function k(r){for(let e of O)try{e(r)}catch(t){f.warn(`task update listener failed: ${t}`)}}async function oe(r,e){C(e.metadata);let t=T(r);await d.mkdir(t,{recursive:!0});let a=15;for(let o=0;o<a;o++){let c=await I(t),s={id:c,subject:e.subject,description:e.description,activeForm:e.activeForm,owner:e.owner,status:"pending",blocks:[],blockedBy:[],metadata:e.metadata},n=b.join(t,`${c}.json`);try{await(await d.open(n,B.O_WRONLY|B.O_CREAT|B.O_EXCL)).close()}catch(i){if(l(i)&&i.code==="EEXIST")continue;throw i}try{await g(n,s)}catch(i){throw await d.unlink(n).catch(()=>{}),i}return k(r),s}throw new Error(`Failed to create task after ${a} attempts (ID contention).`)}async function ce(r,e){let t=m(r,e);try{let a=await d.readFile(t,"utf-8");return JSON.parse(a)}catch(a){if(l(a)&&a.code==="ENOENT")return;throw a}}var p=class extends Error{constructor(t,a,o){super(`Task #${t} is owned by "${o}". Only the leader or the owner can change status / owner / subject / description / blocks.`);this.taskId=t;this.callerName=a;this.actualOwner=o;this.name="TaskOwnershipError"}};async function F(r,e,t,a){let o=m(r,e);return h(o,async()=>{let c;try{c=await d.readFile(o,"utf-8")}catch(n){if(l(n)&&n.code==="ENOENT")return;throw n}let s=JSON.parse(c);if(a?.callerName!==void 0&&a.callerName!==z&&(t.status!==void 0||t.owner!==void 0||t.subject!==void 0||t.description!==void 0||(t.addBlocks?.length??0)>0||(t.addBlockedBy?.length??0)>0)&&s.owner&&s.owner!==a.callerName)throw new p(e,a.callerName,s.owner);if(t.addBlocks?.length){let n=new Set(s.blocks);for(let i of t.addBlocks)n.add(i);s.blocks=Array.from(n)}if(t.addBlockedBy?.length){let n=new Set(s.blockedBy);for(let i of t.addBlockedBy)n.add(i);s.blockedBy=Array.from(n)}if(t.status!==void 0&&(s.status=t.status,t.status==="completed"&&s.blocks.length>0&&await V(r,e,s.blocks)),t.owner!==void 0&&(s.owner=t.owner?t.owner:void 0),t.subject!==void 0&&(s.subject=t.subject),t.description!==void 0&&(s.description=t.description),t.activeForm!==void 0&&(s.activeForm=t.activeForm??void 0),t.metadata!==void 0){s.metadata=s.metadata??{};for(let[n,i]of Object.entries(t.metadata))n==="__proto__"||n==="constructor"||n==="prototype"||(i===null?delete s.metadata[n]:s.metadata[n]=i);Object.keys(s.metadata).length===0&&(s.metadata=void 0),C(s.metadata)}return await g(o,s),k(r),s},()=>{})}async function de(r,e,t){let a=m(r,e),o=await h(a,async()=>{let s;try{let i=await d.readFile(a,"utf-8");s=JSON.parse(i)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}if(t?.callerName!==void 0&&s.owner&&s.owner!==t.callerName)throw new p(e,t.callerName,s.owner);let n=new Set([...s.blocks,...s.blockedBy]);n.delete(e);try{await d.unlink(a)}catch(i){if(l(i)&&i.code==="ENOENT")return null;throw i}return n},()=>null);if(o===null)return!1;let c=await Promise.allSettled(Array.from(o).map(s=>Q(r,s,e)));for(let s of c)s.status==="rejected"&&f.warn(`deleteTask(${e}): edge cleanup failed: ${s.reason}`);return k(r),!0}async function Q(r,e,t){let a=m(r,e);await h(a,async()=>{try{let o=await d.readFile(a,"utf-8"),c=JSON.parse(o),s=c.blocks.length,n=c.blockedBy.length;if(c.blocks=c.blocks.filter(i=>i!==t),c.blockedBy=c.blockedBy.filter(i=>i!==t),c.blocks.length===s&&c.blockedBy.length===n)return;await g(a,c)}catch(o){if(l(o)&&o.code==="ENOENT")return;throw o}},()=>{})}async function x(r,e){let t=T(r),a;try{a=await d.readdir(t)}catch(n){if(l(n)&&n.code==="ENOENT")return[];let i=n instanceof Error?n.message:String(n);throw f.warn(`Failed to list tasks dir ${t}: ${i}`),n instanceof Error?n:new Error(i)}let o=a.filter(n=>n.endsWith(".json")),c=[];for(let n=0;n<o.length;n+=A){let i=o.slice(n,n+A),w=await Promise.all(i.map(async D=>{let y=b.join(t,D),S;try{S=await d.readFile(y,"utf-8")}catch(u){if(l(u)&&u.code==="ENOENT")return;let E=u instanceof Error?u.message:String(u);f.warn(`Failed to read task file ${y}: ${E}`);return}if(S.trim()!=="")try{return JSON.parse(S)}catch(u){let E=u instanceof Error?u.message:String(u);f.warn(`Quarantining corrupt task file ${y}: ${E}`);let J=`${y}.corrupt-${Date.now()}`;try{await d.rename(y,J)}catch(N){let U=N instanceof Error?N.message:String(N);f.warn(`Failed to quarantine ${y}: ${U}`)}return}}));c.push(...w)}let s=c.filter(n=>n!==void 0);return s.sort((n,i)=>Number(n.id)-Number(i.id)),e?s.filter(n=>!(e.status!==void 0&&n.status!==e.status||e.owner!==void 0&&n.owner!==e.owner||e.blockedBy!==void 0&&!n.blockedBy.includes(e.blockedBy))):s}async function le(r){let e=T(r);await d.rm(e,{recursive:!0,force:!0}),k(r)}async function V(r,e,t){let a=await Promise.allSettled(t.map(async o=>{let c=m(r,o);await h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(w){if(l(w)&&w.code==="ENOENT")return;throw w}let n=JSON.parse(s),i=n.blockedBy.length;n.blockedBy=n.blockedBy.filter(w=>w!==e),n.blockedBy.length!==i&&await g(c,n)},()=>{})}));for(let o of a)o.status==="rejected"&&f.warn(`unblockDependents(${e}): ${o.reason}`);k(r)}async function ue(r,e,t){await F(r,e,{addBlocks:[t]}),await F(r,t,{addBlockedBy:[e]})}async function fe(r,e,t,a){return a?.checkAgentBusy?Y(t).runExclusive(()=>M(r,e,t,a,!0)):M(r,e,t,a,!1)}async function M(r,e,t,a,o){if(o&&await H(r,t))return;let c=m(r,e);return h(c,async()=>{let s;try{s=await d.readFile(c,"utf-8")}catch(i){if(l(i)&&i.code==="ENOENT")return;throw i}let n=JSON.parse(s);if(n.status==="pending"&&!n.owner)return n.owner=a?.ownerName??t,n.status="in_progress",await g(c,n),k(r),n},()=>{})}async function H(r,e){let t=await x(r,{status:"in_progress"}),a=e.split("@")[0];return t.some(o=>o.owner===e||o.owner===a)}async function Z(r,e,t){let a=m(r,e);return h(a,async()=>{let o;try{o=await d.readFile(a,"utf-8")}catch(s){if(l(s)&&s.code==="ENOENT")return!1;throw s}let c=JSON.parse(o);return c.status!=="in_progress"||c.owner!==t?!1:(c.owner=void 0,c.status="pending",await g(a,c),!0)},()=>!1)}async function we(r,e){let t=e.split("@")[0],o=(await x(r,{status:"in_progress"})).filter(i=>i.owner===e||i.owner===t),c=await Promise.allSettled(o.map(i=>Z(r,i.id,i.owner))),s=c.filter(i=>i.status==="rejected");s.length>0&&f.warn(`unassignTeammateTasks: ${s.length}/${o.length} task(s) failed to unassign for ${e}`);let n=c.filter(i=>i.status==="fulfilled"&&i.value===!0).length;return n>0&&k(r),n}async function ge(r){let e=await x(r),t=new Map;for(let a of e){if(!a.owner)continue;let o=t.get(a.owner)??{inProgress:0,completed:0};a.status==="in_progress"?o.inProgress++:a.status==="completed"&&o.completed++,t.set(a.owner,o)}return t}async function I(r){let e;try{e=await d.readdir(r)}catch{return"1"}let t=0;for(let a of e){if(!a.endsWith(".json"))continue;let o=parseInt(a.replace(".json",""),10);!isNaN(o)&&o>t&&(t=o)}return String(t+1)}export{z as a,G as b,m as c,ie as d,k as e,oe as f,ce as g,p as h,F as i,de as j,x as k,le as l,ue as m,fe as n,Z as o,we as p,ge as q};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,9 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a,c}from"./chunk-5QAKUC2D.js";import{b as E}from"./chunk-GZPNIYVZ.js";E();import{URL as g}from"node:url";var l=[/^10\./,/^127\./,/^172\.(1[6-9]|2[0-9]|3[0-1])\./,/^192\.168\./,/^::1$/,/^fc00:/,/^fe80:/],f=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID"]),T=new Set([...f,"ECONNRESET","ETIMEDOUT","ECONNREFUSED","ENOTFOUND","EAI_AGAIN","EHOSTUNREACH","ENETUNREACH"]),u=class extends Error{constructor(t,o){super(t);this.code=o;this.name="FetchError"}};function S(n){try{let e=new g(n).hostname;return l.some(t=>t.test(e))}catch{return!1}}async function A(n,e,t){let o=new AbortController,r=setTimeout(()=>o.abort(),e);try{return await fetch(n,{signal:o.signal,headers:t})}catch(s){throw a(s)&&s.code==="ABORT_ERR"?new u(`Request timed out after ${e}ms`,"ETIMEDOUT"):new u(c(s))}finally{clearTimeout(r)}}function i(n){if(!(!n||typeof n!="object")&&"code"in n&&typeof n.code=="string")return n.code}function h(n){if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return String(n);if(n instanceof Error)return n.message;if(!n||typeof n!="object")return;let e=n.message;if(typeof e=="string")return e}function m(n){if(!(n instanceof Error))return;let e=n.cause;if(!e)return;let t=i(e),o=h(e);if(!(!t&&!o))return t&&o&&!o.includes(t)?`${t}: ${o}`:o??t}function N(n,e={}){let t=c(n),o=n instanceof Error?i(n.cause)??i(n):i(n),r=m(n),s=[t,r?`(cause: ${r})`:void 0].filter(Boolean).join(" "),d=t.toLowerCase().includes("fetch failed")||o!=null&&T.has(o),R=o!=null&&f.has(o);if(!d)return s;let _=["","Troubleshooting:",...e.url?[`- Confirm you can reach ${e.url} from this machine.`]:[],"- If you are behind a proxy, pass `--proxy <url>` (or set `proxy` in settings).",...R?["- If your network uses a corporate TLS inspection CA, set `NODE_EXTRA_CA_CERTS` to your CA bundle."]:[]];return`${s}${_.join(`
4
- `)}`}export{S as a,A as b,N as c};
5
- /**
6
- * @license
7
- * Copyright 2025 Google LLC
8
- * SPDX-License-Identifier: Apache-2.0
9
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{c as a,d as b,e as c}from"./chunk-46QIOR55.js";import"./chunk-7LZNA4VT.js";import"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.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,22 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Qe as _,Re as j}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import{b as D}from"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{g as k}from"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import{g as M,i as C,p as N,q as A}from"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import{D as $,G as O,K as v,Z as R,c as x}from"./chunk-5QAKUC2D.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
-
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
-
7
- [Search stopped after scanning ${B} entries. Results may be incomplete \u2014 narrow the search by passing a more specific 'path' or pattern.]`:"";if(!l||l.length===0)return{llmContent:`No files found matching pattern "${this.params.pattern}" ${r}${p}`,returnDisplay:o?"No files found (search truncated)":"No files found"};let d=24*60*60*1e3,P=new Date().getTime(),m=K(l,P,d),h=m.length,f=Math.min(Y,this.config.getTruncateToolOutputLines()),y=h>f,b=(y?m.slice(0,f):m).map(i=>i.fullpath()),X=b.join(`
8
- `),w=`Found ${h} file(s) matching "${this.params.pattern}" ${r}`;if(w+=`, sorted by modification time (newest first):
9
- ---
10
- ${X}`,y){let i=h-f;w+=`
11
- ---
12
- [${i} ${i===1?"file":"files"} truncated] ...`}return w+=p,{llmContent:w,returnDisplay:`Found ${h} matching file(s)${y?" (truncated)":""}`,resultFilePaths:b}}catch(e){let r=e instanceof Error?e.message:String(e);V.error(`GlobLogic execute Error: ${r}`,e);let s=`Error during glob search operation: ${r}`;return{llmContent:s,returnDisplay:`Error: ${r||"An unexpected error occurred."}`,error:{message:s,type:"glob_execution_error"}}}}getFileFilteringOptions(){let t=this.config.getFileFilteringOptions?.();return{respectGitIgnore:t?.respectGitIgnore??D.respectGitIgnore,respectMatildaIgnore:t?.respectMatildaIgnore??D.respectMatildaIgnore}}},U=class u extends C{constructor(t){super(u.Name,A.GLOB,`Fast file pattern matching tool that works with any codebase size
13
- - Supports glob patterns like "**/*.js" or "src/**/*.ts"
14
- - Returns matching file paths sorted by modification time
15
- - Use this tool when you need to find files by name patterns
16
- - When you are doing an open ended search that may require multiple rounds of globbing and grepping, use the Agent tool instead
17
- - You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.`,"search",{properties:{pattern:{description:"The glob pattern to match files against",type:"string"},path:{description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.',type:"string"}},required:["pattern"],type:"object"});this.config=t}static Name=N.GLOB;validateToolParamValues(t){if(!t.pattern||typeof t.pattern!="string"||t.pattern.trim()==="")return"The 'pattern' parameter cannot be empty.";if(t.path){t.path=$(t.path.trim());try{v(this.config,t.path,{allowExternalPaths:!0})}catch(e){return x(e)}}return null}createInvocation(t){return new S(this.config,t)}};export{U as GlobTool,B as MAX_SCAN_ENTRIES,W as MAX_SCAN_MS,K as sortFileEntries};
18
- /**
19
- * @license
20
- * Copyright 2025 Google LLC
21
- * SPDX-License-Identifier: Apache-2.0
22
- */
@@ -1,15 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as d}from"./chunk-RNKDFE2S.js";import{g as N}from"./chunk-VB4MJSMC.js";import{g as C,i as x,p as w,q as F}from"./chunk-BGZJUBRA.js";import{A as E,B as I,D as S,G as u,H as L,M as R,Z as O}from"./chunk-5QAKUC2D.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
- `),h=`Listed ${p} item(s) in ${this.params.path}:
5
- ---
6
- ${W}`;if(m){let r=p-g;h+=`
7
- ---
8
- [${r} ${r===1?"item":"items"} truncated] ...`}let n=[];P>0&&n.push(`${P} git-ignored`),b>0&&n.push(`${b} matilda-ignored`),n.length>0&&(h+=`
9
-
10
- (${n.join(", ")})`);let f=`Listed ${p} item(s)`;return n.length>0&&(f+=` (${n.join(", ")})`),m&&(f+=" (truncated)"),{llmContent:h,returnDisplay:f}}catch(e){let i=`Error listing directory: ${e instanceof Error?e.message:String(e)}`;return this.errorResult(i,"Failed to list directory.","ls_execution_error")}}},M=class D extends x{constructor(t){super(D.Name,F.LS,"Lists the names of files and subdirectories directly within a specified directory path. Can optionally ignore entries matching provided glob patterns.","search",{properties:{path:{description:"The absolute path to the directory to list (must be absolute, not relative)",type:"string"},ignore:{description:"List of glob patterns to ignore",items:{type:"string"},type:"array"},file_filtering_options:{description:"Optional: Whether to respect ignore patterns from .gitignore or .matildaignore",type:"object",properties:{respect_git_ignore:{description:"Optional: Whether to respect .gitignore patterns when listing files. Only available in git repositories. Defaults to true.",type:"boolean"},respect_matilda_ignore:{description:"Optional: Whether to respect .matildaignore patterns when listing files. Defaults to true.",type:"boolean"}}}},required:["path"],type:"object"});this.config=t}static Name=w.LS;validateToolParamValues(t){return t.path=S(t.path.trim()),s.isAbsolute(t.path)?null:`Path must be absolute: ${t.path}`}createInvocation(t){return new T(this.config,t)}};export{M as LSTool};
11
- /**
12
- * @license
13
- * Copyright 2025 Google LLC
14
- * SPDX-License-Identifier: Apache-2.0
15
- */
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as d,i as u}from"./chunk-KAOSSAJ7.js";import"./chunk-U3O6TMV7.js";import"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import{d as o}from"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{k as s}from"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import{c}from"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import{Z as i}from"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as a}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";a();var l=class extends u{debugLogger=i("MATILDA");matildaClient;sharedManager;currentToken;constructor(e,t,r){let n=new d(t,r);super(t,r,n),this.matildaClient=e,this.sharedManager=c.getInstance(),t?.baseUrl&&t?.apiKey&&(this.pipeline.client.baseURL=t?.baseUrl,this.pipeline.client.apiKey=t?.apiKey)}getCurrentEndpoint(e){let t=e||o,r="/v1",n=t.startsWith("http")?t:`https://${t}`;return n.endsWith(r)||n.endsWith("/api/v1")||n.endsWith("/api/v1/code")?n:`${n}${r}`}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:r,endpoint:n}=await this.getValidToken();return this.pipeline.client.apiKey=r,this.pipeline.client.baseURL=n,await e()};try{return await t()}catch(r){if(this.isAuthError(r))return await this.sharedManager.getValidCredentials(this.matildaClient,!0),await s("retry",t);throw r}}async generateContent(e,t){return this.executeWithCredentialManagement(()=>super.generateContent(e,t))}async generateContentStream(e,t){return this.executeWithCredentialManagement(()=>super.generateContentStream(e,t))}async countTokens(e){return super.countTokens(e)}async embedContent(e){return this.executeWithCredentialManagement(()=>super.embedContent(e))}isAuthError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e,n=r?.status||r?.code;return n===401||n===403||n==="401"||n==="403"||t.includes("unauthorized")||t.includes("forbidden")||t.includes("invalid api key")||t.includes("invalid access token")||t.includes("token expired")||t.includes("authentication")||t.includes("access denied")||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{l as MatildaContentGenerator};
4
- /**
5
- * @license
6
- * Copyright 2025 Matilda
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,32 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Ec as tt,Je as st,Oe as L,Pc as et,Pe as at,Sc as ot,Tc as A,Yc as C,Zc as nt,bd as it,pi as P,ri as lt,ye as rt}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import{g as Z,i as q,p as Y,q as Q}from"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import{H as J,Z as K,c as m}from"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as H}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";H();import{spawn as ct}from"node:child_process";import mt from"node:path";import{randomUUID as wt}from"node:crypto";var u=K("MONITOR"),Et=1e3,O=1e4,St=3e5,N=6e5,dt=80,R=4096,ut=5,ft=1e3;function pt(l){return l.length>dt?l.slice(0,dt-1)+"\u2026":l}var kt=new Set(["task-notification","task-id","tool-use-id","kind","status","event-count","summary","result"]),xt=/<(\/?)([a-zA-Z][a-zA-Z0-9-]*)>/g;function gt(l){let y="";for(let t=0;t<l.length;t++){let o=l.charCodeAt(t);if(o===9){y+=l[t];continue}o<32||o>=128&&o<=159||(y+=l[t])}return y=y.replace(xt,(t,o,a)=>kt.has(String(a).toLowerCase())?o==="/"?`</\u200B${a}>`:`<\u200B${a}>`:t),y}var U=class extends Z{constructor(t,o){super(o);this.config=t}callId;setCallId(t){this.callId=t}getDescription(){let t=this.params.description||C(this.params.command).spawnCommand;return`Monitor: ${pt(t)}`}async getDefaultPermission(){let t=C(this.params.command).safetyCommand;try{if(await L(t))return"allow"}catch(o){u.warn("AST read-only check failed, falling back to ask:",o)}return"ask"}async getConfirmationDetails(t){let o=C(this.params.command),a=ot(o.safetyCommand),f=[];for(let s of a){let p=!1;try{p=await L(s)}catch(d){u.warn("AST read-only check failed for monitor sub-command, falling back to ask:",d)}p||f.push(s)}let S=f.length>0?f:a,M=[...new Set(S.map(s=>A(s)).filter(s=>!!s))],v=[];try{let s=[];for(let p of S){let d=await at(p);s.push(...d)}v=[...new Set(s)].map(p=>`Monitor(${p})`)}catch(s){u.warn("Failed to extract monitor command rules:",s),v=[`Monitor(${o.safetyCommand})`]}let i=it(o.safetyCommand,this.params.command),c={type:"exec",title:"Monitor",command:o.spawnCommand,rootCommand:M.join(", ")||(A(o.safetyCommand)??o.spawnCommand),permissionRules:v,onConfirm:async(s,p)=>{}};return i&&(c.warnings=i),c}async execute(t){if(t.aborted)return{llmContent:"Monitor was cancelled before it could start.",returnDisplay:"Monitor cancelled."};let o=C(this.params.command),a=o.spawnCommand;o.strippedTrailingAmp&&u.warn("Stripped trailing & from monitor command \u2014 monitor lifecycle handles backgrounding");let f=gt(this.params.description||a),S=pt(f),M=Math.min(this.params.max_events??Et,O),v=Math.min(this.params.idle_timeout_ms??St,N),i=`mon_${wt().replace(/-/g,"").slice(0,16)}`,c=this.config.getMonitorRegistry(),s=tt()??void 0;if(c.getRunning().length>=P)return{llmContent:`Cannot start monitor: maximum concurrent monitors (${P}) reached. Stop an existing monitor first.`,returnDisplay:"Monitor rejected: too many concurrent monitors."};let d=new AbortController,g={monitorId:i,command:a,description:f,status:"running",startTime:Date.now(),abortController:d,toolUseId:this.callId,eventCount:0,lastEventTime:0,maxEvents:M,idleTimeoutMs:v,droppedLines:0,outputFile:lt(this.config.storage.getProjectDir(),this.config.getSessionId(),i),...s?{ownerAgentId:s}:{}},{executable:yt,argsPrefix:vt}=et(),n;try{n=ct(yt,[...vt,a],{cwd:this.params.directory||this.config.getTargetDir(),stdio:["ignore","pipe","pipe"],detached:!0,env:{...process.env,MATILDA_CODE:"1",TERM:"dumb",PAGER:"cat",...st()}})}catch(e){return{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}g.pid=n.pid;let b=!1,w,D=e=>{w??=e};n.on("error",D);let B={value:""},G={value:""},k=ut,I=Date.now(),$=e=>{let r=gt(e);if(r.length===0||r.trim().length===0)return;let T=Date.now(),_=T-I;if(_<0)u.warn(`Monitor ${i}: clock moved backwards by ${-_}ms, resetting refill timestamp`),I=T;else{let h=Math.floor(_/ft);h>0&&(k=Math.min(ut,k+h),I+=h*ft)}k>0?(k--,c.emitEvent(i,r)):g.droppedLines++},j=()=>{for(let e of[B,G]){let r=e.value.trim();r.length>0&&$(r),e.value=""}},Tt=()=>{if(!(b||!n.pid))if(process.platform==="win32")ct("taskkill",["/pid",n.pid.toString(),"/f","/t"],{stdio:"ignore"}).on("error",r=>u.warn(`Monitor taskkill failed for pid ${n.pid}: ${m(r)}`));else{try{process.kill(-n.pid,"SIGTERM")}catch(e){u.warn(`Monitor ${i} SIGTERM failed (pid=${n.pid}): ${m(e)}`)}setTimeout(()=>{if(!b&&n.pid)try{process.kill(-n.pid,"SIGKILL")}catch(e){u.warn(`Monitor ${i} SIGKILL escalation failed (pid=${n.pid}): ${m(e)}`)}},200).unref?.()}},E=()=>{j(),Tt()};d.signal.addEventListener("abort",E,{once:!0}),d.signal.aborted&&E();try{c.register(g)}catch(e){return E(),d.signal.removeEventListener("abort",E),n.stdout?.destroy?.(),n.stderr?.destroy?.(),n.removeListener("error",D),n.on("error",()=>{}),{llmContent:`Monitor failed to start: ${m(e)}`,returnDisplay:`Monitor failed: ${m(e)}`}}let z=(e,r)=>{if(g.status!=="running")return;let T=rt(r.toString("utf-8"));if(e.value+=T,!e.value.includes(`
4
- `)&&e.value.length>R){let h=e.value.trim();h.length>0&&$(h.slice(0,R)+"..."),e.value="";return}let _=e.value.split(`
5
- `);e.value=_.pop()??"";for(let h of _){let x=h.trim();if(x.length===0)continue;let bt=x.length>R?x.slice(0,R)+"...":x;$(bt)}};n.stdout?.on("data",e=>z(B,e)),n.stderr?.on("data",e=>z(G,e));let F=!1,X=()=>{F||(F=!0,j(),d.signal.removeEventListener("abort",E),g.droppedLines>0&&u.info(`Monitor ${i} dropped ${g.droppedLines} lines due to throttling`))},V=null,_t=(e,r)=>{g.status==="running"&&(d.signal.aborted?c.cancel(i):e!==null&&e!==0?c.fail(i,`Exit code ${e}`):r?c.fail(i,`Killed by signal ${r}`):c.complete(i,e))},Ct=(e,r)=>{b=!0,V={code:e,sig:r}},Mt=(e,r)=>{b=!0,X();let T=V??{code:e,sig:r};_t(T.code,T.sig)},W=e=>{b=!0,X(),g.status==="running"&&c.fail(i,m(e))};return n.on("exit",Ct),n.on("close",Mt),n.on("error",W),n.removeListener("error",D),w?(W(w),{llmContent:`Monitor failed to start: ${m(w)}`,returnDisplay:`Monitor failed: ${m(w)}`}):{llmContent:`Monitor started.
6
- id: ${i}
7
- command: ${a}
8
- description: ${f}
9
- max_events: ${M}
10
- idle_timeout: ${v}ms
11
- Events will be delivered as notifications. The monitor auto-stops after ${M} events or ${v}ms of silence.
12
- To inspect: /tasks (text) or the interactive Background tasks dialog (focus the footer Background tasks pill, then Enter \u2014 detail view + live updates).`,returnDisplay:`Monitor started: ${S} (${i})`}}},ht=class l extends q{constructor(t){super(l.Name,Q.MONITOR,`Starts a long-running shell command and streams its stdout/stderr as event notifications back to you.
13
-
14
- Use this tool for:
15
- - Watching log files: \`tail -f /var/log/app.log\`
16
- - Monitoring build output: \`npm run build --watch\`
17
- - Polling for state changes: \`while true; do curl -s http://localhost:8080/health; sleep 1; done\`
18
- - Watching file changes: \`fswatch -r ./src\`
19
-
20
- Each output line from the command becomes a notification event delivered to you. The monitor runs in the background \u2014 you can continue working while it streams events.
21
-
22
- **Auto-stop:** The monitor automatically stops after max_events (default 1000) events or after idle_timeout_ms (default 5 minutes) of silence. The process is killed when the monitor stops.
23
-
24
- **Do NOT use this tool for:**
25
- - One-shot commands (use run_shell_command instead)
26
- - Commands you need the full output from (use run_shell_command instead)
27
- - Commands with no output (use run_shell_command with is_background: true instead)`,"execute",{type:"object",properties:{command:{type:"string",description:"Shell command to run and monitor. Each output line (stdout and stderr) becomes an event notification."},description:{type:"string",description:'Brief description of what this monitor watches (e.g., "webpack build output"). Truncated to 80 characters in display.'},max_events:{type:"number",description:"Stop the monitor after this many events. Default 1000. Max 10000."},idle_timeout_ms:{type:"number",description:"Stop the monitor if no output for this many milliseconds. Default 300000 (5 min). Max 600000."},directory:{type:"string",description:"(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be within the workspace."}},required:["command"],additionalProperties:!1},!0,!1,!0,!1,"monitor watch tail log stream background");this.config=t}static Name=Y.MONITOR;validateToolParamValues(t){if(typeof t.command!="string"||!C(t.command).analysisCommand)return"Command cannot be empty.";if(nt(t.command))return'Monitor commands must not contain non-final top-level background operators. Remove "&" and let the monitor manage process lifetime.';if(t.max_events!==void 0){if(typeof t.max_events!="number"||!Number.isInteger(t.max_events)||t.max_events<=0)return"max_events must be a positive integer.";if(t.max_events>O)return`max_events cannot exceed ${O}.`}if(t.idle_timeout_ms!==void 0){if(typeof t.idle_timeout_ms!="number"||!Number.isInteger(t.idle_timeout_ms)||t.idle_timeout_ms<=0)return"idle_timeout_ms must be a positive integer.";if(t.idle_timeout_ms>N)return`idle_timeout_ms cannot exceed ${N}ms (10 minutes).`}if(t.directory){if(!mt.isAbsolute(t.directory))return"Directory must be an absolute path.";let o=mt.resolve(t.directory),a=this.config.storage.getUserSkillsDirs();if(J(a,o))return"Explicitly running monitor commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.";if(!this.config.getWorkspaceContext().isPathWithinWorkspace(t.directory))return`Directory '${t.directory}' is not within any of the registered workspace directories.`}return null}createInvocation(t){return new U(this.config,t)}toAutoClassifierInput(t){let o={command:t.command};return t.directory&&(o.directory=t.directory),o}};export{ht as MonitorTool,gt as sanitizeMonitorLine};
28
- /**
29
- * @license
30
- * Copyright 2025 Matilda
31
- * SPDX-License-Identifier: Apache-2.0
32
- */
@@ -1,17 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Me as y,Xe as X,_e as Z,ja as R,re as D,se as Y,uc as Q}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{J as B,K as k,L as U,Lb as z,M as K,N as q,O as b,P as W,Q as j,R as C,S as J,T as V,U as w,V as M,_c as H,ca as G}from"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import{g as $,i as L,p as c,q as x}from"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import{A as _,B as N,D as T,Z as F}from"./chunk-5QAKUC2D.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();import*as E from"node:fs";import*as m from"node:path";var ee=F("NOTEBOOK_EDIT");function g(d,r,t){return ee.debug("prior-read-rejected",{path:d,reason:r,type:t.type,displayMessage:t.displayMessage}),t}var u=class extends Error{constructor(t,e){super(t);this.type=e;this.name="NotebookEditError"}};function te(d,r){if(r==="delete")return"";if(typeof d!="string")throw new u(`new_source is required when edit_mode is "${r}".`,"invalid_tool_params");return d}function I(d,r){return d?q(d,r):`cell-${r}`}function oe(d,r,t){if(!r){if(t==="insert")return-1;throw new u("cell_id is required for replace and delete operations.","invalid_tool_params")}if(W(d,r))throw new u(`Cell ID "${r}" is ambiguous in the rendered notebook. Re-read the notebook and target a stable real cell ID before editing.`,"invalid_tool_params");let e=j(d,r);if(e===-1)throw new u(`Cell with ID "${r}" not found in notebook.`,"notebook_cell_not_found");return e}function ie(d,r,t,e){let o={cell_type:r,metadata:{},source:w(t,e)},i=J(d);return i&&(o.id=i),M(o,r),o}function O(d,r){let t;try{t=k(d)}catch(a){throw new u(a instanceof Error?a.message:String(a),"notebook_invalid_json")}let e=r.edit_mode??"replace",o=te(r.new_source,e),i=b(t),n=oe(t,r.cell_id,e),l=C(t),p=U(d),s=(a,f)=>{let h=e==="insert"||e==="delete";return{...f,updatedContent:K(a,p),requiresReadAfterWrite:h&&!(i&&b(a))}};switch(e){case"insert":{let a=r.cell_type??"code",f=n===-1?0:n+1,h=ie(t,a,o,V(t,f));return t.cells.splice(f,0,h),s(t,{editedCellId:I(h,f),editedCellType:a,language:l,mode:e})}case"delete":{let[a]=t.cells.splice(n,1);return s(t,{editedCellId:I(a,n),editedCellType:a?.cell_type,language:l,mode:e})}case"replace":{let a=t.cells[n];if(!a)throw new u(`Cell index ${n} is out of range.`,"notebook_cell_not_found");let f=r.cell_type??a.cell_type;return a.source=w(o,Array.isArray(a.source)),M(a,f),s(t,{editedCellId:I(a,n),editedCellType:f,language:l,mode:e})}default:throw new u(`Unsupported notebook edit mode: ${e}`,"invalid_tool_params")}}function re(d,r,t){let e,o;try{e=k(r),o=k(d)}catch(i){throw new u(i instanceof Error?i.message:String(i),"notebook_invalid_json")}return{updatedContent:r,editedCellId:t.cell_id??"user-modified-notebook",editedCellType:void 0,language:C(e),mode:t.edit_mode??"replace",requiresReadAfterWrite:!b(o)||!b(e)}}async function A(d,r,t={}){if(d.getFileReadCacheDisabled())return{ok:!0};let e;try{e=await E.promises.stat(r)}catch(i){let n=i?.code;return n==="ENOENT"?t.expectExisting?g(r,"missing-after-read",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} disappeared after it was read. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook disappeared after last read; re-run ${c.READ_FILE} first.`}):{ok:!0}:g(r,"stat-failed",{ok:!1,type:"prior_read_verification_failed",rawMessage:`Could not stat ${r} to verify prior notebook read (${n??"unknown error"}). Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`cannot verify prior read of ${r}; re-run ${c.READ_FILE} before editing this notebook.`})}if(e.isDirectory())return g(r,"target-is-directory",{ok:!1,type:"target_is_directory",rawMessage:`${r} is a directory. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"path is a directory; cannot edit as a notebook."});if(!e.isFile())return g(r,"target-not-regular-file",{ok:!1,type:"target_not_regular_file",rawMessage:`${r} is not a regular file. The NotebookEdit tool only operates on .ipynb files.`,displayMessage:"special file; cannot edit as a notebook."});let o=d.getFileReadCache().check(e);return o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadWasFull?{ok:!0}:o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadWasFull?g(r,"truncated-cache-entry",{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} is too large for cell-level editing because its rendered output was truncated when read. Reduce the notebook output size or split the notebook before editing cells.`,displayMessage:"notebook too large for cell-level editing."}):o.state==="stale"?g(r,"stale-cache-entry",{ok:!1,type:"file_changed_since_read",rawMessage:`Notebook ${r} has been modified since you last read it. Re-read it with the ${c.READ_FILE} tool before editing it.`,displayMessage:`notebook changed since last read; re-run ${c.READ_FILE} first.`}):g(r,`cache-${o.state}`,{ok:!1,type:"edit_requires_prior_read",rawMessage:`Notebook ${r} has not been fully read in this session. Use the ${c.READ_FILE} tool first, without offset or limit, before editing cells.`,displayMessage:`${c.READ_FILE} required before editing this notebook.`})}var P=class extends ${constructor(t,e,o){super(e);this.config=t;this.modifyMetadata=o}toolLocations(){return[{path:this.params.notebook_path}]}getDescription(){let t=N(this.params.notebook_path,this.config.getTargetDir()),e=this.params.edit_mode??"replace",o=this.params.cell_id??"beginning";return`${e} notebook cell ${o} in ${_(t)}`}async getDefaultPermission(){return"ask"}async getConfirmationDetails(t){let e=await this.prepareEdit(t),o=m.basename(this.params.notebook_path),i=R(o,e.originalContent,e.updatedContent,"Current","Proposed",D);return{type:"edit",title:`Confirm Notebook Edit: ${_(N(this.params.notebook_path,this.config.getTargetDir()))}`,fileName:o,filePath:this.params.notebook_path,fileDiff:i,originalContent:e.originalContent,newContent:e.updatedContent,onConfirm:async l=>{l==="proceed_always"&&this.config.setApprovalMode("auto-edit")}}}async prepareEdit(t){let e=await A(this.config,this.params.notebook_path);if(!e.ok)throw new y(e.rawMessage,e.type);let o,i=!1,n,l="lf";try{let s=await this.config.getFileSystemService().readTextFile({path:this.params.notebook_path});o=s.content,i=s._meta?.bom??!1,n=s._meta?.encoding,l=s._meta?.lineEnding??X(s.content)}catch(s){throw t.aborted?s:s?.code==="ENOENT"?new y(`Notebook file not found: ${this.params.notebook_path}`,"file_not_found"):new y(`Error reading notebook: ${s instanceof Error?s.message:String(s)}`,"read_content_failure")}let p=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!p.ok)throw new y(p.rawMessage,p.type);try{return this.modifyMetadata?.modifiedNotebookContent!==void 0?{...re(o,this.modifyMetadata.modifiedNotebookContent,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}:{...O(o,this.params),originalContent:o,bom:i,encoding:n,lineEnding:l}}catch(s){throw s instanceof u?new y(s.message,s.type):s}}async execute(t){let e;try{e=await this.prepareEdit(t)}catch(o){if(t.aborted)throw o;let i=o instanceof y?o.errorType:"notebook_edit_failure",n=o instanceof Error?o.message:String(o);return{llmContent:n,returnDisplay:`Error: ${n}`,error:{message:n,type:i}}}try{try{await this.config.getFileHistoryService().trackEdit(this.params.notebook_path)}catch{}let o=await A(this.config,this.params.notebook_path,{expectExisting:!0});if(!o.ok)return{llmContent:o.rawMessage,returnDisplay:`Error: ${o.displayMessage}`,error:{message:o.rawMessage,type:o.type}};await this.config.getFileSystemService().writeTextFile({path:this.params.notebook_path,content:e.updatedContent,_meta:{bom:e.bom,encoding:e.encoding,lineEnding:e.lineEnding}}),this.modifyMetadata?.modifiedByUser||Q.getInstance().recordEdit(this.params.notebook_path,e.originalContent,e.updatedContent);try{let a=E.statSync(this.params.notebook_path),f=this.config.getFileReadCache();e.requiresReadAfterWrite?f.invalidate(a):f.recordWrite(this.params.notebook_path,a,{cacheable:!1})}catch(a){ee.warn(`[NotebookEdit] post-write cache update failed for ${this.params.notebook_path}: ${a instanceof Error?a.message:String(a)}`)}let i=m.basename(this.params.notebook_path),n=R(i,e.originalContent,e.updatedContent,"Current","Proposed",D),l=Y(i,e.originalContent,this.modifyMetadata?.aiProposedContent??e.updatedContent,e.updatedContent);z(this.config,new H(S.Name,"update",e.updatedContent.split(`
4
- `).length,G(this.params.notebook_path),".ipynb",e.language));let p={fileDiff:n,fileName:i,originalContent:e.originalContent,newContent:e.updatedContent,diffStat:l},s=this.modifyMetadata?.modifiedNotebookContent!==void 0?`Notebook ${this.params.notebook_path} has been updated. Notebook content was modified by the user before approval; the final saved notebook may differ from the original ${e.mode} cell ${e.editedCellId} proposal.`:`Notebook ${this.params.notebook_path} has been updated. ${e.mode} cell ${e.editedCellId}.${e.mode==="delete"?"":`
5
-
6
- Updated source:
7
-
8
- ---
9
-
10
- ${B(this.params.new_source??"")}`}`;try{let a=await Z(this.config,this.params.notebook_path);a&&(s+=`
11
-
12
- ${a}`)}catch{}return{llmContent:s,returnDisplay:p,resultFilePaths:[this.params.notebook_path]}}catch(o){let i=o instanceof Error?o.message:String(o);return{llmContent:`Error writing notebook: ${i}`,returnDisplay:`Error writing notebook: ${i}`,error:{message:i,type:"file_write_failure"}}}}},S=class d extends L{constructor(t){super(d.Name,x.NOTEBOOK_EDIT,`Edits a Jupyter notebook (.ipynb) safely at the cell level. Use this instead of ${c.EDIT} or ${c.WRITE_FILE} for notebook cells. Supports replacing, inserting, and deleting cells. Always read the notebook first with ${c.READ_FILE}; then use the cell IDs shown in that output.`,"edit",{properties:{notebook_path:{description:"Absolute path to the Jupyter notebook file to edit. Must end with .ipynb.",type:"string"},cell_id:{description:"Target cell ID from read_file output, or cell-N 0-based fallback. Required for replace and delete. For insert, the new cell is inserted after this cell; if omitted, inserted at the beginning.",type:"string"},new_source:{description:"New source content for replace and insert operations. Not required for delete.",type:"string"},cell_type:{description:"Cell type for inserted cells or type conversion on replace.",type:"string",enum:["code","markdown"]},edit_mode:{description:"Notebook edit operation. Defaults to replace.",type:"string",enum:["replace","insert","delete"]}},required:["notebook_path"],additionalProperties:!1,type:"object"});this.config=t}static Name=c.NOTEBOOK_EDIT;modifyMetadataByParams=new WeakMap;modifyMetadataByKey=new Map;validateToolParamValues(t){if(t.notebook_path=T(t.notebook_path.trim()),!t.notebook_path)return"The 'notebook_path' parameter must be non-empty.";if(!m.isAbsolute(t.notebook_path))return`Notebook path must be absolute: ${t.notebook_path}`;if(m.extname(t.notebook_path).toLowerCase()!==".ipynb")return"File must be a Jupyter notebook (.ipynb). Use the edit tool for other file types.";let e=t.edit_mode??"replace";return["replace","insert","delete"].includes(e)?t.cell_type&&!["code","markdown"].includes(t.cell_type)?"cell_type must be 'code' or 'markdown'.":e!=="insert"&&!t.cell_id?"cell_id is required for replace and delete operations.":e!=="delete"&&typeof t.new_source!="string"?`new_source is required when edit_mode is "${e}".`:this.config.getFileService().shouldMatildaIgnoreFile(t.notebook_path)?`File path '${t.notebook_path}' is ignored by .matildaignore pattern(s).`:null:"edit_mode must be 'replace', 'insert', or 'delete'."}createInvocation(t){return new P(this.config,t,this.consumeModifyMetadata(t))}getModifyMetadataKey(t){return JSON.stringify({notebook_path:T(t.notebook_path.trim()),cell_id:t.cell_id,new_source:t.new_source,cell_type:t.cell_type,edit_mode:t.edit_mode})}rememberModifyMetadata(t,e){this.modifyMetadataByParams.set(t,e);let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o)??[];i.push(e),this.modifyMetadataByKey.set(o,i)}consumeModifyMetadata(t){let e=this.modifyMetadataByParams.get(t);if(e)return this.modifyMetadataByParams.delete(t),this.removeQueuedModifyMetadata(t,e),e;let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o),n=i?.shift();return i&&i.length===0&&this.modifyMetadataByKey.delete(o),n}removeQueuedModifyMetadata(t,e){let o=this.getModifyMetadataKey(t),i=this.modifyMetadataByKey.get(o);if(!i)return;let n=i.indexOf(e);n!==-1&&i.splice(n,1),i.length===0&&this.modifyMetadataByKey.delete(o)}getModifyContext(t){let e=new Map,o=async i=>{let n=e.get(i.notebook_path);if(n!==void 0)return n;let{content:l}=await this.config.getFileSystemService().readTextFile({path:i.notebook_path});return e.set(i.notebook_path,l),l};return{getFilePath:i=>i.notebook_path,getCurrentContent:async i=>o(i),getProposedContent:async i=>{let n=await o(i);return O(n,i).updatedContent},createUpdatedParams:(i,n,l)=>{let p=this.modifyMetadataByParams.get(l)?.aiProposedContent;if(p===void 0)try{p=O(i,l).updatedContent}catch{p=n}let s={...l};return this.rememberModifyMetadata(s,{aiProposedContent:p,modifiedByUser:!0,modifiedNotebookContent:n}),s}}}};export{S as NotebookEditTool,O as applyNotebookEdit};
13
- /**
14
- * @license
15
- * Copyright 2026 Matilda Team
16
- * SPDX-License-Identifier: Apache-2.0
17
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{wc as a}from"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{a as ReadFileTool};
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{Mj as a,Nj as b}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as RipGrepTool,a as _resetRipGrepCachesForTest};
@@ -1,8 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{b as E}from"./chunk-7ZATDBWL.js";import{wa as P}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import{M as l,Z as c}from"./chunk-5QAKUC2D.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();import{stat as V}from"node:fs/promises";import{join as p}from"node:path";s();import{readdir as N,stat as H,rm as F,rmdir as A}from"node:fs/promises";import{join as y}from"node:path";var k=c("HOUSEKEEPING"),U=24*60*60*1e3,$=60*60*1e3,_=20;function T(e){let t=e>0?e*U:$;return new Date(Date.now()-t)}async function b(e){let t={removed:0,errors:0},r=y(l.getGlobalMatildaDir(),P),i=e.excludeSessionIds??new Set,o;try{o=await N(r,{withFileTypes:!0})}catch(n){return G(n)||k.error("readdir failed",n),t}let a=o.filter(n=>n.isDirectory()&&!i.has(n.name)).map(n=>y(r,n.name));for(let n=0;n<a.length;n+=_){let v=a.slice(n,n+_);await Promise.all(v.map(async g=>{try{(await H(g)).mtime<e.cutoffDate&&(await F(g,{recursive:!0,force:!0}),t.removed++)}catch(w){t.errors++,k.error(`failed to sweep ${g}`,w)}}))}return await A(r).catch(()=>{}),t}function G(e){return e?.code==="ENOENT"}s();import{mkdir as Y,open as K,stat as I,unlink as D,writeFile as j}from"node:fs/promises";import{dirname as B}from"node:path";var m=c("HOUSEKEEPING"),q=24*60*60*1e3,J=60*60*1e3;async function R(e,t){let r=e.minIntervalMs??q,i=e.staleLockMs??J;if(await Y(B(e.lockPath),{recursive:!0,mode:448}).catch(()=>{}),await C(e.markerPath,r,e.name))return!1;let o=await h(e.lockPath);if(!o){try{let a=await I(e.lockPath);Date.now()-a.mtimeMs>i&&(await D(e.lockPath).catch(()=>{}),o=await h(e.lockPath))}catch{o=await h(e.lockPath)}if(!o)return m.debug(`${e.name}: skipping, lock held`),!1}try{if(await C(e.markerPath,r,e.name))return!1;let a=!1;try{await t(),a=!0}finally{if(a)try{await j(e.markerPath,new Date().toISOString())}catch(n){m.debug(`${e.name}: marker write failed (cleanup succeeded)`,n)}}return a}finally{await D(e.lockPath).catch(()=>{m.debug(`${e.name}: lock unlink failed (harmless)`)})}}async function C(e,t,r){try{let i=await I(e),o=Date.now()-i.mtimeMs;if(o<t)return m.debug(`${r}: skipping, ran ${o}ms ago`),!0}catch{}return!1}async function h(e){try{return await(await K(e,"wx")).close(),!0}catch(t){if(t?.code==="EEXIST")return!1;throw t}}var u=c("HOUSEKEEPING"),O=10*60*1e3,W=24*60*60*1e3,X=60*1e3,z=7*24*60*60*1e3,Q=60*1e3,f=".file-history-cleanup",d=!1;function pe(e,t){d||(d=!0,Z(e,t).catch(r=>{d=!1,u.error("scheduleFirstPass failed; chain will retry on next start",r)}))}async function Z(e,t){let r=p(l.getGlobalMatildaDir(),f),i=await L(r)?Q:O;u.debug(`first pass in ${i/1e3}s`),setTimeout(()=>S(e,t),i).unref()}async function L(e){try{let t=await V(e);return Date.now()-t.mtimeMs>z}catch{return!0}}async function M(e,t){if(E()<X){u.debug("user active, deferring 10 min"),setTimeout(()=>S(e,t),O).unref();return}try{await x(e,t)}catch(r){u.error("housekeeping pass failed; will retry next cycle",r)}setTimeout(()=>S(e,t),W).unref()}function S(e,t){M(e,t).catch(r=>{u.error("runPass rejected unexpectedly",r)})}async function x(e,t){let r=t.merged.general?.cleanupPeriodDays??30,i=T(r),o=e.getSessionId(),a=l.getGlobalMatildaDir();await R({name:"file-history-cleanup",markerPath:p(a,f),lockPath:p(a,f+".lock")},async()=>{let n=await b({cutoffDate:i,excludeSessionIds:new Set([o])});u.debug(`file-history: removed=${n.removed} errors=${n.errors}`)})}function Se(){d=!1}var we=L,Pe=x,Ee=M,ye=f;export{ye as _FILE_HISTORY_MARKER_FOR_TESTING,we as _needsCatchUpForTesting,Se as _resetForTesting,Pe as _runHousekeepingForTesting,Ee as _runPassForTesting,pe as startBackgroundHousekeeping};
4
- /**
5
- * @license
6
- * Copyright 2025 Google LLC
7
- * SPDX-License-Identifier: Apache-2.0
8
- */
@@ -1,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{$e as a,af as b,bf as c,cf as d,df as e,ef as f,ff as g}from"./chunk-AMO6HY3T.js";import"./chunk-TZIDSCTF.js";import"./chunk-2HFKTFO5.js";import"./chunk-UHDKX2CR.js";import"./chunk-X4ML2NEE.js";import"./chunk-FQ44TPC5.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-FW6Z25AA.js";import"./chunk-TISQNFB5.js";import"./chunk-RQIV43CR.js";import"./chunk-47XR7IMP.js";import"./chunk-MW3LAIJW.js";import"./chunk-QKYGQLWC.js";import"./chunk-LNTO3FNQ.js";import"./chunk-L5ASITMV.js";import"./chunk-RNKDFE2S.js";import"./chunk-SOKNPND5.js";import"./chunk-743LSI67.js";import"./chunk-XITA5WMN.js";import"./chunk-QZWBA3NL.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-O3OUYCSO.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-OVC5Z3EX.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-VB4MJSMC.js";import"./chunk-OXHC3R2R.js";import"./chunk-BGZJUBRA.js";import"./chunk-N6BOYL6K.js";import"./chunk-VBOVIARK.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-SWEYYDZO.js";import"./chunk-5QAKUC2D.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as OUTPUT_UPDATE_INTERVAL_MS,g as ShellTool,f as ShellToolInvocation,c as buildLongRunningForegroundHint,d as detectBlockedSleepPattern,a as parseNumstat,e as repairLeakedShellToolArgMarkup};