@maincode-ai/matilda-code 0.21.11 → 0.21.13-nightly.20261026.e0eae1d8c

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 (200) hide show
  1. package/bundled/mainy/SKILL.md +0 -2
  2. package/bundled/mainy/docs/_meta.ts +0 -2
  3. package/bundled/mainy/docs/configuration/auth.md +5 -10
  4. package/bundled/mainy/docs/configuration/model-providers.md +31 -217
  5. package/bundled/mainy/docs/configuration/settings.md +48 -9
  6. package/bundled/mainy/docs/configuration/trusted-folders.md +12 -6
  7. package/bundled/mainy/docs/features/auto-mode.md +1 -1
  8. package/bundled/mainy/docs/features/channels/_meta.ts +0 -3
  9. package/bundled/mainy/docs/features/channels/overview.md +8 -16
  10. package/bundled/mainy/docs/features/commands.md +4 -4
  11. package/bundled/mainy/docs/features/hooks.md +9 -7
  12. package/bundled/mainy/docs/features/language.md +2 -29
  13. package/bundled/mainy/docs/features/sub-agents.md +1 -1
  14. package/bundled/mainy/docs/features/worktree.md +3 -5
  15. package/bundled/mainy/docs/integration-github-action.md +3 -3
  16. package/bundled/mainy/docs/matilda-serve.md +1 -1
  17. package/bundled/mainy/docs/quickstart.md +2 -2
  18. package/bundled/mainy/docs/support/troubleshooting.md +3 -10
  19. package/chunks/agent-4FTU3WN6.js +3 -0
  20. package/chunks/agent-headless-QJUVHPFC.js +3 -0
  21. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-QKX4NEFX.js} +1 -1
  22. package/chunks/{ca-EUJBUYX5.js → ca-C2V7I65K.js} +6 -6
  23. package/chunks/{chunk-T4P4KEDW.js → chunk-2ONZZ46N.js} +2 -2
  24. package/chunks/chunk-36K4HBVM.js +7 -0
  25. package/chunks/{chunk-EQGA7LH7.js → chunk-3B2HABK7.js} +1 -1
  26. package/chunks/{chunk-5427BPR2.js → chunk-5NMK4Y7C.js} +1 -1
  27. package/chunks/chunk-5YT4GCK7.js +14 -0
  28. package/chunks/{chunk-MH2P4YXC.js → chunk-62AFAL4I.js} +10 -10
  29. package/chunks/chunk-75KP2FVD.js +81 -0
  30. package/chunks/chunk-7ZODGQO6.js +4 -0
  31. package/chunks/chunk-BZB7HYRC.js +37 -0
  32. package/chunks/{chunk-WHG6N5X2.js → chunk-EXNHJQCD.js} +1 -1
  33. package/chunks/chunk-FCGYRGV4.js +9 -0
  34. package/chunks/chunk-G4YMVWG4.js +8 -0
  35. package/chunks/{chunk-4FVBPNTZ.js → chunk-HDARIAVM.js} +1 -1
  36. package/chunks/{chunk-4YVN5HXG.js → chunk-HM5LCKDB.js} +2 -2
  37. package/chunks/chunk-IIQ5YERM.js +120 -0
  38. package/chunks/chunk-JGJ7BVZN.js +101 -0
  39. package/chunks/{chunk-FFFZ2QMG.js → chunk-JIKQI4MZ.js} +1 -1
  40. package/chunks/{chunk-SPW5DXX4.js → chunk-LHDCAN7Z.js} +1 -1
  41. package/chunks/chunk-LZDHANXA.js +89 -0
  42. package/chunks/{chunk-ELH4YHJR.js → chunk-NOE4UNQN.js} +1 -1
  43. package/chunks/chunk-OEZS5R3S.js +207 -0
  44. package/chunks/{chunk-OOEH6ZSV.js → chunk-PTMCLADZ.js} +1 -1
  45. package/chunks/{chunk-NYEWHSBL.js → chunk-PYZNGIIR.js} +1 -1
  46. package/chunks/chunk-QJJTUDDA.js +56 -0
  47. package/chunks/{chunk-GO2GA2GY.js → chunk-R34HYLL4.js} +1 -1
  48. package/chunks/{chunk-Q55AVE2N.js → chunk-RK4LPGBV.js} +11 -11
  49. package/chunks/{chunk-JXUDKX6D.js → chunk-RYHMPK5G.js} +1 -1
  50. package/chunks/chunk-SR7ARGUY.js +13 -0
  51. package/chunks/chunk-SY6JRCN3.js +2612 -0
  52. package/chunks/chunk-TUKNB5CQ.js +33 -0
  53. package/chunks/{chunk-YMIF2DMT.js → chunk-TZ4FRU6B.js} +1 -1
  54. package/chunks/chunk-U7V7APDV.js +9 -0
  55. package/chunks/{chunk-SNLH42QJ.js → chunk-UVWZ44ZW.js} +1 -1
  56. package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
  57. package/chunks/{chunk-4CSSDBOS.js → chunk-VLDZBRTL.js} +10 -10
  58. package/chunks/{computer-use-SXP25RZQ.js → computer-use-OXAMR75N.js} +1 -1
  59. package/chunks/contextCommand-ERLW5VWL.js +3 -0
  60. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-AUDQ6STP.js} +1 -1
  61. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-P5HE3PDD.js} +1 -1
  62. package/chunks/{cron-list-YYAXNHB6.js → cron-list-NR5FZBK2.js} +1 -1
  63. package/chunks/{de-DNEPG7S7.js → de-KOUI2CEW.js} +6 -6
  64. package/chunks/{devtools-5JRKK3E7.js → devtools-G5DWLP2N.js} +1 -1
  65. package/chunks/dist-XXTQNTKQ.js +42 -0
  66. package/chunks/dist-ZFZZLIQU.js +3 -0
  67. package/chunks/edit-REFR5ROS.js +43 -0
  68. package/chunks/{en-NOD6KQNM.js → en-RMYRLXC2.js} +4 -4
  69. package/chunks/{enter-worktree-X47BSJLE.js → enter-worktree-WO3DT2G7.js} +1 -1
  70. package/chunks/{enterPlanMode-F22ZNTYJ.js → enterPlanMode-PLRHEU5A.js} +1 -1
  71. package/chunks/{exit-worktree-XY5UMDHX.js → exit-worktree-J5PW6DCV.js} +1 -1
  72. package/chunks/exitPlanMode-KXUPNLCJ.js +120 -0
  73. package/chunks/{fr-2OE5WLJ4.js → fr-R3QF3LA2.js} +5 -5
  74. package/chunks/glob-ZVTVRDQO.js +22 -0
  75. package/chunks/{goal-tools-6QTC3UI7.js → goal-tools-XVKQJL5I.js} +1 -1
  76. package/chunks/{grep-6TTPZ524.js → grep-R7CWUNNE.js} +1 -1
  77. package/chunks/{ja-3B6V5KS7.js → ja-A5OQLXUZ.js} +6 -6
  78. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-IM4UB4P4.js} +1 -1
  79. package/chunks/{ls-YWZU3FYL.js → ls-DEAFYDVV.js} +1 -1
  80. package/chunks/{lsp-4CJDKEEC.js → lsp-DL7W47VY.js} +1 -1
  81. package/chunks/matildaAgentContentGenerator-57EIU5XE.js +8 -0
  82. package/chunks/mcp-client-X7LEGSP3.js +3 -0
  83. package/chunks/monitor-KPWTMH3V.js +32 -0
  84. package/chunks/{multipart-parser-JI75T2O5.js → multipart-parser-FKHYAVGR.js} +1 -1
  85. package/chunks/notebook-edit-3ZH5M2TC.js +17 -0
  86. package/chunks/openaiContentGenerator-6PXSD3T7.js +37 -0
  87. package/chunks/{pt-KP2JCPUY.js → pt-RG3S3KA7.js} +6 -6
  88. package/chunks/read-file-JNS7WRUP.js +3 -0
  89. package/chunks/ripGrep-ICJDGIIV.js +3 -0
  90. package/chunks/{ru-K7IQQKHC.js → ru-5S5HLRT7.js} +5 -5
  91. package/chunks/scheduler-QC2PPMFP.js +8 -0
  92. package/chunks/{send-message-OO2HAKCC.js → send-message-V2WYLN5X.js} +1 -1
  93. package/chunks/{serve-ZQX2WBLF.js → serve-NUVQULZJ.js} +59 -48
  94. package/chunks/shell-5LNI7URE.js +3 -0
  95. package/chunks/{skill-KDM3UUML.js → skill-QFATRHQW.js} +1 -1
  96. package/chunks/src-6UPZ7TVB.js +3 -0
  97. package/chunks/src-LZEU4AYF.js +5 -0
  98. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-WL6ZHUUN.js} +1 -1
  99. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-3KW6SQAF.js} +1 -1
  100. package/chunks/task-create-PNW5SN27.js +3 -0
  101. package/chunks/{task-detach-I67ZE5MX.js → task-detach-B7PDPFBA.js} +1 -1
  102. package/chunks/task-list-GGZATGK5.js +9 -0
  103. package/chunks/{task-stop-ERI5X4AO.js → task-stop-UKBBE2KG.js} +1 -1
  104. package/chunks/{task-update-CD3W556L.js → task-update-4RHVUBUV.js} +1 -1
  105. package/chunks/{team-create-F4KQRGMB.js → team-create-2TJC3X57.js} +1 -1
  106. package/chunks/team-delete-4UJ7SU65.js +8 -0
  107. package/chunks/todoWrite-NEBVKOSG.js +3 -0
  108. package/chunks/{tool-search-JFCD5W5M.js → tool-search-R5GS64YR.js} +1 -1
  109. package/chunks/tree-sitter-bash-2SWKO5B7.js +3 -0
  110. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-H3XJMAEF.js} +17 -17
  111. package/chunks/{web-search-OX2DPEVN.js → web-search-Q6RWPEIB.js} +1 -1
  112. package/chunks/{workflow-SEFYGBED.js → workflow-3A7KN3E3.js} +2 -2
  113. package/chunks/write-file-O7Q6SKZC.js +15 -0
  114. package/cli.js +509 -495
  115. package/locales/ca.js +2 -28
  116. package/locales/de.js +2 -28
  117. package/locales/en.js +2 -30
  118. package/locales/fr.js +2 -30
  119. package/locales/ja.js +2 -28
  120. package/locales/pt.js +2 -28
  121. package/locales/ru.js +2 -28
  122. package/package.json +2 -2
  123. package/sandbox-macos-permissive-closed.sb +0 -1
  124. package/sandbox-macos-permissive-open.sb +0 -1
  125. package/sandbox-macos-permissive-proxied.sb +0 -1
  126. package/sandbox-macos-restrictive-closed.sb +3 -1
  127. package/sandbox-macos-restrictive-open.sb +3 -1
  128. package/sandbox-macos-restrictive-proxied.sb +3 -1
  129. package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
  130. package/bundled/mainy/docs/features/channels/feishu.md +0 -186
  131. package/bundled/mainy/docs/features/channels/weixin.md +0 -106
  132. package/bundled/mainy/docs/integration-jetbrains.md +0 -81
  133. package/bundled/mainy/docs/integration-zed.md +0 -72
  134. package/chunks/agent-ZFZ4HJQC.js +0 -3
  135. package/chunks/agent-headless-KH2BKLP7.js +0 -3
  136. package/chunks/anthropicContentGenerator-IYZILRDW.js +0 -39
  137. package/chunks/chunk-25NCTG5H.js +0 -184
  138. package/chunks/chunk-2HQMJ2IU.js +0 -8
  139. package/chunks/chunk-3YLXGE6T.js +0 -8
  140. package/chunks/chunk-4F4DA5UI.js +0 -8
  141. package/chunks/chunk-4J6DC24J.js +0 -59
  142. package/chunks/chunk-4Q2SNBUH.js +0 -18
  143. package/chunks/chunk-6GBNB5Z2.js +0 -3
  144. package/chunks/chunk-G7R2XEEF.js +0 -7
  145. package/chunks/chunk-GHBKFIHC.js +0 -35
  146. package/chunks/chunk-GUFIMKF5.js +0 -65
  147. package/chunks/chunk-HWOQNYAO.js +0 -27
  148. package/chunks/chunk-LJR4RZZ2.js +0 -3
  149. package/chunks/chunk-NIQK6NX3.js +0 -37
  150. package/chunks/chunk-NVM7W7TG.js +0 -101
  151. package/chunks/chunk-O44XK65C.js +0 -8
  152. package/chunks/chunk-OA56BXPD.js +0 -3
  153. package/chunks/chunk-ODZOYHIC.js +0 -8
  154. package/chunks/chunk-PA6532AY.js +0 -6
  155. package/chunks/chunk-QFNFLE2I.js +0 -2625
  156. package/chunks/chunk-QH7736R5.js +0 -8
  157. package/chunks/chunk-QN6WSWMM.js +0 -9
  158. package/chunks/chunk-QN6Y6NPA.js +0 -3
  159. package/chunks/chunk-RK2AKQAX.js +0 -39
  160. package/chunks/chunk-SDTWBD62.js +0 -8
  161. package/chunks/chunk-SUH3UUWZ.js +0 -25
  162. package/chunks/chunk-U347OO7S.js +0 -9
  163. package/chunks/chunk-UIRBHC5X.js +0 -3
  164. package/chunks/chunk-VI74YQQO.js +0 -8
  165. package/chunks/chunk-VYZOOSMP.js +0 -30
  166. package/chunks/chunk-W5CGKUM4.js +0 -15
  167. package/chunks/chunk-WRQLIPXW.js +0 -113
  168. package/chunks/chunk-WVY2P6WH.js +0 -26
  169. package/chunks/chunk-WZ75OGYY.js +0 -14
  170. package/chunks/chunk-XCFLI3OC.js +0 -9
  171. package/chunks/chunk-XMZIY7XX.js +0 -13
  172. package/chunks/contextCommand-3GN5CAOK.js +0 -3
  173. package/chunks/dist-7UYRLSLE.js +0 -3
  174. package/chunks/dist-ME6647DQ.js +0 -195
  175. package/chunks/dist-P6SLWL5V.js +0 -42
  176. package/chunks/dist-VG3ZDJ2A.js +0 -28
  177. package/chunks/dist-YTCHM57U.js +0 -23
  178. package/chunks/edit-KX6V4PH3.js +0 -39
  179. package/chunks/exitPlanMode-G3QLIWJ4.js +0 -90
  180. package/chunks/fileFromPath-7UCWPD4W.js +0 -3
  181. package/chunks/geminiContentGenerator-EQEGOXOV.js +0 -8
  182. package/chunks/glob-KSBEWI3E.js +0 -22
  183. package/chunks/matildaAgentContentGenerator-OV4U6DJD.js +0 -8
  184. package/chunks/matildaContentGenerator-ETIAWE22.js +0 -8
  185. package/chunks/matildaOAuth2-WOY7ZS43.js +0 -3
  186. package/chunks/monitor-F4K5HOZX.js +0 -32
  187. package/chunks/notebook-edit-TL7CI5EA.js +0 -17
  188. package/chunks/openaiContentGenerator-MGASUFQL.js +0 -3
  189. package/chunks/read-file-6EAPS2KG.js +0 -3
  190. package/chunks/ripGrep-K6SFFUIE.js +0 -3
  191. package/chunks/scheduler-TKWPD4LP.js +0 -8
  192. package/chunks/shell-AZRK5GIO.js +0 -3
  193. package/chunks/src-SGI6VLOS.js +0 -3
  194. package/chunks/src-WZTRMETQ.js +0 -5
  195. package/chunks/task-create-EBJD55TB.js +0 -3
  196. package/chunks/task-list-5BGX4G5N.js +0 -9
  197. package/chunks/team-delete-5U3GBFKJ.js +0 -8
  198. package/chunks/todoWrite-YGG6AZ3A.js +0 -3
  199. package/chunks/tree-sitter-bash-XNCMPQBK.js +0 -3
  200. package/chunks/write-file-UAGVBZMC.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-XCFLI3OC.js";import{c as Q}from"./chunk-VI74YQQO.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-GO2GA2GY.js";import{Q as S,ba as I}from"./chunk-MH2P4YXC.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,3 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{a as t,b as m,c as p,d as f,e as i,f as c,g as S,h as a}from"./chunk-U347OO7S.js";import{b as r}from"./chunk-GZPNIYVZ.js";import{f as e}from"./chunk-OWGSC52X.js";r();var b=e(c(),1),s=e(f(),1),k=e(t(),1),l=e(m(),1),n=e(p(),1),x=e(S(),1),o=e(i(),1),W=e(a(),1);var d=o.default;export{o as a,W as b,d as c};
@@ -1,37 +0,0 @@
1
- // Force strict mode and setup for ESM
2
- "use strict";
3
- import{l as k}from"./chunk-4YVN5HXG.js";import{Nb as It,Ub as St}from"./chunk-QFNFLE2I.js";import{a as Tt}from"./chunk-SPW5DXX4.js";import{m as Ct}from"./chunk-SUH3UUWZ.js";import{Gc as ht,h as nt}from"./chunk-25NCTG5H.js";import{p as st}from"./chunk-T4P4KEDW.js";import{b as C}from"./chunk-GZPNIYVZ.js";import{d as gt,f as Bt}from"./chunk-OWGSC52X.js";var Mt=gt(i=>{"use strict";C();var at=Symbol.for("react.transitional.element"),$t=Symbol.for("react.portal"),Gt=Symbol.for("react.fragment"),jt=Symbol.for("react.strict_mode"),Wt=Symbol.for("react.profiler"),qt=Symbol.for("react.consumer"),Ft=Symbol.for("react.context"),Yt=Symbol.for("react.forward_ref"),Kt=Symbol.for("react.suspense"),Jt=Symbol.for("react.memo"),kt=Symbol.for("react.lazy"),zt=Symbol.for("react.activity"),xt=Symbol.iterator;function Qt(t){return t===null||typeof t!="object"?null:(t=xt&&t[xt]||t["@@iterator"],typeof t=="function"?t:null)}var Rt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},vt=Object.assign,Et={};function v(t,e,s){this.props=t,this.context=e,this.refs=Et,this.updater=s||Rt}v.prototype.isReactComponent={};v.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};v.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function At(){}At.prototype=v.prototype;function ut(t,e,s){this.props=t,this.context=e,this.refs=Et,this.updater=s||Rt}var mt=ut.prototype=new At;mt.constructor=ut;vt(mt,v.prototype);mt.isPureReactComponent=!0;var bt=Array.isArray;function it(){}var p={H:null,A:null,T:null,S:null},wt=Object.prototype.hasOwnProperty;function lt(t,e,s){var o=s.ref;return{$$typeof:at,type:t,key:e,ref:o!==void 0?o:null,props:s}}function Vt(t,e){return lt(t.type,e,t.props)}function pt(t){return typeof t=="object"&&t!==null&&t.$$typeof===at}function Xt(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(s){return e[s]})}var _t=/\/+/g;function rt(t,e){return typeof t=="object"&&t!==null&&t.key!=null?Xt(""+t.key):e.toString(36)}function Zt(t){switch(t.status){case"fulfilled":return t.value;case"rejected":throw t.reason;default:switch(typeof t.status=="string"?t.then(it,it):(t.status="pending",t.then(function(e){t.status==="pending"&&(t.status="fulfilled",t.value=e)},function(e){t.status==="pending"&&(t.status="rejected",t.reason=e)})),t.status){case"fulfilled":return t.value;case"rejected":throw t.reason}}throw t}function R(t,e,s,o,n){var a=typeof t;(a==="undefined"||a==="boolean")&&(t=null);var m=!1;if(t===null)m=!0;else switch(a){case"bigint":case"string":case"number":m=!0;break;case"object":switch(t.$$typeof){case at:case $t:m=!0;break;case kt:return m=t._init,R(m(t._payload),e,s,o,n)}}if(m)return n=n(t),m=o===""?"."+rt(t,0):o,bt(n)?(s="",m!=null&&(s=m.replace(_t,"$&/")+"/"),R(n,e,s,"",function(g){return g})):n!=null&&(pt(n)&&(n=Vt(n,s+(n.key==null||t&&t.key===n.key?"":(""+n.key).replace(_t,"$&/")+"/")+m)),e.push(n)),1;m=0;var d=o===""?".":o+":";if(bt(t))for(var c=0;c<t.length;c++)o=t[c],a=d+rt(o,c),m+=R(o,e,s,a,n);else if(c=Qt(t),typeof c=="function")for(t=c.call(t),c=0;!(o=t.next()).done;)o=o.value,a=d+rt(o,c++),m+=R(o,e,s,a,n);else if(a==="object"){if(typeof t.then=="function")return R(Zt(t),e,s,o,n);throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.")}return m}function B(t,e,s){if(t==null)return t;var o=[],n=0;return R(t,o,"","",function(a){return e.call(s,a,n++)}),o}function te(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(s){(t._status===0||t._status===-1)&&(t._status=1,t._result=s)},function(s){(t._status===0||t._status===-1)&&(t._status=2,t._result=s)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ht=typeof reportError=="function"?reportError:function(t){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var e=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof t=="object"&&t!==null&&typeof t.message=="string"?String(t.message):String(t),error:t});if(!window.dispatchEvent(e))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",t);return}console.error(t)},ee={map:B,forEach:function(t,e,s){B(t,function(){e.apply(this,arguments)},s)},count:function(t){var e=0;return B(t,function(){e++}),e},toArray:function(t){return B(t,function(e){return e})||[]},only:function(t){if(!pt(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};i.Activity=zt;i.Children=ee;i.Component=v;i.Fragment=Gt;i.Profiler=Wt;i.PureComponent=ut;i.StrictMode=jt;i.Suspense=Kt;i.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=p;i.__COMPILER_RUNTIME={__proto__:null,c:function(t){return p.H.useMemoCache(t)}};i.cache=function(t){return function(){return t.apply(null,arguments)}};i.cacheSignal=function(){return null};i.cloneElement=function(t,e,s){if(t==null)throw Error("The argument must be a React element, but you passed "+t+".");var o=vt({},t.props),n=t.key;if(e!=null)for(a in e.key!==void 0&&(n=""+e.key),e)!wt.call(e,a)||a==="key"||a==="__self"||a==="__source"||a==="ref"&&e.ref===void 0||(o[a]=e[a]);var a=arguments.length-2;if(a===1)o.children=s;else if(1<a){for(var m=Array(a),d=0;d<a;d++)m[d]=arguments[d+2];o.children=m}return lt(t.type,n,o)};i.createContext=function(t){return t={$$typeof:Ft,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider=t,t.Consumer={$$typeof:qt,_context:t},t};i.createElement=function(t,e,s){var o,n={},a=null;if(e!=null)for(o in e.key!==void 0&&(a=""+e.key),e)wt.call(e,o)&&o!=="key"&&o!=="__self"&&o!=="__source"&&(n[o]=e[o]);var m=arguments.length-2;if(m===1)n.children=s;else if(1<m){for(var d=Array(m),c=0;c<m;c++)d[c]=arguments[c+2];n.children=d}if(t&&t.defaultProps)for(o in m=t.defaultProps,m)n[o]===void 0&&(n[o]=m[o]);return lt(t,a,n)};i.createRef=function(){return{current:null}};i.forwardRef=function(t){return{$$typeof:Yt,render:t}};i.isValidElement=pt;i.lazy=function(t){return{$$typeof:kt,_payload:{_status:-1,_result:t},_init:te}};i.memo=function(t,e){return{$$typeof:Jt,type:t,compare:e===void 0?null:e}};i.startTransition=function(t){var e=p.T,s={};p.T=s;try{var o=t(),n=p.S;n!==null&&n(s,o),typeof o=="object"&&o!==null&&typeof o.then=="function"&&o.then(it,Ht)}catch(a){Ht(a)}finally{e!==null&&s.types!==null&&(e.types=s.types),p.T=e}};i.unstable_useCacheRefresh=function(){return p.H.useCacheRefresh()};i.use=function(t){return p.H.use(t)};i.useActionState=function(t,e,s){return p.H.useActionState(t,e,s)};i.useCallback=function(t,e){return p.H.useCallback(t,e)};i.useContext=function(t){return p.H.useContext(t)};i.useDebugValue=function(){};i.useDeferredValue=function(t,e){return p.H.useDeferredValue(t,e)};i.useEffect=function(t,e){return p.H.useEffect(t,e)};i.useEffectEvent=function(t){return p.H.useEffectEvent(t)};i.useId=function(){return p.H.useId()};i.useImperativeHandle=function(t,e,s){return p.H.useImperativeHandle(t,e,s)};i.useInsertionEffect=function(t,e){return p.H.useInsertionEffect(t,e)};i.useLayoutEffect=function(t,e){return p.H.useLayoutEffect(t,e)};i.useMemo=function(t,e){return p.H.useMemo(t,e)};i.useOptimistic=function(t,e){return p.H.useOptimistic(t,e)};i.useReducer=function(t,e,s){return p.H.useReducer(t,e,s)};i.useRef=function(t){return p.H.useRef(t)};i.useState=function(t){return p.H.useState(t)};i.useSyncExternalStore=function(t,e,s){return p.H.useSyncExternalStore(t,e,s)};i.useTransition=function(){return p.H.useTransition()};i.version="19.2.4"});var Dt=gt((de,Pt)=>{"use strict";C();Pt.exports=Mt()});C();C();C();var fe=Bt(Dt(),1);var oe=["achieved","aborted","failed"];function ge(t){return oe.includes(t)}function ne(t,e){return t>=e.hard?"hard":t>=e.auto?"auto":t>=e.warn?"warn":"safe"}function T(t){if(!t||t.length===0)return 0;let e=0,s=0;for(let o=0;o<t.length;o++)t.charCodeAt(o)<128?e++:s++;return Math.ceil(e/4+s*1.5)}function se(t){if(!t||t.trim().length===0)return[];let e=[],s=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g,o;for(;(o=s.exec(t))!==null;){let n=o[1],a=o[2];e.push({path:n,tokens:T(a)})}return e.length===0&&t.trim().length>0&&e.push({path:k("memory"),tokens:T(t)}),e}async function re(t,e){let s=t.getModelDisplayName()||"unknown",o=t.getContentGeneratorConfig(),n=o.contextWindowSize??131072,a=nt.getLastPromptTokenCount(),m=nt.getLastCachedContentTokenCount(),d=It(void 0,s),c=T(d),g=t.getToolRegistry(),M=g?g.getAllTools():[],r=g?g.getFunctionDeclarations():[],P=JSON.stringify(r),_=T(P),H=[],x=[];for(let u of M){if(u.shouldDefer&&!u.alwaysLoad&&!g?.isDeferredToolRevealed(u.name))continue;let h=JSON.stringify(u.schema),S=T(h);u instanceof ht?x.push({name:`${u.serverName}__${u.serverToolName||u.name}`,tokens:S}):u.name!==st.SKILL&&H.push({name:u.name,tokens:S})}let l=t.getUserMemory(),y=se(l),$=y.reduce((u,h)=>u+h.tokens,0),E=M.find(u=>u.name===st.SKILL),G=E?T(JSON.stringify(E.schema)):0,Nt=E&&"getLoadedSkillNames"in E?E.getLoadedSkillNames():new Set,dt=t.getSkillManager(),Ut=dt?await dt.listSkills():[],D=0,j=Ut.map(u=>{let h=T(`<skill>
4
- <name>
5
- ${u.name}
6
- </name>
7
- <description>
8
- ${u.description} (${u.level})
9
- </description>
10
- <location>
11
- ${u.level}
12
- </location>
13
- </skill>`),S=Nt.has(u.name),A;if(S&&u.body){let et=u.filePath?u.filePath.replace(/\/[^/]+$/,""):"";A=T(Tt(et,u.body)),D+=A}return{name:u.name,tokens:h,loaded:S,bodyTokens:A}}),yt=G+D,Lt=o.samplingParams?.max_tokens??0,W=St(n-Lt),q=Math.max(0,Math.round(n-W.auto)),N=c+_+$+D,F=a===0,Y=x.reduce((u,h)=>u+h.tokens,0),I,U,K,J,L,z,O,Q,V,X,Z,tt;if(F)I=0,U=c,z=yt,K=Math.max(0,_-G-Y),J=Y,L=$,O=0,Q=Math.max(0,n-N-q),V=H,X=x,Z=y,tt=j;else{I=a;let u=N>I?I/N:1;U=Math.round(c*u);let h=Math.round(_*u);L=Math.round($*u),z=Math.round(yt*u);let S=Math.round(Y*u);J=S;let A=Math.round(G*u);K=Math.max(0,h-A-S);let et=U+h+L+Math.round(D*u);m>0?O=Math.max(0,I-m):O=Math.max(0,I-et),Q=Math.max(0,n-I-q);let ot=b=>u<1?b.map(ft=>({...ft,tokens:Math.round(ft.tokens*u)})):b;V=ot(H),X=ot(x),Z=ot(y),tt=u<1?j.map(b=>({...b,tokens:Math.round(b.tokens*u),bodyTokens:b.bodyTokens?Math.round(b.bodyTokens*u):void 0})):j}let Ot={systemPrompt:U,builtinTools:K,mcpTools:J,memoryFiles:L,skills:z,messages:O,freeSpace:Q,autocompactBuffer:q,thresholds:W,currentTier:ne(F?N:a,W)};return{type:"context_usage",modelName:s,totalTokens:I,contextWindowSize:n,breakdown:Ot,builtinTools:e?V:[],mcpTools:e?X:[],memoryFiles:e?Z:[],skills:e?tt:[],isEstimated:F,showDetails:e}}function ct(t){return t>=1e3?`${(t/1e3).toFixed(1)}k`:`${t}`}function f(t,e,s,o=" "){let n=s>0?(e/s*100).toFixed(1):"0.0",a=`${ct(e)} tokens (${n}%)`,m=`${o}${t}`,c=Math.max(1,56-m.length-a.length);return`${m}${" ".repeat(c)}${a}`}function w(t){return Math.round(t).toLocaleString("en-US")}function ie(t){let{modelName:e,totalTokens:s,contextWindowSize:o,breakdown:n,builtinTools:a,mcpTools:m,memoryFiles:d,skills:c,isEstimated:g,showDetails:M}=t,r=[];if(r.push("## Context Usage"),r.push(""),g?(r.push("*No API response yet. Send a message to see actual usage.*"),r.push(""),r.push("**Estimated pre-conversation overhead**"),r.push(`Model: ${e} Context window: ${ct(o)} tokens`),r.push("")):(r.push(`Model: ${e} Context window: ${ct(o)} tokens`),r.push(""),r.push(f("Used",s,o)),r.push(f("Free",n.freeSpace,o)),r.push(""),r.push("**Compaction thresholds**"),r.push(` Effective window: ${w(n.thresholds.effectiveWindow)} (window \u2212 ${w(o-n.thresholds.effectiveWindow)} reserve)`),r.push(` Warn threshold: ${w(n.thresholds.warn)}`),r.push(` Auto threshold: ${w(n.thresholds.auto)}`),r.push(` Hard threshold: ${w(n.thresholds.hard)}`),r.push(` Current tier: ${n.currentTier}`),r.push(""),r.push("**Usage by category**")),r.push(f("System prompt",n.systemPrompt,o)),r.push(f("Built-in tools",n.builtinTools,o)),n.mcpTools>0&&r.push(f("MCP tools",n.mcpTools,o)),r.push(f("Memory files",n.memoryFiles,o)),r.push(f("Skills",n.skills,o)),g||r.push(f("Messages",n.messages,o)),M){let P=[...a].sort((l,y)=>y.tokens-l.tokens),_=[...m].sort((l,y)=>y.tokens-l.tokens),H=[...d].sort((l,y)=>y.tokens-l.tokens),x=[...c].sort((l,y)=>l.loaded!==y.loaded?l.loaded?-1:1:y.tokens+(y.bodyTokens??0)-(l.tokens+(l.bodyTokens??0)));if(P.length>0){r.push(""),r.push("**Built-in tools**");for(let l of P)r.push(f(l.name,l.tokens,o," \u2514 "))}if(_.length>0){r.push(""),r.push("**MCP tools**");for(let l of _)r.push(f(l.name,l.tokens,o," \u2514 "))}if(H.length>0){r.push(""),r.push("**Memory files**");for(let l of H)r.push(f(l.path,l.tokens,o," \u2514 "))}if(x.length>0){r.push(""),r.push("**Skills**");for(let l of x){let y=l.loaded?`${l.name} (active)`:l.name;r.push(f(y,l.tokens,o," \u2514 ")),l.loaded&&l.bodyTokens&&l.bodyTokens>0&&r.push(f("body loaded",l.bodyTokens,o," \u2514 "))}}}else r.push(""),r.push("*Run /context detail for per-item breakdown.*");return r.join(`
14
- `)}var ae={name:"context",get description(){return k('Show context window usage breakdown. Use "/context detail" for per-item breakdown.')},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async(t,e)=>{let s=e?.trim().toLowerCase(),o=s==="detail"||s==="-d",n=t.executionMode??"interactive",{config:a}=t.services;if(!a){if(n==="interactive"){t.ui.addItem({type:"error",text:k("Config not loaded.")},Date.now());return}return{type:"message",messageType:"error",content:k("Config not loaded.")}}let m=await re(a,o);if(n==="interactive"){t.ui.addItem(m,Date.now());return}return{type:"message",messageType:"info",content:ie(m)}},subCommands:[{name:"detail",get description(){return k("Show per-item context usage breakdown.")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:async t=>{await ae.action(t,"detail")}}]};export{Dt as a,ge as b,re as c,ie as d,ae as e};
15
- /**
16
- * @license
17
- * Copyright 2025 Google LLC
18
- * SPDX-License-Identifier: Apache-2.0
19
- */
20
- /**
21
- * @license
22
- * Copyright 2025 Matilda
23
- * SPDX-License-Identifier: Apache-2.0
24
- */
25
- /*! Bundled license information:
26
-
27
- react/cjs/react.production.js:
28
- (**
29
- * @license React
30
- * react.production.js
31
- *
32
- * Copyright (c) Meta Platforms, Inc. and affiliates.
33
- *
34
- * This source code is licensed under the MIT license found in the
35
- * LICENSE file in the root directory of this source tree.
36
- *)
37
- */