@maincode-ai/matilda-code 0.21.10 → 0.21.11-nightly.20261018.c0a604b33

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 (138) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +10 -1
  2. package/bundled/mainy/docs/matilda-serve.md +6 -6
  3. package/chunks/agent-JGPVXC63.js +3 -0
  4. package/chunks/agent-headless-MKWVWSTI.js +3 -0
  5. package/chunks/{anthropicContentGenerator-SFJGSZHT.js → anthropicContentGenerator-IYZILRDW.js} +1 -1
  6. package/chunks/{askUserQuestion-MJ4FTAOQ.js → askUserQuestion-XWHJY3DM.js} +1 -1
  7. package/chunks/{ca-H4HPSGTI.js → ca-EUJBUYX5.js} +1 -1
  8. package/chunks/{chunk-B3NVKOSU.js → chunk-25NCTG5H.js} +63 -54
  9. package/chunks/{chunk-INAZKGGR.js → chunk-2HQMJ2IU.js} +1 -1
  10. package/chunks/{todoWrite-7BZMVNBC.js → chunk-4CSSDBOS.js} +2 -2
  11. package/chunks/{chunk-5PMMY47S.js → chunk-4FVBPNTZ.js} +1 -1
  12. package/chunks/{chunk-LSDMWVW6.js → chunk-5427BPR2.js} +2 -2
  13. package/chunks/{chunk-GC2F575A.js → chunk-6GBNB5Z2.js} +1 -1
  14. package/chunks/{chunk-32PTAACU.js → chunk-ELH4YHJR.js} +1 -1
  15. package/chunks/{chunk-3HUM74NZ.js → chunk-EQGA7LH7.js} +2 -2
  16. package/chunks/{chunk-FWIVFCKF.js → chunk-FFFZ2QMG.js} +1 -1
  17. package/chunks/chunk-GHBKFIHC.js +35 -0
  18. package/chunks/{chunk-EQEQPZLQ.js → chunk-GO2GA2GY.js} +1 -1
  19. package/chunks/{chunk-QHA3ZBRO.js → chunk-GUFIMKF5.js} +1 -1
  20. package/chunks/{chunk-RJX7DK4Y.js → chunk-HWOQNYAO.js} +1 -1
  21. package/chunks/chunk-HYVP4472.js +8 -0
  22. package/chunks/chunk-JJQEEMCE.js +113 -0
  23. package/chunks/chunk-JL4MGYP5.js +2625 -0
  24. package/chunks/{chunk-VWWEEU4V.js → chunk-JXUDKX6D.js} +1 -1
  25. package/chunks/chunk-LXXDSWWA.js +39 -0
  26. package/chunks/chunk-M53RP3YP.js +31 -0
  27. package/chunks/{chunk-VLYRNOD3.js → chunk-MH2P4YXC.js} +10 -10
  28. package/chunks/{chunk-VYTYYCBR.js → chunk-NYEWHSBL.js} +1 -1
  29. package/chunks/{chunk-LIWYWWOK.js → chunk-ODZOYHIC.js} +1 -1
  30. package/chunks/{chunk-DJSOHDUB.js → chunk-OHFTFZDW.js} +1 -1
  31. package/chunks/{chunk-C62LTEOV.js → chunk-P2EJ7L75.js} +2 -2
  32. package/chunks/{chunk-Q2I3ARPJ.js → chunk-QH7736R5.js} +1 -1
  33. package/chunks/chunk-QN6WSWMM.js +9 -0
  34. package/chunks/chunk-SNLH42QJ.js +10 -0
  35. package/chunks/chunk-SPW5DXX4.js +35 -0
  36. package/chunks/{chunk-S7G6QPEP.js → chunk-SUH3UUWZ.js} +1 -1
  37. package/chunks/chunk-T2T2UEPY.js +4 -0
  38. package/chunks/{chunk-6B5BDE7S.js → chunk-T4P4KEDW.js} +8 -8
  39. package/chunks/chunk-VI74YQQO.js +8 -0
  40. package/chunks/{chunk-DCQKJTAX.js → chunk-W5CGKUM4.js} +8 -3
  41. package/chunks/{chunk-32T6RWWT.js → chunk-WHG6N5X2.js} +1 -1
  42. package/chunks/{chunk-XCJYORZX.js → chunk-XCFLI3OC.js} +1 -1
  43. package/chunks/{chunk-EXIO3QHE.js → chunk-XMREPBZQ.js} +9 -9
  44. package/chunks/{chunk-3ZAMYREW.js → chunk-YMIF2DMT.js} +1 -1
  45. package/chunks/{chunk-K3ELACN2.js → chunk-ZWWK3LOA.js} +17 -17
  46. package/chunks/{computer-use-DJV6HTND.js → computer-use-74O2RS5O.js} +7 -7
  47. package/chunks/contextCommand-ORWYIKKD.js +3 -0
  48. package/chunks/{cron-create-BTTPO3JC.js → cron-create-2UI4AT4Q.js} +1 -1
  49. package/chunks/{cron-delete-U55RHRID.js → cron-delete-ZB6BOTFF.js} +1 -1
  50. package/chunks/{cron-list-J4HRR46K.js → cron-list-YYAXNHB6.js} +1 -1
  51. package/chunks/{de-S7F37S4F.js → de-DNEPG7S7.js} +1 -1
  52. package/chunks/{dist-SVKXQXJX.js → dist-ME6647DQ.js} +1 -1
  53. package/chunks/{dist-SCXU6QWY.js → dist-P6SLWL5V.js} +1 -1
  54. package/chunks/{dist-PVENOVGI.js → dist-VG3ZDJ2A.js} +1 -1
  55. package/chunks/{dist-N66KF4KX.js → dist-YTCHM57U.js} +1 -1
  56. package/chunks/{edit-7XEZHXE4.js → edit-OIBH4BLL.js} +1 -1
  57. package/chunks/{en-S6DMCJQZ.js → en-NOD6KQNM.js} +1 -1
  58. package/chunks/{enter-worktree-MR64QLS4.js → enter-worktree-AIU3KJBK.js} +1 -1
  59. package/chunks/{enterPlanMode-UNWCEVYY.js → enterPlanMode-SVXQCL26.js} +1 -1
  60. package/chunks/{exit-worktree-D4BMN6LH.js → exit-worktree-LJPQWUWN.js} +1 -1
  61. package/chunks/{exitPlanMode-AKLFFYT2.js → exitPlanMode-EBNIDKOG.js} +1 -1
  62. package/chunks/{fr-RFJP3KVL.js → fr-2OE5WLJ4.js} +1 -1
  63. package/chunks/{geminiContentGenerator-JBASUS2T.js → geminiContentGenerator-ZZ5QAWZB.js} +1 -1
  64. package/chunks/glob-IT3EACPK.js +22 -0
  65. package/chunks/goal-tools-6QTC3UI7.js +12 -0
  66. package/chunks/grep-3BB6FQKH.js +22 -0
  67. package/chunks/{ja-UTJHPL3M.js → ja-3B6V5KS7.js} +1 -1
  68. package/chunks/{keychain-token-storage-HAFQQIXL.js → keychain-token-storage-54BNK6VH.js} +1 -1
  69. package/chunks/{ls-CLDNF3YS.js → ls-YWZU3FYL.js} +1 -1
  70. package/chunks/{lsp-7SKRKR5Q.js → lsp-4CJDKEEC.js} +1 -1
  71. package/chunks/{matildaAgentContentGenerator-GMDJPWES.js → matildaAgentContentGenerator-NFEYGURX.js} +1 -1
  72. package/chunks/matildaContentGenerator-SXG4OZTI.js +8 -0
  73. package/chunks/{matildaOAuth2-W2DQO2NK.js → matildaOAuth2-WOY7ZS43.js} +1 -1
  74. package/chunks/monitor-6O6VBEJI.js +32 -0
  75. package/chunks/notebook-edit-STXOZN2Q.js +17 -0
  76. package/chunks/{openaiContentGenerator-XDOQRO4G.js → openaiContentGenerator-43XA6RSY.js} +1 -1
  77. package/chunks/{pt-KXMOTADP.js → pt-KP2JCPUY.js} +1 -1
  78. package/chunks/read-file-6EAPS2KG.js +3 -0
  79. package/chunks/ripGrep-PZRHD4DM.js +3 -0
  80. package/chunks/{ru-EWGWZPQH.js → ru-K7IQQKHC.js} +1 -1
  81. package/chunks/scheduler-5HVKP7US.js +8 -0
  82. package/chunks/{send-message-XXRROIL7.js → send-message-OO2HAKCC.js} +1 -1
  83. package/chunks/{serve-4MDSDWP7.js → serve-GNAEOLUJ.js} +31 -31
  84. package/chunks/shell-OLBIQ5NE.js +3 -0
  85. package/chunks/{skill-JIISRKQN.js → skill-ED2FVJW3.js} +1 -1
  86. package/chunks/src-DNZKTGVD.js +3 -0
  87. package/chunks/{symbol-search-3MVTK4KV.js → symbol-search-ALYOX5JN.js} +1 -1
  88. package/chunks/{syntheticOutput-QEUQIVQJ.js → syntheticOutput-UASKABJH.js} +1 -1
  89. package/chunks/task-create-EBJD55TB.js +3 -0
  90. package/chunks/task-detach-I67ZE5MX.js +9 -0
  91. package/chunks/{task-list-ZEJTNZ2O.js → task-list-5BGX4G5N.js} +1 -1
  92. package/chunks/{task-stop-JO3CXG2K.js → task-stop-ERI5X4AO.js} +1 -1
  93. package/chunks/{task-update-3YY37VFN.js → task-update-CD3W556L.js} +1 -1
  94. package/chunks/{team-create-GMI5DIH7.js → team-create-SHNPWPTO.js} +1 -1
  95. package/chunks/{team-delete-4YYLUV23.js → team-delete-5U3GBFKJ.js} +1 -1
  96. package/chunks/todoWrite-YGG6AZ3A.js +3 -0
  97. package/chunks/{tool-search-OWJC3UTX.js → tool-search-JFCD5W5M.js} +1 -1
  98. package/chunks/{web-fetch-K575OWZ7.js → web-fetch-REWGIRWQ.js} +1 -1
  99. package/chunks/{web-search-F6JRBXFV.js → web-search-OX2DPEVN.js} +1 -1
  100. package/chunks/{workflow-H5DWTI5W.js → workflow-WASIJJUX.js} +2 -2
  101. package/chunks/write-file-VHYWOKNS.js +15 -0
  102. package/cli.js +480 -475
  103. package/locales/ca.js +8 -2
  104. package/locales/de.js +9 -2
  105. package/locales/en.js +15 -8
  106. package/locales/fr.js +9 -2
  107. package/locales/ja.js +8 -2
  108. package/locales/pt.js +8 -2
  109. package/locales/ru.js +9 -2
  110. package/package.json +2 -2
  111. package/sandbox-macos-restrictive-closed.sb +4 -0
  112. package/sandbox-macos-restrictive-open.sb +4 -0
  113. package/sandbox-macos-restrictive-proxied.sb +4 -0
  114. package/chunks/agent-2ZM5WMHY.js +0 -3
  115. package/chunks/agent-headless-PX4INULZ.js +0 -3
  116. package/chunks/chunk-2UDXLDSZ.js +0 -34
  117. package/chunks/chunk-34DXSYJZ.js +0 -34
  118. package/chunks/chunk-ESSYHTAZ.js +0 -8
  119. package/chunks/chunk-FRL6KOLY.js +0 -35
  120. package/chunks/chunk-I7TAYS6D.js +0 -108
  121. package/chunks/chunk-JSFA3NEP.js +0 -5
  122. package/chunks/chunk-ROETRE5J.js +0 -9
  123. package/chunks/chunk-RYLWDCCN.js +0 -2594
  124. package/chunks/chunk-TZIDSCTF.js +0 -31
  125. package/chunks/contextCommand-TAFFF6V7.js +0 -3
  126. package/chunks/glob-3QKPKP7Z.js +0 -22
  127. package/chunks/grep-6CL6HJ5Y.js +0 -22
  128. package/chunks/matildaContentGenerator-EFK4QDRS.js +0 -8
  129. package/chunks/monitor-6W2R25LH.js +0 -32
  130. package/chunks/notebook-edit-WL6MZ6AW.js +0 -17
  131. package/chunks/read-file-J5UBJYDO.js +0 -3
  132. package/chunks/ripGrep-2AMYRBCZ.js +0 -3
  133. package/chunks/scheduler-LFSCKDU6.js +0 -8
  134. package/chunks/shell-SMTFAOAE.js +0 -3
  135. package/chunks/src-OF7NIVIL.js +0 -3
  136. package/chunks/task-create-AEJQ73GE.js +0 -3
  137. package/chunks/update-goal-CF6G57J7.js +0 -16
  138. package/chunks/write-file-RUHYPLKF.js +0 -15
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as f}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-EQEQPZLQ.js";import{H as d,P as m,aa as p}from"./chunk-VLYRNOD3.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=p("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new f,h.set(e,t)),t}function c(e){return s.join(m.getGlobalTempDir(),d(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await g(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
3
+ import{b as f}from"./chunk-TISQNFB5.js";import{c as g}from"./chunk-GO2GA2GY.js";import{H as d,Q as m,ba as p}from"./chunk-MH2P4YXC.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=p("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new f,h.set(e,t)),t}function c(e){return s.join(m.getGlobalTempDir(),d(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await g(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{g as w,i as x}from"./chunk-QHA3ZBRO.js";import{aa as I}from"./chunk-VLYRNOD3.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};
3
+ import{g as w,i as x}from"./chunk-GUFIMKF5.js";import{ba as I}from"./chunk-MH2P4YXC.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
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{l as k}from"./chunk-C62LTEOV.js";import{Mb as It,Sb as St}from"./chunk-RYLWDCCN.js";import{c as Tt}from"./chunk-FRL6KOLY.js";import{m as Ct}from"./chunk-S7G6QPEP.js";import{Cc as ht,h as nt}from"./chunk-B3NVKOSU.js";import{p as st}from"./chunk-6B5BDE7S.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>
3
+ import{l as k}from"./chunk-P2EJ7L75.js";import{Nb as It,Ub as St}from"./chunk-JL4MGYP5.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
4
  <name>
5
5
  ${u.name}
6
6
  </name>
@@ -1,10 +1,10 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Sh as T}from"./chunk-RYLWDCCN.js";import{P as b}from"./chunk-VLYRNOD3.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
3
+ import{_h as T}from"./chunk-JL4MGYP5.js";import{Q as b}from"./chunk-MH2P4YXC.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
7
- `)},W=()=>{console.clear()};o();import*as u from"node:fs";import*as f from"node:path";import{pathToFileURL as N}from"node:url";o();var p=[{code:"en",id:"en-AU",fullName:"Australian English",nativeName:"English (AU)"},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function A(e){return e.trim().replace(/_/g,"-").toLowerCase()}var M=new Set(["zh","zh-cn","zh-hans","zh-sg","zh-tw","zh-hk","zh-mo","zh-hant","chinese","traditional chinese","simplified chinese","\u4E2D\u6587","\u7B80\u4F53\u4E2D\u6587","\u7E41\u9AD4\u4E2D\u6587","\u7E41\u4F53\u4E2D\u6587"]);function E(e){let t=A(e);return t?M.has(t)?!0:t.startsWith("zh-")||t.startsWith("zh.")||t.startsWith("zh@"):!1}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function z(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function l(e){let t=A(e);if(!t)return;if(t==="english"||t==="australian"||t==="australian-english")return"en";let n;for(let r of p){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=z(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function C(e){let t=l(e);return(t?p.find(r=>r.code===t):void 0)?.fullName||"English"}function q(){return[{value:"auto",label:"Auto (detect from system)"},...p.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var I=w({"./locales/ca.js":()=>import("./ca-H4HPSGTI.js"),"./locales/de.js":()=>import("./de-S7F37S4F.js"),"./locales/en.js":()=>import("./en-S6DMCJQZ.js"),"./locales/fr.js":()=>import("./fr-RFJP3KVL.js"),"./locales/ja.js":()=>import("./ja-UTJHPL3M.js"),"./locales/pt.js":()=>import("./pt-KXMOTADP.js"),"./locales/ru.js":()=>import("./ru-EWGWZPQH.js")});var y="en",v={},i={},S={},R=()=>f.join(T(import.meta.url),"locales"),U=()=>f.join(b.getGlobalMatildaDir(),"locales");var D=(e,t=!1)=>{let n=t?U():R();return f.join(n,`${e}.js`)};function O(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=l(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=l(t);if(n)return n}catch{}return"en"}async function P(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){try{let t=await I(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function j(e){if(i[e])return i[e];let t=S[e];if(t)return t;let n=(async()=>{let r=D(e,!0);if(u.existsSync(U())&&u.existsSync(r)){let s=await P(N(r).href);if(s.translations)return i[e]=s.translations,s.translations;m(`Failed to load translations from user directory for ${e}: ${s.error.message}`)}let a=D(e,!1),x=[];u.existsSync(R())&&u.existsSync(a)&&x.push(N(a).href);let c;for(let s of x){let g=await P(s);if(g.translations)return i[e]=g.translations,g.translations;c=g.error}let d=await $(e);return d.translations?(i[e]=d.translations,d.translations):(c=d.error,c&&m(`Failed to load JS translations for ${e}: ${c.message}`),i[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function _(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function F(e){return e==="auto"?O():E(e)?"en":l(e)??e}async function G(e){y=F(e),v=await j(y)}function le(){return y}function ue(e,t){let n=v[e]??e;return Array.isArray(n)?e:_(n,t)}function ce(e){let t=v[e];return Array.isArray(t)?t:[]}async function de(e){await G(e??"auto")}export{B as a,m as b,W as c,p as d,E as e,l as f,C as g,q as h,O as i,G as j,le as k,ue as l,ce as m,de as n};
7
+ `)},W=()=>{console.clear()};o();import*as u from"node:fs";import*as f from"node:path";import{pathToFileURL as N}from"node:url";o();var p=[{code:"en",id:"en-AU",fullName:"Australian English",nativeName:"English (AU)"},{code:"ru",id:"ru-RU",fullName:"Russian",nativeName:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"de",id:"de-DE",fullName:"German",nativeName:"Deutsch"},{code:"ja",id:"ja-JP",fullName:"Japanese",nativeName:"\u65E5\u672C\u8A9E"},{code:"pt",id:"pt-BR",fullName:"Portuguese",nativeName:"Portugu\xEAs"},{code:"fr",id:"fr-FR",fullName:"French",nativeName:"Fran\xE7ais"},{code:"ca",id:"ca-ES",fullName:"Catalan",nativeName:"Catal\xE0"}];function A(e){return e.trim().replace(/_/g,"-").toLowerCase()}var M=new Set(["zh","zh-cn","zh-hans","zh-sg","zh-tw","zh-hk","zh-mo","zh-hant","chinese","traditional chinese","simplified chinese","\u4E2D\u6587","\u7B80\u4F53\u4E2D\u6587","\u7E41\u9AD4\u4E2D\u6587","\u7E41\u4F53\u4E2D\u6587"]);function E(e){let t=A(e);return t?M.has(t)?!0:t.startsWith("zh-")||t.startsWith("zh.")||t.startsWith("zh@"):!1}function k(e,t){return e===t||e.startsWith(`${t}-`)||e.startsWith(`${t}.`)||e.startsWith(`${t}@`)}function z(e,t){let n=t.code.toLowerCase(),r=t.id.toLowerCase();if(k(e,r))return r.length;if(k(e,n))return n.length}function l(e){let t=A(e);if(!t)return;if(t==="english"||t==="australian"||t==="australian-english")return"en";let n;for(let r of p){if(t===r.fullName.toLowerCase()||r.nativeName&&t===r.nativeName.toLowerCase())return r.code;let a=z(t,r);a!==void 0&&(!n||a>n.tokenLength)&&(n={code:r.code,tokenLength:a})}return n?.code}function C(e){let t=l(e);return(t?p.find(r=>r.code===t):void 0)?.fullName||"English"}function q(){return[{value:"auto",label:"Auto (detect from system)"},...p.map(e=>({value:e.code,label:e.nativeName?`${e.nativeName} (${e.fullName})`:`${e.fullName} (${e.id})`}))]}o();function h(e){return Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function L(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length>0}o();var I=w({"./locales/ca.js":()=>import("./ca-EUJBUYX5.js"),"./locales/de.js":()=>import("./de-DNEPG7S7.js"),"./locales/en.js":()=>import("./en-NOD6KQNM.js"),"./locales/fr.js":()=>import("./fr-2OE5WLJ4.js"),"./locales/ja.js":()=>import("./ja-3B6V5KS7.js"),"./locales/pt.js":()=>import("./pt-KP2JCPUY.js"),"./locales/ru.js":()=>import("./ru-K7IQQKHC.js")});var y="en",v={},i={},S={},R=()=>f.join(T(import.meta.url),"locales"),U=()=>f.join(b.getGlobalMatildaDir(),"locales");var D=(e,t=!1)=>{let n=t?U():R();return f.join(n,`${e}.js`)};function O(){let e=process.env.MATILDA_CODE_LANG||process.env.LANG;if(e){let t=l(e);if(t)return t}try{let t=Intl.DateTimeFormat().resolvedOptions().locale,n=l(t);if(n)return n}catch{}return"en"}async function P(e){try{let t=await import(e),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function $(e){try{let t=await I(`./locales/${e}.js`),n=h(t);return L(n)?{translations:n}:{error:new Error("Module loaded but result is empty or invalid")}}catch(t){return{error:t instanceof Error?t:new Error(String(t))}}}async function j(e){if(i[e])return i[e];let t=S[e];if(t)return t;let n=(async()=>{let r=D(e,!0);if(u.existsSync(U())&&u.existsSync(r)){let s=await P(N(r).href);if(s.translations)return i[e]=s.translations,s.translations;m(`Failed to load translations from user directory for ${e}: ${s.error.message}`)}let a=D(e,!1),x=[];u.existsSync(R())&&u.existsSync(a)&&x.push(N(a).href);let c;for(let s of x){let g=await P(s);if(g.translations)return i[e]=g.translations,g.translations;c=g.error}let d=await $(e);return d.translations?(i[e]=d.translations,d.translations):(c=d.error,c&&m(`Failed to load JS translations for ${e}: ${c.message}`),i[e]={},{})})();return S[e]=n,n.finally(()=>{delete S[e]}),n}function _(e,t){return t?e.replace(/\{\{(\w+)\}\}/g,(n,r)=>t[r]??n):e}function F(e){return e==="auto"?O():E(e)?"en":l(e)??e}async function G(e){y=F(e),v=await j(y)}function le(){return y}function ue(e,t){let n=v[e]??e;return Array.isArray(n)?e:_(n,t)}function ce(e){let t=v[e];return Array.isArray(t)?t:[]}async function de(e){await G(e??"auto")}export{B as a,m as b,W as c,p as d,E as e,l as f,C as g,q as h,O as i,G as j,le as k,ue as l,ce as m,de as n};
8
8
  /**
9
9
  * @license
10
10
  * Copyright 2025 Matilda Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{e as l}from"./chunk-EQEQPZLQ.js";import{P as a,aa as e}from"./chunk-VLYRNOD3.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};
3
+ import{e as l}from"./chunk-GO2GA2GY.js";import{Q as a,ba as e}from"./chunk-MH2P4YXC.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
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{b as h,g}from"./chunk-W5CGKUM4.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-GO2GA2GY.js";import{b as c,ba as b}from"./chunk-MH2P4YXC.js";import{b as p}from"./chunk-GZPNIYVZ.js";import{f as E}from"./chunk-OWGSC52X.js";p();var m=null;function D(e){m=e}function _(){return m}function P(){m=null}function S(e,r,o){return m?(m.enqueueApproval({teammateName:e,teammateColor:r,details:o}),!0):!1}function $(e,r,o,t){return{...e,title:`[${r}] ${e.title}`,onConfirm:async(i,s)=>{await o(i,s)}}}p();var C=E(h(),1);import*as a from"node:fs/promises";import*as u from"node:path";var y=b("AGENTS_TEAM_MAILBOX"),N={retries:{retries:10,minTimeout:5,maxTimeout:100,factor:2,randomize:!0},stale:5e3,onCompromised:e=>{y.debug("mailbox lock compromised:",e?.message??e)}},d=new Map;function O(e){let r=d.get(e);return r||(r=new M,d.set(e,r)),r}function I(e){let r=g(e),o=0;for(let t of d.keys())u.dirname(t)===r&&(d.delete(t),o++);return o}async function T(e,r){return O(e).runExclusive(async()=>{let o=await C.default.lock(e,N);try{return await r()}finally{await o()}})}function x(e,r){return u.join(g(e),`${r}.json`)}async function X(e,r){let o=x(e,r);try{let t=await a.readFile(o,"utf-8");return JSON.parse(t)}catch(t){if(c(t)&&t.code==="ENOENT")return[];throw t}}var L=5*60*1e3;async function A(e,r,o){let t=x(e,r);await v(t),await T(t,async()=>{let i=await k(t),s=Date.now()-L,l=i.filter(f=>{if(!f.read)return!0;let n=Date.parse(f.timestamp);return Number.isNaN(n)||n>=s});l.push(o),await w(t,l)})}async function z(e,r,o){let t=x(e,r);return await v(t),T(t,async()=>{let i=await k(t),s=n=>!n.read&&(o===void 0||n.type===o),l=i.filter(s);if(l.length===0)return[];let f=i.map(n=>s(n)?{...n,read:!0}:n);return await w(t,f),l})}async function G(e,r){let o=x(e,r);try{await a.unlink(o)}catch(t){if(!c(t)||t.code!=="ENOENT")throw t}}async function K(e){let r=g(e);await a.rm(r,{recursive:!0,force:!0}),I(e)}async function Q(e,r,o){await A(e,r,{from:o.from,text:o.text,timestamp:new Date().toISOString(),read:!1,type:o.type,color:o.color,summary:o.summary})}async function v(e){await a.mkdir(u.dirname(e),{recursive:!0});try{await a.writeFile(e,`[]
4
+ `,{flag:"wx"})}catch(r){if(!c(r)||r.code!=="EEXIST")throw r}}async function k(e){try{let r=await a.readFile(e,"utf-8");return JSON.parse(r)}catch(r){if(c(r)&&r.code==="ENOENT")return[];let o=r instanceof Error?r.message:String(r);y.warn(`Quarantining corrupt inbox at ${e}: ${o}`);try{await a.rename(e,`${e}.corrupt-${Date.now()}`)}catch(t){let i=t instanceof Error?t.message:String(t);throw y.warn(`Failed to quarantine ${e}: ${i}`),r instanceof Error?r:new Error(`Failed to read inbox at ${e}: ${o}`)}return[]}}export{D as a,_ as b,P as c,S as d,$ as e,I as f,x as g,X as h,A as i,z as j,G as k,K as l,Q as m};
5
+ /**
6
+ * @license
7
+ * Copyright 2025 Matilda
8
+ * SPDX-License-Identifier: Apache-2.0
9
+ */
@@ -0,0 +1,10 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as c}from"./chunk-HYVP4472.js";import{p as u}from"./chunk-T4P4KEDW.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{AsyncLocalStorage as h}from"node:async_hooks";var a=new h,r=new WeakMap,p={turns:"max_turn_requests",session_turns:"max_turn_requests",loop_detected:"max_turn_requests",continuations:"max_turn_requests",session_tokens:"max_tokens"},k=class{jobs=new Map;joinsJobs;wake;closed=!1;revision=0;task;lastResponse;stop;ended;finished;constructor(e={}){this.joinsJobs=e.joinsJobs??!0}begin(e,t,s=e){this.task||(this.task={startUuid:e,rootUuid:s,recorder:t},this.ended&&this.finish(this.ended).catch(()=>{}))}get taskStartUuid(){return this.task?.startUuid}get taskRef(){return this.task?{startUuid:this.task.startUuid,rootUuid:this.task.rootUuid}:void 0}noteResponse(e){this.lastResponse=e}noteStop(e){this.stop=e}finish(e){let t=this.task;return t?(this.finished??=this.recordOutcome(t,e),this.finished):(this.ended??=e,Promise.resolve(void 0))}async recordOutcome(e,t){let s=this.stop&&(t.outcome==="completed"||t.outcome==="error")?p[this.stop]:t.outcome,i=s==="completed"&&this.lastResponse?.finalAnswer?this.lastResponse:void 0,n=t.limitKind??(s==="max_tokens"||s==="max_turn_requests"?this.stop:void 0);return await e.recorder.recordTaskOutcome({taskStartUuid:e.startUuid,outcome:s,...n?{limitKind:n}:{},...s==="completed"?{finalAnswerUuid:i?i.recordId??i.id:null}:{}}),{outcome:s,...i&&{finalAnswerId:i.id}}}static get current(){return a.getStore()}run(e){return a.run(this,e)}static detached(e){return a.run(void 0,e)}static register(e,t,s){let i=a.getStore();e.originTask??=s?.originTask??i?.taskRef;let n=s?.status==="running"?r.get(s):void 0,o=n??(i?.joinsJobs?i:void 0);if(o){if(n&&s&&n.consume(s),e.completion==="detached"||!n&&e.status!=="running"){o.changed();return}if(r.set(e,o),o.closed){t();return}o.jobs.set(e,t),o.changed()}}static changed(e){e&&r.get(e)?.changed()}static abandoned(e){return r.get(e)?.closed===!0}static detach(e){let t=r.get(e);return!t||t.closed||!t.owns(e)||e.status!=="running"?!1:(e.completion="detached",t.consume(e),t.changed(),!0)}owns(e){return this.jobs.has(e)}consume(e){r.delete(e),this.jobs.delete(e)}get pending(){return this.jobs.size>0}get position(){return this.revision}get paused(){return[...this.jobs.keys()].some(e=>e.status==="paused")}get running(){return[...this.jobs.keys()].filter(e=>e.status==="running")}changed(){this.revision++,this.wake?.()}async wait(e,t,s){this.closed||t.aborted||e!==this.revision||await new Promise(i=>{let n,o=()=>{clearTimeout(n),t.removeEventListener("abort",o),this.wake=void 0,i()};this.wake=o,t.addEventListener("abort",o,{once:!0}),s!==void 0&&(n=setTimeout(o,s))})}close(){this.closed=!0;for(let[e,t]of this.jobs)e.status==="running"&&t();this.changed()}};function g(d,e){let t=s=>{let i=s.description.replace(/[\p{Cc}\s]+/gu," ").trim(),n=Math.max(1,Math.round((e-s.startTime)/6e4));return`background ${s.kind} "${i.length>80?`${i.slice(0,77)}...`:i}" (running ${n} min)`};return{displayText:`Still waiting on ${d.map(t).join(", ")}.`,modelText:d.map(s=>["<task-notification>",`<task-id>${c(s.id)}</task-id>`,`<kind>${s.kind}</kind>`,"<status>running</status>",`<summary>${c(`The ${t(s)} is still running, and this request cannot finish until it does. If the request needs its result, keep waiting. If it should keep running after the request, such as a server or watcher, call ${u.TASK_DETACH}. If it is no longer needed, call ${u.TASK_STOP}.`)}</summary>`,"</task-notification>"].join(`
4
+ `)).join(`
5
+ `)}}export{k as a,g as b};
6
+ /**
7
+ * @license
8
+ * Copyright 2026 Matilda
9
+ * SPDX-License-Identifier: Apache-2.0
10
+ */
@@ -0,0 +1,35 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{a as r}from"./chunk-HYVP4472.js";import{ba as g}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();function h(n,o){return`Base directory for this skill: ${n}
4
+ Important: ALWAYS resolve absolute paths from this base directory when working with skills.
5
+
6
+ ${o}
7
+ `}async function C(n,o){let i=await n.listSkills(),l=o.getDisabledSkillNames(),t=e=>l.has(e.toLowerCase()),s=i.filter(e=>!e.disableModelInvocation&&n.isSkillActive(e)&&!t(e.name)),m=new Set(i.filter(e=>!e.disableModelInvocation&&e.paths&&e.paths.length>0&&!n.isSkillActive(e)&&!t(e.name)).map(e=>e.name)),a=o.getModelInvocableCommandsProvider(),c=a?a():[],k=new Set(i.filter(e=>!e.disableModelInvocation&&!t(e.name)).map(e=>e.name)),d=c.filter(e=>!k.has(e.name)),S=[...s.map(e=>({name:e.name,description:e.description,whenToUse:e.whenToUse,level:e.level})),...d.map(e=>({name:e.name,description:e.description}))];return{availableSkills:s,pendingConditionalSkillNames:m,modelInvocableCommands:d,entries:S}}function u(n,o){let i=n.level!==void 0?0:1,l=o.level!==void 0?0:1;return i!==l?i-l:n.name.localeCompare(o.name)}function H(n){return[...n].sort(u).map(o=>{if(o.level!==void 0){let i=`${r(o.description)}${o.whenToUse?` \u2014 ${r(o.whenToUse)}`:""} (${o.level})`;return`<skill>
8
+ <name>
9
+ ${r(o.name)}
10
+ </name>
11
+ <description>
12
+ ${i}
13
+ </description>
14
+ <location>
15
+ ${o.level}
16
+ </location>
17
+ </skill>`}return`<skill>
18
+ <name>
19
+ ${r(o.name)}
20
+ </name>
21
+ <description>
22
+ ${r(o.description)}
23
+ </description>
24
+ </skill>`}).join(`
25
+ `)}function y(n,o){if(!(!n||!o?.length))for(let i of o)n.addSessionAllowRule(i)}f();var p=g("SKILL_HOOKS");function M(n,o,i){if(!i.hooks)return p.debug(`Skill '${i.name}' has no hooks to register`),0;let l=i.hooks,t=0;for(let s of Object.keys(l)){let m=l[s];if(m)for(let a of m){let c=a.matcher||"";for(let k of a.hooks){if(k.type==="function"){p.debug("Skipping function hook from skill (not supported in frontmatter)");continue}let d=v(k,i.skillRoot);n.addSessionHook(o,s,c,d,{skillRoot:i.skillRoot}),t++,p.debug(`Registered hook for ${s} with matcher '${c}' from skill '${i.name}'`)}}}return t>0&&p.info(`Registered ${t} hooks from skill '${i.name}'`),t}function v(n,o){return n.type==="command"&&o?{...n,env:{...n.env,MATILDA_SKILL_ROOT:o}}:n}export{h as a,C as b,H as c,y as d,M as e};
26
+ /**
27
+ * @license
28
+ * Copyright 2025 Matilda
29
+ * SPDX-License-Identifier: Apache-2.0
30
+ */
31
+ /**
32
+ * @license
33
+ * Copyright 2026 Matilda Team
34
+ * SPDX-License-Identifier: Apache-2.0
35
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{aa as te}from"./chunk-VLYRNOD3.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
3
+ import{ba as te}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";f();var Ne="MATILDA_CODE_PROFILE_RUNTIME";function ne(t=process.env){return t[Ne]==="1"}var W=class{enabled;now;startedAt;requestIndex=0;openAIWireRequestIndex=0;anthropicWireRequestIndex=0;requests=[];openaiWireRequests=[];anthropicWireRequests=[];tools=oe();constructor(e={}){this.enabled=e.enabled??ne(),this.now=e.now??(()=>new Date().toISOString()),this.startedAt=this.now()}reset(e={}){this.enabled=e.enabled??ne(),this.startedAt=this.now(),this.requestIndex=0,this.openAIWireRequestIndex=0,this.anthropicWireRequestIndex=0,this.requests=[],this.openaiWireRequests=[],this.anthropicWireRequests=[],this.tools=oe()}isEnabled(){return this.enabled}recordGenerateContentRequest(e,n){this.enabled&&(this.requestIndex+=1,this.requests.push({index:this.requestIndex,timestamp:this.now(),source:n.source,model:e.model,stream:n.stream,serializedBytes:p(We(e)),contents:re(e.contents),systemInstructionBytes:ve(e.config?.systemInstruction),generationConfigBytes:p(se(e.config)),tools:Me(e.config?.tools)}))}recordOpenAIWireRequest(e){this.enabled&&(this.openAIWireRequestIndex+=1,this.openaiWireRequests.push({index:this.openAIWireRequestIndex,timestamp:this.now(),...Ie(e)}))}recordAnthropicWireRequest(e){this.enabled&&(this.anthropicWireRequestIndex+=1,this.anthropicWireRequests.push({index:this.anthropicWireRequestIndex,timestamp:this.now(),...Le(e)}))}recordToolUse(e,n){if(!this.enabled)return;let o=p(n),r=this.getToolNameDiagnostics(e);r.uses+=1,r.argBytes+=o,r.maxArgBytes=Math.max(r.maxArgBytes,o),this.tools.toolUseCount+=1,this.tools.totalToolUseArgBytes+=o,this.tools.maxToolUseArgBytes=Math.max(this.tools.maxToolUseArgBytes,o)}recordToolResult(e){if(!this.enabled)return;let n=this.getToolNameDiagnostics(e.name);n.results+=1,n.resultBytes+=e.resultBytes,n.maxResultBytes=Math.max(n.maxResultBytes,e.resultBytes),e.isError&&(n.errors+=1,this.tools.toolResultErrorCount+=1),this.tools.toolResultCount+=1,this.tools.totalToolResultBytes+=e.resultBytes,this.tools.maxToolResultBytes=Math.max(this.tools.maxToolResultBytes,e.resultBytes)}snapshot(){return{enabled:this.enabled,startedAt:this.startedAt,requests:this.requests.map(e=>({...e,contents:{...e.contents,roleCounts:{...e.contents.roleCounts}},tools:{...e.tools}})),openaiWireRequests:this.openaiWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),anthropicWireRequests:this.anthropicWireRequests.map(e=>({...e,messageBytesByRole:{...e.messageBytesByRole},topLevelKeys:[...e.topLevelKeys]})),tools:{...this.tools,byName:Object.fromEntries(Object.entries(this.tools.byName).map(([e,n])=>[e,{...n}]))}}}getToolNameDiagnostics(e){let n=this.tools.byName[e];if(n)return n;let o=xe();return this.tools.byName[e]=o,o}},He=new W;function Ie(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function Le(t){let e=b(t),n=Array.isArray(e.messages)?e.messages:[],o=Array.isArray(e.tools)?e.tools:[],r={};for(let u of n){let a=b(u),d=typeof a.role=="string"?a.role:"unknown";r[d]=(r[d]??0)+p(a.content)}return{model:typeof e.model=="string"?e.model:"unknown",stream:e.stream===!0,bodyBytes:p(t),messageCount:n.length,messageBytesByRole:r,systemBytes:p(e.system),toolsCount:o.length,toolSchemaBytes:p(o),topLevelKeys:Object.keys(e).sort()}}function oe(){return{toolUseCount:0,toolResultCount:0,toolResultErrorCount:0,totalToolUseArgBytes:0,maxToolUseArgBytes:0,totalToolResultBytes:0,maxToolResultBytes:0,byName:Object.create(null)}}function xe(){return{uses:0,argBytes:0,maxArgBytes:0,results:0,errors:0,resultBytes:0,maxResultBytes:0}}function re(t){let e={count:0,roleCounts:{},partCount:0,textBytes:0,functionCallCount:0,functionCallArgBytes:0,functionResponseCount:0,functionResponseBytes:0,inlineDataCount:0,inlineDataBytes:0,fileDataCount:0},n=Array.isArray(t)?t:t==null?[]:[t];for(let o of n){if(e.count+=1,typeof o=="string"){e.roleCounts.user=(e.roleCounts.user??0)+1,e.partCount+=1,e.textBytes+=p(o);continue}let r=b(o),u=typeof r.role=="string"?r.role:"unknown";e.roleCounts[u]=(e.roleCounts[u]??0)+1;let a=Array.isArray(r.parts)?r.parts:[];Ue(a,e)}return e}function ve(t){return re(t).textBytes}function Ue(t,e){for(let n of t){if(e.partCount+=1,typeof n=="string"){e.textBytes+=p(n);continue}let o=b(n);typeof o.text=="string"&&(e.textBytes+=p(o.text));let r=M(o.functionCall);r&&(e.functionCallCount+=1,e.functionCallArgBytes+=p(r.args));let u=M(o.functionResponse);u&&(e.functionResponseCount+=1,e.functionResponseBytes+=p(u.response)+p(u.parts));let a=M(o.inlineData);a&&(e.inlineDataCount+=1,e.inlineDataBytes+=p(a.data)),o.fileData&&(e.fileDataCount+=1)}}function Me(t){let e=Array.isArray(t)?t:[],n=0;for(let o of e){let r=b(o),u=Array.isArray(r.functionDeclarations)?r.functionDeclarations:[];n+=u.length}return{count:e.length,functionDeclarationCount:n,schemaBytes:p(e)}}function We(t){return{model:t.model,contents:t.contents,config:se(t.config)}}function se(t){if(!t)return;let e=b(t),n={};for(let[o,r]of Object.entries(e))o!=="abortSignal"&&(n[o]=r);return n}function p(t){return t==null?0:typeof t=="string"?Buffer.byteLength(t,"utf8"):Buffer.byteLength(Pe(t),"utf8")}function Pe(t){try{return JSON.stringify(t)??""}catch{return"[unserializable]"}}function b(t){return typeof t=="object"&&t!==null?t:{}}function M(t){return typeof t=="object"&&t!==null?t:null}f();var et=131072,tt=32e3,nt=8e3,ot=64e3,rt=2048;function st(t,e,n,o=2048){let r=e-n-o;return!Number.isFinite(r)||r<=0?0:Math.min(t,r)}var i={"32k":32768,"64k":65536,"128k":131072,"192k":196608,"200k":2e5,"256k":262144,"272k":272e3,"384k":384e3,"400k":4e5,"512k":524288,"1m":1e6,"4k":4096,"8k":8192,"16k":16384};function ie(t){let e=(t??"").toLowerCase().trim();return e=e.replace(/^.*\//,""),e=e.split("|").pop()??e,e=e.split(":").pop()??e,e=e.replace(/\s+/g,"-"),e=e.replace(/-preview/g,""),!e.match(/^matilda-(?:plus|flash|vl-max)-latest$/)&&!e.match(/^kimi-k2-\d{4}$/)&&(e=e.replace(/-(?:\d{4,}|\d+x\d+b|v\d+(?:\.\d+)*|(?<=-[^-]+-)\d+(?:\.\d+)+|latest|exp)$/g,"")),e=e.replace(/-(?:\d?bit|int[48]|bf16|fp16|q[45]|quantized)$/g,""),e}var qe=[[/^gemini-3/,i["1m"]],[/^gemini-/,i["1m"]],[/^gpt-5/,i["272k"]],[/^gpt-/,i["128k"]],[/^o\d/,i["200k"]],[/^claude-/,i["200k"]],[/^matilda3-coder-plus/,i["1m"]],[/^matilda3-coder-flash/,i["1m"]],[/^matilda3\.\d/,i["1m"]],[/^matilda-plus-latest$/,i["1m"]],[/^matilda-flash-latest$/,i["1m"]],[/^coder-model$/,i["1m"]],[/^matilda-code$/,i["1m"]],[/^matilda3-max/,i["256k"]],[/^matilda3-coder-/,i["256k"]],[/^matilda/,i["256k"]],[/^deepseek-v4/,i["1m"]],[/^deepseek/,i["128k"]],[/^glm-5(\.[01])?(-|$)/,202752],[/^glm-(?:[5-9]|\d{2,})/,i["1m"]],[/^glm-/,202752],[/^matilda/,i["256k"]],[/^ornith/,i["64k"]],[/^minimax-m3/i,i["1m"]],[/^minimax-m2\.5/i,i["192k"]],[/^minimax-/i,i["200k"]],[/^kimi-/,i["256k"]],[/^seed-oss/,i["512k"]]],ue=[[/^gemini-3/,i["64k"]],[/^gemini-/,i["8k"]],[/^gpt-5/,i["128k"]],[/^gpt-/,i["16k"]],[/^o\d/,i["128k"]],[/^claude-opus-4-6/,i["128k"]],[/^claude-sonnet-4-6/,i["64k"]],[/^claude-/,i["64k"]],[/^matilda3\.\d/,i["64k"]],[/^coder-model$/,i["64k"]],[/^matilda-code$/,i["64k"]],[/^matilda$/,i["64k"]],[/^matilda-core$/,i["64k"]],[/^matilda/,i["32k"]],[/^deepseek-v4/,i["384k"]],[/^deepseek-reasoner/,i["64k"]],[/^deepseek-r1/,i["64k"]],[/^deepseek-chat/,i["8k"]],[/^glm-5\.2/,i["64k"]],[/^glm-5/,i["64k"]],[/^glm-4\.7/,i["16k"]],[/^ornith/,i["32k"]],[/^minimax-m2\.5/i,i["64k"]],[/^kimi-k2\.5/,i["32k"]]];function $e(t,e="input"){let n=ie(t),o=e==="output"?ue:qe;for(let[r,u]of o)if(r.test(n))return u}function it(t){let e=ie(t);return ue.some(([n])=>n.test(e))}function Fe(t,e="input"){return $e(t,e)}function ut(t,e="input"){return Fe(t,e)??(e==="output"?32e3:131072)}f();f();f();f();var y=class extends Error{constructor(e,n){super(`${e} at position ${n}`),this.position=n}};f();function ae(t){return/^[0-9A-Fa-f]$/.test(t)}function k(t){return t>="0"&&t<="9"}function ce(t){return t>=" "}function _(t){return`,:[]/{}()
4
4
  +`.includes(t)}function P(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"}function q(t){return t>="a"&&t<="z"||t>="A"&&t<="Z"||t==="_"||t==="$"||t>="0"&&t<="9"}var $=/^(http|https|ftp|mailto|file|data|irc):\/\/$/,F=/^[A-Za-z0-9-._~:/?#@!$&'()*+;=]$/;function K(t){return`,[]/{}
5
5
  +`.includes(t)}function J(t){return E(t)||Ke.test(t)}var Ke=/^[[{\w-]$/;function le(t){return t===`
6
6
  `||t==="\r"||t===" "||t==="\b"||t==="\f"}function C(t,e){let n=t.charCodeAt(e);return n===32||n===10||n===9||n===13}function me(t,e){let n=t.charCodeAt(e);return n===32||n===9||n===13}function fe(t,e){let n=t.charCodeAt(e);return n===160||n>=8192&&n<=8202||n===8239||n===8287||n===12288}function E(t){return Q(t)||L(t)}function Q(t){return t==='"'||t==="\u201C"||t==="\u201D"}function z(t){return t==='"'}function L(t){return t==="'"||t==="\u2018"||t==="\u2019"||t==="`"||t==="\xB4"}function G(t){return t==="'"}function B(t,e){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,o=t.lastIndexOf(e);return o!==-1?t.substring(0,o)+(n?"":t.substring(o+1)):t}function h(t,e){let n=t.length;if(!C(t,n-1))return t+e;for(;C(t,n-1);)n--;return t.substring(0,n)+e+t.substring(n)}function pe(t,e,n){return t.substring(0,e)+t.substring(e+n)}function de(t){return/[,\n][ \t\r]*$/.test(t)}var Je={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r"," ":"\\t"},Qe={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
@@ -0,0 +1,4 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{d as n,e as et,f as E,g as C,h as y,i as he,k as r,l as g,m as i,n as nt,o as h,q as H,r as a,t as l,z as A}from"./chunk-M53RP3YP.js";import{b as R}from"./chunk-GZPNIYVZ.js";R();var u={initialize:"initialize",authenticate:"authenticate",providers_list:"providers/list",providers_set:"providers/set",providers_disable:"providers/disable",session_new:"session/new",session_load:"session/load",session_set_mode:"session/set_mode",session_set_config_option:"session/set_config_option",session_prompt:"session/prompt",session_cancel:"session/cancel",mcp_message:"mcp/message",session_list:"session/list",session_delete:"session/delete",session_fork:"session/fork",session_resume:"session/resume",session_close:"session/close",logout:"logout",nes_start:"nes/start",nes_suggest:"nes/suggest",nes_accept:"nes/accept",nes_reject:"nes/reject",nes_close:"nes/close",document_did_open:"document/didOpen",document_did_change:"document/didChange",document_did_close:"document/didClose",document_did_save:"document/didSave",document_did_focus:"document/didFocus"},p={session_request_permission:"session/request_permission",session_update:"session/update",fs_write_text_file:"fs/write_text_file",fs_read_text_file:"fs/read_text_file",terminal_create:"terminal/create",terminal_output:"terminal/output",terminal_release:"terminal/release",terminal_wait_for_exit:"terminal/wait_for_exit",terminal_kill:"terminal/kill",mcp_message:"mcp/message",elicitation_create:"elicitation/create",elicitation_complete:"elicitation/complete"},ke={cancel_request:"$/cancel_request"},Vt=1;R();R();R();R();var tt=Symbol("skippedItem");function s(o,e){return o.catch(e)}function q(o,e){let t=o.catch(e);return A.unknown().transform((c,d)=>c!==void 0?t.parse(c):(d.addIssue({code:"custom",message:"Required value is missing"}),A.NEVER))}function st(o,e){if(o===null||typeof o!="object"||Array.isArray(o))return;let t=o[e];return typeof t=="string"?t:void 0}function B(o,e,t){return o.superRefine((c,d)=>{let z=st(c,e);z!==void 0&&t.includes(z)&&d.addIssue({code:"custom",path:[e],message:`${e} ${JSON.stringify(z)} is reserved by a known variant, but the value does not match that variant's schema`})})}function W(o,e,t){return A.unknown().transform((c,d)=>{let z=o.safeParse(c);if(!z.success){for(let _ of z.error.issues)d.addIssue({..._,input:c});return A.NEVER}let f=z.data,m=st(c,e);if(m!==void 0&&!t.includes(m)){let _=c;for(let[j,S]of Object.entries(_))j!=="__proto__"&&(Object.hasOwn(f,j)||(f[j]=S))}return f})}function it(o,e){return A.preprocess(t=>{if(t===null||typeof t!="object"||Array.isArray(t))return t;let c=t,d=c[e];if(d==null||typeof d=="string")return t;let z={...c};return delete z[e],z},o)}function T(o){return A.array(o.catch(tt)).transform(e=>e.filter(t=>t!==tt))}var G=h([E(),n()]).nullable(),b=n(),qe=i({sessionId:b,path:n(),content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Oe=i({sessionId:b,path:n(),line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),limit:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ie=n(),ot=h([l("read"),l("edit"),l("delete"),l("move"),l("search"),l("execute"),l("think"),l("fetch"),l("switch_mode"),l("other")]),rt=h([l("pending"),l("in_progress"),l("completed"),l("failed")]),Xt=h([l("assistant"),l("user")]),ae=i({audience:s(T(Xt).nullish(),()=>{}),lastModified:s(n().nullish(),()=>{}),priority:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Yt=i({annotations:s(ae.nullish(),()=>{}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zt=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),uri:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),es=i({annotations:s(ae.nullish(),()=>{}),data:n(),mimeType:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ns=i({annotations:s(ae.nullish(),()=>{}),description:s(n().nullish(),()=>{}),mimeType:s(n().nullish(),()=>{}),name:n(),size:s(E().nullish(),()=>{}),title:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ts=i({mimeType:s(n().nullish(),()=>{}),text:n(),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ss=i({blob:n(),mimeType:s(n().nullish(),()=>{}),uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),is=h([ts,ss]),os=i({annotations:s(ae.nullish(),()=>{}),resource:is,_meta:s(a(n(),r()).nullish(),()=>{})}),$=h([Yt.and(i({type:l("text")})),Zt.and(i({type:l("image")})),es.and(i({type:l("audio")})),ns.and(i({type:l("resource_link")})),os.and(i({type:l("resource")}))]),rs=i({content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),as=i({path:n(),oldText:s(n().nullish(),()=>{}),newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),V=n(),cs=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),at=h([rs.and(i({type:l("content")})),as.and(i({type:l("diff")})),cs.and(i({type:l("terminal")}))]),ct=i({path:n(),line:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),lt=i({toolCallId:Ie,kind:s(ot.nullish(),()=>{}),status:s(rt.nullish(),()=>{}),title:s(n().nullish(),()=>{}),name:s(n().nullish(),()=>{}),content:s(T(at).nullish(),()=>{}),locations:s(T(ct).nullish(),()=>{}),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),dt=n(),ls=h([l("allow_once"),l("allow_always"),l("reject_once"),l("reject_always")]),ds=i({optionId:dt,name:n(),kind:ls,_meta:s(a(n(),r()).nullish(),()=>{})}),He=i({sessionId:b,toolCall:lt,options:g(ds),_meta:s(a(n(),r()).nullish(),()=>{})}),ut=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ve=i({sessionId:b,command:n(),args:g(n()).optional(),env:g(ut).optional(),cwd:n().nullish(),outputByteLimit:E().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ae=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ge=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Pe=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Le=i({sessionId:b,terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),ce=i({sessionId:b,toolCallId:s(Ie.nullish(),()=>{})}),le=i({requestId:G}),us=l("object"),zs=h([l("email"),l("uri"),l("date"),l("date-time")]),zt=i({const:n(),title:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ue=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),maxLength:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),pattern:n().nullish(),format:zs.nullish(),default:s(n().nullish(),()=>{}),enum:g(n()).nullish(),oneOf:g(zt).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fe=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Be=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minimum:E().nullish(),maximum:E().nullish(),default:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),We=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),default:s(y().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),$e=i({enum:g(n()),_meta:s(a(n(),r()).nullish(),()=>{})}),pt=i({anyOf:g(zt),_meta:s(a(n(),r()).nullish(),()=>{})}),ps=W(h([$e.and(i({type:l("string")})),B(i({type:n()}),"type",["string"]),pt]),"type",["string"]),Je=i({title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),minItems:E().nullish(),maxItems:E().nullish(),items:ps,default:s(T(n()).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hs=W(h([Ue.and(i({type:l("string")})),Fe.and(i({type:l("number")})),Be.and(i({type:l("integer")})),We.and(i({type:l("boolean")})),Je.and(i({type:l("array")})),B(i({type:n()}),"type",["array","boolean","integer","number","string"])]),"type",["array","boolean","integer","number","string"]),fs=i({type:s(us.optional().default("object"),()=>"object"),title:s(n().nullish(),()=>{}),properties:a(n(),hs).optional().default({}),required:g(n()).nullish(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ve=H(h([ce,le]),i({requestedSchema:fs})),ht=n(),Ke=H(h([ce,le]),i({elicitationId:ht,url:et()})),Qe=W(H(h([Ve.and(i({mode:l("form")})),Ke.and(i({mode:l("url")})),B(H(h([ce,le]),i({mode:n()})),"mode",["form","url"])]),i({message:n(),_meta:s(a(n(),r()).nullish(),()=>{})})),"mode",["form","url"]),Xe=n(),ft=n(),ms=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),mt=r(),Fr=i({id:G,method:n(),params:h([qe,Oe,He,ve,Ae,Ge,Pe,Le,Qe,ms,mt]).nullish()}),gt=C().gte(0).lte(65535),gs=i({image:s(y().optional().default(!1),()=>!1),audio:s(y().optional().default(!1),()=>!1),embeddedContext:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),_s=i({http:s(y().optional().default(!1),()=>!1),sse:s(y().optional().default(!1),()=>!1),acp:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Es=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ss=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ts=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ws=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Rs=i({list:s(bs.nullish(),()=>{}),delete:s(Es.nullish(),()=>{}),additionalDirectories:s(xs.nullish(),()=>{}),fork:s(Ss.nullish(),()=>{}),resume:s(Ts.nullish(),()=>{}),close:s(ws.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ns=i({_meta:s(a(n(),r()).nullish(),()=>{})}),js=i({logout:s(Ns.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ys=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Cs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ms=h([l("full"),l("incremental")]),ks=i({syncKind:Ms,_meta:s(a(n(),r()).nullish(),()=>{})}),Ds=i({_meta:s(a(n(),r()).nullish(),()=>{})}),qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Os=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Is=i({didOpen:s(Cs.nullish(),()=>{}),didChange:s(ks.nullish(),()=>{}),didClose:s(Ds.nullish(),()=>{}),didSave:s(qs.nullish(),()=>{}),didFocus:s(Os.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Hs=i({document:s(Is.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),vs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),As=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Gs=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ps=i({maxCount:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ls=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Us=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Fs=i({recentFiles:s(vs.nullish(),()=>{}),relatedSnippets:s(As.nullish(),()=>{}),editHistory:s(Gs.nullish(),()=>{}),userActions:s(Ps.nullish(),()=>{}),openFiles:s(Ls.nullish(),()=>{}),diagnostics:s(Us.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Bs=i({events:s(Hs.nullish(),()=>{}),context:s(Fs.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),_t=h([l("utf-16"),l("utf-32"),l("utf-8")]),Ws=i({loadSession:s(y().optional().default(!1),()=>!1),promptCapabilities:s(gs.optional().default({image:!1,audio:!1,embeddedContext:!1}),()=>({image:!1,audio:!1,embeddedContext:!1})),mcpCapabilities:s(_s.optional().default({http:!1,sse:!1,acp:!1}),()=>({http:!1,sse:!1,acp:!1})),sessionCapabilities:s(Rs.optional().default({}),()=>({})),auth:s(js.optional().default({}),()=>({})),providers:s(ys.nullish(),()=>{}),nes:s(Bs.nullish(),()=>{}),positionEncoding:s(_t.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ye=n(),$s=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),args:g(n()).optional(),env:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Js=i({id:Ye,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Vs=h([$s.and(i({type:l("terminal")})),Js]),bt=i({name:n(),title:s(n().nullish(),()=>{}),version:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ks=i({protocolVersion:gt,agentCapabilities:s(Ws.optional().default({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}}),()=>({loadSession:!1,promptCapabilities:{image:!1,audio:!1,embeddedContext:!1},mcpCapabilities:{http:!1,sse:!1,acp:!1},sessionCapabilities:{},auth:{}})),authMethods:s(T(Vs).optional().default([]),()=>[]),agentInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qs=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ze=n(),en=h([l("anthropic"),l("openai"),l("azure"),l("vertex"),l("bedrock"),n()]),Xs=i({apiType:en,baseUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ys=i({providerId:Ze,supported:q(T(en),()=>[]),required:y(),current:Xs.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Zs=i({providers:g(Ys),_meta:s(a(n(),r()).nullish(),()=>{})}),ei=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ni=i({_meta:s(a(n(),r()).nullish(),()=>{})}),ti=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fe=n(),si=i({id:fe,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),me=i({currentModeId:fe,availableModes:q(T(si),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Et=n(),ii=h([l("mode"),l("model"),l("model_config"),l("thought_level"),n()]),nn=n(),xt=i({value:nn,name:n(),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),oi=n(),ri=i({group:oi,name:n(),options:q(T(xt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),ai=h([g(xt),g(ri)]),ci=i({currentValue:nn,options:ai}),li=i({currentValue:y()}),K=H(h([ci.and(i({type:l("select")})),li.and(i({type:l("boolean")}))]),i({id:Et,name:n(),description:s(n().nullish(),()=>{}),category:s(ii.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})})),di=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ui=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),zi=i({sessionId:b,cwd:n(),additionalDirectories:s(T(n()).optional(),()=>[]),title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),pi=i({sessions:q(T(zi),()=>[]),nextCursor:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),hi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),fi=i({sessionId:b,modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mi=i({modes:s(me.nullish(),()=>{}),configOptions:s(T(K).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),gi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_i=i({_meta:s(a(n(),r()).nullish(),()=>{})}),bi=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Ei=h([l("end_turn"),l("max_tokens"),l("max_turn_requests"),l("refusal"),l("cancelled")]),ge=i({totalTokens:E(),inputTokens:E(),outputTokens:E(),thoughtTokens:s(E().nullish(),()=>{}),cachedReadTokens:s(E().nullish(),()=>{}),cachedWriteTokens:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),xi=i({stopReason:Ei,usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Si=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Q=n(),P=i({line:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),character:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),_meta:s(a(n(),r()).nullish(),()=>{})}),X=i({start:P,end:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ti=i({range:X,newText:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),wi=i({id:Q,uri:n(),edits:g(Ti),cursorPosition:s(P.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ri=i({id:Q,uri:n(),position:P,_meta:s(a(n(),r()).nullish(),()=>{})}),Ni=i({id:Q,uri:n(),position:P,newName:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ji=i({id:Q,uri:n(),search:n(),replace:n(),isRegex:y().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yi=h([wi.and(i({kind:l("edit")})),Ri.and(i({kind:l("jump")})),Ni.and(i({kind:l("rename")})),ji.and(i({kind:l("searchAndReplace")}))]),Ci=i({suggestions:g(yi),_meta:s(a(n(),r()).nullish(),()=>{})}),Mi=i({_meta:s(a(n(),r()).nullish(),()=>{})}),St=r(),ki=h([l(-32700),l(-32600),l(-32601),l(-32602),l(-32603),l(-32800),l(-32e3),l(-32002),C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"})]),de=i({code:ki,message:n(),data:s(r().optional(),()=>{})}),Br=h([i({id:G,result:h([Ks,Qs,Zs,ei,ni,ti,di,ui,pi,hi,fi,mi,gi,_i,bi,xi,Si,Ci,Mi,St])}),i({id:G,error:de})]),tn=n(),De=i({content:$,messageId:s(tn.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Di=i({toolCallId:Ie,title:n(),name:s(n().nullish(),()=>{}),kind:s(ot.optional(),()=>{}),status:s(rt.optional(),()=>{}),content:s(T(at).optional(),()=>[]),locations:s(T(ct).optional(),()=>[]),rawInput:s(r().optional(),()=>{}),rawOutput:s(r().optional(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qi=h([l("high"),l("medium"),l("low")]),Oi=h([l("pending"),l("in_progress"),l("completed")]),Tt=i({content:n(),priority:qi,status:Oi,_meta:s(a(n(),r()).nullish(),()=>{})}),Ii=i({entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),_e=n(),Hi=i({planId:_e,entries:q(T(Tt),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),vi=i({planId:_e,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ai=i({planId:_e,content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Gi=h([Hi.and(i({type:l("items")})),vi.and(i({type:l("file")})),Ai.and(i({type:l("markdown")}))]),Pi=i({plan:Gi,_meta:s(a(n(),r()).nullish(),()=>{})}),Li=i({planId:_e,_meta:s(a(n(),r()).nullish(),()=>{})}),Ui=i({hint:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Fi=Ui,Bi=i({name:n(),description:n(),input:s(Fi.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Wi=i({availableCommands:q(T(Bi),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),$i=i({currentModeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),Ji=i({configOptions:q(T(K),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),Vi=i({title:s(n().nullish(),()=>{}),updatedAt:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Ki=i({amount:E(),currency:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Qi=i({used:E(),size:E(),cost:s(Ki.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xi=h([l("info"),l("warning"),l("error"),n()]),Yi=i({severity:Xi,title:n().min(1),description:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),wt=n(),Zi=h([l("in_progress"),l("completed"),l("failed"),l("cancelled"),n()]),eo=i({compactionId:wt,status:Zi,summary:s(T($).nullish(),()=>{}),error:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),no=i({compactionId:wt,content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),to=i({_meta:s(a(n(),r()).nullish(),()=>{})}),so=i({cancel:s(to.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),sn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),on=i({error:s(de.nullish(),()=>{})}),rn=it(W(H(h([i({stopReason:l("end_turn")}),i({stopReason:l("max_tokens")}),i({stopReason:l("max_turn_requests")}),i({stopReason:l("refusal")}),i({stopReason:l("cancelled")}),on.and(i({stopReason:l("error")})),B(i({stopReason:n()}),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),i({stopReason:he().optional()})]),i({usage:s(ge.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{}),stopReason:s(n().nullish(),()=>{})})),"stopReason",["cancelled","end_turn","error","max_tokens","max_turn_requests","refusal"]),"stopReason"),an=i({_meta:s(a(n(),r()).nullish(),()=>{})}),cn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),io=W(h([sn.and(i({state:l("running")})),rn.and(i({state:l("idle")})),an.and(i({state:l("requires_action")})),cn.and(i({state:l("unknown")})),B(i({state:n()}),"state",["idle","requires_action","running","unknown"])]),"state",["idle","requires_action","running","unknown"]),oo=i({sessionId:b,title:s(n().nullish(),()=>{}),description:s(n().nullish(),()=>{}),capabilities:s(so.nullish(),()=>{}),state:s(io.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ro=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:s(T($).nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ao=i({messageId:tn,senderSessionId:s(b.nullish(),()=>{}),recipientSessionId:s(b.nullish(),()=>{}),content:$,_meta:s(a(n(),r()).nullish(),()=>{})}),co=h([De.and(i({sessionUpdate:l("user_message_chunk")})),De.and(i({sessionUpdate:l("agent_message_chunk")})),De.and(i({sessionUpdate:l("agent_thought_chunk")})),Di.and(i({sessionUpdate:l("tool_call")})),lt.and(i({sessionUpdate:l("tool_call_update")})),Ii.and(i({sessionUpdate:l("plan")})),Pi.and(i({sessionUpdate:l("plan_update")})),Li.and(i({sessionUpdate:l("plan_removed")})),Wi.and(i({sessionUpdate:l("available_commands_update")})),$i.and(i({sessionUpdate:l("current_mode_update")})),Ji.and(i({sessionUpdate:l("config_option_update")})),Vi.and(i({sessionUpdate:l("session_info_update")})),Qi.and(i({sessionUpdate:l("usage_update")})),Yi.and(i({sessionUpdate:l("notice")})),eo.and(i({sessionUpdate:l("compaction_update")})),no.and(i({sessionUpdate:l("compaction_summary_chunk")})),oo.and(i({sessionUpdate:l("subagent_update")})),ro.and(i({sessionUpdate:l("session_message")})),ao.and(i({sessionUpdate:l("session_message_chunk")}))]),be=i({sessionId:b,update:co,_meta:s(a(n(),r()).nullish(),()=>{})}),ln=i({elicitationId:ht,_meta:s(a(n(),r()).nullish(),()=>{})}),Rt=r(),Wr=i({method:n(),params:h([be,ln,Rt]).nullish()}),lo=i({readTextFile:s(y().optional().default(!1),()=>!1),writeTextFile:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),uo=a(n(),r()),zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),po=i({boolean:s(zo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),ho=a(n(),r()),fo=i({compaction:s(uo.nullish(),()=>{}),configOptions:s(po.nullish(),()=>{}),notices:s(ho.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),mo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),go=i({_meta:s(a(n(),r()).nullish(),()=>{})}),_o=i({terminal:s(y().optional().default(!1),()=>!1),_meta:s(a(n(),r()).nullish(),()=>{})}),bo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Eo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),xo=i({form:s(bo.nullish(),()=>{}),url:s(Eo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),So=i({_meta:s(a(n(),r()).nullish(),()=>{})}),To=i({_meta:s(a(n(),r()).nullish(),()=>{})}),wo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Ro=i({jump:s(So.nullish(),()=>{}),rename:s(To.nullish(),()=>{}),searchAndReplace:s(wo.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),No=i({fs:s(lo.optional().default({readTextFile:!1,writeTextFile:!1}),()=>({readTextFile:!1,writeTextFile:!1})),terminal:s(y().optional().default(!1),()=>!1),session:s(fo.nullish(),()=>{}),subagents:s(mo.nullish(),()=>{}),plan:s(go.nullish(),()=>{}),auth:s(_o.optional().default({terminal:!1}),()=>({terminal:!1})),elicitation:s(xo.nullish(),()=>{}),nes:s(Ro.nullish(),()=>{}),positionEncodings:s(T(_t).optional(),()=>[]),_meta:s(a(n(),r()).nullish(),()=>{})}),dn=i({protocolVersion:gt,clientCapabilities:s(No.optional().default({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}}),()=>({fs:{readTextFile:!1,writeTextFile:!1},terminal:!1,auth:{terminal:!1}})),clientInfo:s(bt.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),un=i({methodId:Ye,_meta:s(a(n(),r()).nullish(),()=>{})}),zn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),pn=i({providerId:Ze,apiType:en,baseUrl:n(),headers:a(n(),n()).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),hn=i({providerId:Ze,_meta:s(a(n(),r()).nullish(),()=>{})}),fn=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Nt=i({name:n(),value:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),jo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),yo=i({name:n(),url:n(),headers:g(Nt),_meta:s(a(n(),r()).nullish(),()=>{})}),Co=i({name:n(),serverId:Xe,_meta:s(a(n(),r()).nullish(),()=>{})}),Mo=i({name:n(),command:n(),args:g(n()),env:g(ut),_meta:s(a(n(),r()).nullish(),()=>{})}),Ee=h([jo.and(i({type:l("http")})),yo.and(i({type:l("sse")})),Co.and(i({type:l("acp")})),Mo]),mn=i({cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee),_meta:s(a(n(),r()).nullish(),()=>{})}),gn=i({mcpServers:g(Ee),cwd:n(),additionalDirectories:g(n()).optional(),sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),_n=i({cwd:n().nullish(),cursor:n().nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),bn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),En=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),xn=i({sessionId:b,cwd:n(),additionalDirectories:g(n()).optional(),mcpServers:g(Ee).optional(),_meta:s(a(n(),r()).nullish(),()=>{})}),Sn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),Tn=i({sessionId:b,modeId:fe,_meta:s(a(n(),r()).nullish(),()=>{})}),wn=H(h([i({value:y(),type:l("boolean")}),i({value:nn})]),i({sessionId:b,configId:Et,_meta:s(a(n(),r()).nullish(),()=>{})})),Rn=i({sessionId:b,prompt:g($),_meta:s(a(n(),r()).nullish(),()=>{})}),ko=i({uri:n(),name:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Do=i({name:n(),owner:n(),remoteUrl:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Nn=i({workspaceUri:s(n().nullish(),()=>{}),workspaceFolders:g(ko).nullish(),repository:s(Do.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),qo=h([l("automatic"),l("diagnostic"),l("manual")]),Oo=i({uri:n(),languageId:n(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Io=i({startLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),endLine:C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ho=i({uri:n(),excerpts:g(Io),_meta:s(a(n(),r()).nullish(),()=>{})}),vo=i({uri:n(),diff:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Ao=i({action:n(),uri:n(),position:P,timestampMs:E(),_meta:s(a(n(),r()).nullish(),()=>{})}),Go=i({uri:n(),languageId:n(),visibleRange:s(X.nullish(),()=>{}),lastFocusedMs:s(E().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Po=h([l("error"),l("warning"),l("information"),l("hint")]),Lo=i({uri:n(),range:X,severity:Po,message:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Uo=i({recentFiles:g(Oo).nullish(),relatedSnippets:g(Ho).nullish(),editHistory:g(vo).nullish(),userActions:g(Ao).nullish(),openFiles:g(Go).nullish(),diagnostics:g(Lo).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),jn=i({sessionId:b,uri:n(),version:E(),position:P,selection:X.nullish(),triggerKind:qo,context:Uo.nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),yn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),$r=i({id:G,method:n(),params:h([dn,un,zn,pn,hn,fn,mn,gn,_n,bn,En,xn,Sn,Tn,wn,Rn,Nn,jn,yn,mt]).nullish()}),Fo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Bo=i({content:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Wo=i({optionId:dt,_meta:s(a(n(),r()).nullish(),()=>{})}),$o=h([i({outcome:l("cancelled")}),Wo.and(i({outcome:l("selected")}))]),Jo=i({outcome:$o,_meta:s(a(n(),r()).nullish(),()=>{})}),Vo=i({terminalId:V,_meta:s(a(n(),r()).nullish(),()=>{})}),Ko=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Qo=i({output:n(),truncated:y(),exitStatus:s(Ko.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Xo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),Yo=i({exitCode:s(C().gte(0).max(4294967295,{error:"Invalid value: Expected uint32 to be <= 4294967295"}).nullish(),()=>{}),signal:s(n().nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),Zo=i({_meta:s(a(n(),r()).nullish(),()=>{})}),er=h([n(),E(),E(),y(),g(n())]),Cn=i({content:a(n(),er).nullish()}),nr=W(H(h([Cn.and(i({action:l("accept")})),i({action:l("decline")}),i({action:l("cancel")}),B(i({action:n()}),"action",["accept","cancel","decline"])]),i({_meta:s(a(n(),r()).nullish(),()=>{})})),"action",["accept","cancel","decline"]),tr=nt({code:C().min(-2147483648,{error:"Invalid value: Expected int32 to be >= -2147483648"}).max(2147483647,{error:"Invalid value: Expected int32 to be <= 2147483647"}),message:n(),data:r().optional()}),sr=h([i({result:r(),_meta:s(a(n(),r()).nullish(),()=>{})}),i({error:tr,_meta:s(a(n(),r()).nullish(),()=>{})})]),Jr=h([i({id:G,result:h([Fo,Bo,Jo,Vo,Qo,Xo,Yo,Zo,nr,sr,St])}),i({id:G,error:de})]),Mn=i({sessionId:b,_meta:s(a(n(),r()).nullish(),()=>{})}),kn=i({sessionId:b,uri:n(),languageId:n(),version:E(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),ir=i({range:X.nullish(),text:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),Dn=i({sessionId:b,uri:n(),version:E(),contentChanges:g(ir),_meta:s(a(n(),r()).nullish(),()=>{})}),qn=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),On=i({sessionId:b,uri:n(),_meta:s(a(n(),r()).nullish(),()=>{})}),In=i({sessionId:b,uri:n(),version:E(),position:P,visibleRange:X,_meta:s(a(n(),r()).nullish(),()=>{})}),Hn=i({sessionId:b,id:Q,_meta:s(a(n(),r()).nullish(),()=>{})}),or=h([l("rejected"),l("ignored"),l("replaced"),l("cancelled")]),vn=i({sessionId:b,id:Q,reason:s(or.nullish(),()=>{}),_meta:s(a(n(),r()).nullish(),()=>{})}),rr=i({serverId:Xe,requestId:ft,method:n(),params:a(n(),r()).nullish(),_meta:s(a(n(),r()).nullish(),()=>{})}),Vr=i({method:n(),params:h([Mn,kn,Dn,qn,On,In,Hn,vn,rr,Rt]).nullish()}),Kr=i({requestId:G,_meta:s(a(n(),r()).nullish(),()=>{})});R();R();var yt="$/cancel_request";function xe(o){return Ln(o)&&"id"in o&&typeof o.method=="string"&&Un(o.id)}function Mt(o){if(!Ln(o)||"method"in o||!("id"in o)||!Un(o.id))return!1;let e=Object.hasOwn(o,"result"),t=Object.hasOwn(o,"error");return e===t?!1:!t||lr(o.error)}function Y(o){return Ln(o)&&!("id"in o)&&typeof o.method=="string"}function L(o){return typeof o=="object"&&o!==null}function Ln(o){return L(o)&&o.jsonrpc==="2.0"}function Un(o){return o===null||typeof o=="string"||typeof o=="number"&&Number.isFinite(o)}function Ct(o){return L(o)&&!("method"in o)&&("id"in o||"result"in o||"error"in o)}function ar(o){let e=!1,t=!1,c=!1,d=!1;for(let z of o)e||=xe(z)||Y(z),t||=Mt(z),L(z)&&(c||="method"in z,d||="result"in z||"error"in z);return e?!1:t?!0:d&&!c}function cr(o){if(!(!L(o)||!Un(o.requestId)))return o.requestId}function lr(o){return L(o)&&typeof o.code=="number"&&Number.isInteger(o.code)&&typeof o.message=="string"}var M={yes(){return{handled:!0}},no(o,e=!1){return{handled:!1,message:o,retry:e}}};function J(o){let e=Promise.reject(o);return e.catch(()=>{}),e}function dr(o){if(o instanceof Error||typeof o=="object"&&o!=null&&"message"in o&&typeof o.message=="string")return o.message}function ur(o){return typeof o=="object"&&o!==null&&"name"in o&&o.name==="ZodError"&&"issues"in o&&Array.isArray(o.issues)&&"format"in o&&typeof o.format=="function"}function kt(o){if(o instanceof N)return o.toResult();if(ur(o))return N.invalidParams(o.format()).toResult();let e=dr(o);try{return N.internalError(e?JSON.parse(e):{}).toResult()}catch{return N.internalError({details:e}).toResult()}}function zr(o){return o instanceof N&&o.code===-32800?o:N.requestCancelled(o)}function pr(o,e){let t=hr(o,e);return t?t.toResult():kt(o)}function hr(o,e){if(!(!e.aborted||!fr(o)))return zr(e.reason)}function fr(o){if(typeof o!="object"||o===null)return!1;let e=o;return e.name==="AbortError"||e.code==="ABORT_ERR"}var An=class{id;sendResult;signal;finishRequest;didRespond=!1;constructor(e,t,c=new AbortController().signal,d){this.id=e,this.sendResult=t,this.signal=c,this.finishRequest=d}get responded(){return this.didRespond}respond(e){return this.respondWithResult({result:e??null})}respondWithError(e){let t=e instanceof N?e.toErrorResponse():e;return this.respondWithResult({error:t})}respondWithResult(e){return this.didRespond?J(new Error("JSON-RPC request already responded")):(this.didRespond=!0,this.sendResult(e).finally(()=>{this.finishRequest?.()}))}},mr=new WeakMap;var ee=class{disposeHandler;active=!0;constructor(e){this.disposeHandler=e}dispose(){this.active&&(this.active=!1,this.disposeHandler())}[Symbol.dispose](){this.dispose()}runIndefinitely(){return this}},Gn=class{connection;constructor(e){this.connection=e}sendRequest(e,t,c,d){return this.connection.sendRequest(e,t,c,d)}sendNotification(e,t){return this.connection.sendNotification(e,t)}sendBatch(e){return this.connection.sendBatch(e)}sendCancelRequest(e){return this.connection.sendCancelRequest(e)}addDynamicHandler(e){return this.connection.addDynamicHandler(e)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},ne=class{pendingResponses=new Map;incomingRequests=new Map;nextRequestId=0;staticHandlers=[];dynamicHandlers=new Set;stream;writeQueue=Promise.resolve();abortController=new AbortController;closedPromise;retryQueue=[];context=new Gn(this);receiveReader;allowBatches=!0;constructor(e,t,c,d){if(typeof e=="function"){let _=e,j=t,S=c;this.initialize(S,[...d?.handlers??[],this.legacyHandler(_,j)],d);return}let z=e,f=t,m=c;this.initialize(z,[...m?.handlers??[],...f],m)}static builder(){return new Pn}runUntil(e){let t=!1,c=Promise.resolve().then(()=>e(this.context)).finally(()=>{t=!0}),d=this.closed.then(()=>{if(t)return new Promise(()=>{});throw this.closedReason()});return Promise.race([c,d]).finally(()=>{t=!0,this.close()})}addDynamicHandler(e){if(this.dynamicHandlers.add(e),this.retryQueue.length>0)for(let t of this.retryQueue.splice(0))this.processIncomingMessage(t).catch(c=>this.close(c));return new ee(()=>{this.dynamicHandlers.delete(e)})}get signal(){return this.abortController.signal}get closed(){return this.closedPromise}getContext(){return this.context}sendRequest(e,t,c,d={}){if(this.abortController.signal.aborted)return J(this.closedReason());let z=this.prepareRequest(e,t,c,d);return this.sendWireMessage(z.message).catch(()=>{}),d.cancellationSignal?.aborted&&z.cancel(),z.response}sendBatch(e){if(this.abortController.signal.aborted)return J(this.closedReason());if(!this.allowBatches)return J(new TypeError("JSON-RPC batches are not supported on this connection"));if(e.length===0)return J(new TypeError("JSON-RPC batch must contain at least one entry"));let t=[],c=[],d=[];for(let _ of e){if(_.kind==="notification"){t.push({jsonrpc:"2.0",method:_.method,params:_.params}),d.push(Promise.resolve(void 0));continue}let j=this.prepareRequest(_.method,_.params,_.mapResponse,_.options);t.push(j.message),d.push(j.response),c.push({signal:_.options?.cancellationSignal,cancel:j.cancel})}let z=t,f=this.sendWireMessage(z);for(let _ of c)_.signal?.aborted&&_.cancel();let m=Promise.all([f,...d]).then(([,..._])=>_);return m.catch(()=>{}),m}sendCancelRequest(e){return this.sendNotification(yt,{requestId:e})}sendNotification(e,t){return this.abortController.signal.aborted?J(this.closedReason()):this.sendWireMessage({jsonrpc:"2.0",method:e,params:t})}prepareRequest(e,t,c,d={}){let z=this.nextRequestId++,f=()=>{},m=new Promise((_,j)=>{let S={resolve:D=>{try{_(c?c(D):D)}catch(k){j(k)}},reject:j};f=()=>{S.cancellationSent||(S.cancellationSent=!0,S.cleanup?.(),this.sendCancelRequest(z).catch(()=>{}))},d.cancellationSignal?.addEventListener("abort",f,{once:!0}),S.cleanup=()=>{d.cancellationSignal?.removeEventListener("abort",f)},this.pendingResponses.set(z,S)});return m.catch(()=>{}),{message:{jsonrpc:"2.0",id:z,method:e,params:t},response:m,cancel:()=>f()}}close(e){if(this.abortController.signal.aborted)return;let t=e??new Error("ACP connection closed");this.abortController.abort(t);for(let c of this.pendingResponses.values())c.cleanup?.(),c.reject(t);this.pendingResponses.clear();for(let c of this.incomingRequests.values())c.abort(t);this.incomingRequests.clear(),this.receiveReader?.cancel(t).catch(()=>{})}initialize(e,t,c){this.stream=e,this.staticHandlers=t,this.allowBatches=c?.allowBatches??!0,this.closedPromise=new Promise(d=>{this.abortController.signal.addEventListener("abort",()=>d())}),this.receive()}legacyHandler(e,t){return{handleMessage:async(c,d)=>{if(c.kind==="request"){let z=await e(c.method,c.params,d);await c.responder.respond(z)}else await t(c.method,c.params,d);return M.yes()}}}async receive(){let e;try{let t=this.stream.readable.getReader();this.receiveReader=t;try{for(;!this.abortController.signal.aborted;){let{value:c,done:d}=await t.read();if(this.abortController.signal.aborted||d)break;this.receiveWireMessage(c)}}finally{this.receiveReader===t&&(this.receiveReader=void 0),t.releaseLock()}}catch(t){e=t}finally{this.close(e)}}receiveWireMessage(e){if(Array.isArray(e)){if(!this.allowBatches){this.close(new TypeError("JSON-RPC batches are not supported on this connection"));return}this.receiveBatch(e);return}if(!xe(e)&&!Y(e)&&!Ct(e)){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}this.receiveMessage(e)}receiveBatch(e){if(e.length===0){this.sendWireMessage(Z(N.invalidRequest(e))).catch(()=>{});return}let t=ar(e),d=t?0:e.reduce((S,D)=>S+(Y(D)?0:1),0),z=e.reduce((S,D)=>S+(Y(D)?1:0),0),f=!1,m=[],_=async()=>{f||d!==0||z!==0||m.length===0||(f=!0,await this.sendWireMessage(m))},j=async S=>{m.push(S),d-=1,await _()};for(let S of e){if(t){Ct(S)&&this.receiveMessage(S);continue}if(!xe(S)&&!Y(S)){j(Z(N.invalidRequest(S))).catch(()=>{});continue}let D=this.receiveMessage(S,xe(S)?j:void 0,e.length);Y(S)&&D.finally(()=>{z-=1,_().catch(k=>this.close(k))})}}receiveMessage(e,t,c){return this.abortController.signal.aborted?Promise.resolve():L(e)?"method"in e?("id"in e||this.handleProtocolNotification(e),this.processIncomingMessage(this.toIncomingMessage(e,t,c)).catch(d=>this.close(d))):("id"in e?this.handleResponse(e):console.error("Invalid message",{message:e}),Promise.resolve()):(console.error("Invalid message",{message:e}),Promise.resolve())}async processIncomingMessage(e){if(this.abortController.signal.aborted)return;let t=e,c=!1;try{for(let d of[...this.staticHandlers,...this.dynamicHandlers.values()]){if(this.abortController.signal.aborted)return;let z=await d.handleMessage(t,this.context)??{handled:!0};if(z.handled)return;t=z.message??t,c=c||!!z.retry}c?this.retryQueue.push(t):t.kind==="request"&&await t.responder.respondWithError(N.methodNotFound(t.method))}catch(d){if(this.abortController.signal.aborted)return;if(t.kind==="request"&&!t.responder.responded)await t.responder.respondWithResult(pr(d,t.responder.signal));else{let z=kt(d);"error"in z&&console.error("Error handling notification",e.raw,z.error)}}}toIncomingMessage(e,t,c){if("id"in e){let d=new AbortController;this.incomingRequests.set(e.id,d);let z=()=>{this.incomingRequests.get(e.id)===d&&this.incomingRequests.delete(e.id)},f=new An(e.id,m=>{let _={jsonrpc:"2.0",id:e.id,...m};return t?t(_):this.sendWireMessage(_)},d.signal,z);return c!==void 0&&mr.set(f,c),{kind:"request",method:e.method,params:e.params,raw:e,signal:d.signal,responder:f}}return{kind:"notification",method:e.method,params:e.params,raw:e}}handleResponse(e){let t=this.pendingResponses.get(e.id);if(t)if(this.pendingResponses.delete(e.id),t.cleanup?.(),!Mt(e))t.reject(N.invalidRequest(e));else if("result"in e)t.resolve(e.result);else{let{code:c,message:d,data:z}=e.error;t.reject(new N(c,d,z))}else console.error("Got response to unknown request",e.id)}handleProtocolNotification(e){if(e.method!==yt)return;let t=cr(e.params);if(t===void 0)return;let c=this.incomingRequests.get(t);!c||c.signal.aborted||c.abort(N.requestCancelled({requestId:t}))}closedReason(){return this.abortController.signal.reason??new Error("ACP connection closed")}async sendWireMessage(e){return this.abortController.signal.aborted?J(this.closedReason()):(this.writeQueue=this.writeQueue.then(async()=>{if(this.abortController.signal.aborted)throw this.closedReason();let t=this.stream.writable.getWriter();try{await t.write(e)}finally{t.releaseLock()}}).catch(t=>{throw this.close(t),t}),this.writeQueue)}},Pn=class{handlers=[];connectionName;name(e){return this.connectionName=e,this}withHandler(e){return this.handlers.push(e),this}onReceiveMessage(e){return this.withHandler({handleMessage:async(t,c)=>await e(t,c)??M.no(t),describe:()=>this.connectionName??"onReceiveMessage"})}onReceiveRequest(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="request"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,d.responder,z)??M.yes()},describe:()=>`${this.connectionName??"request"}:${e}`})}onReceiveNotification(e,t,c){return this.withHandler({handleMessage:async(d,z)=>{if(d.kind!=="notification"||d.method!==e)return M.no(d);let f=t(d.params);return await c(f,z)??M.yes()},describe:()=>`${this.connectionName??"notification"}:${e}`})}connect(e,t){return new ne(e,this.handlers,t)}connectWith(e,t,c){return this.connect(e,c).runUntil(t)}},N=class o extends Error{code;data;constructor(e,t,c){super(t),this.code=e,this.name="RequestError",this.data=c}static parseError(e,t){return new o(-32700,`Parse error${t?`: ${t}`:""}`,e)}static invalidRequest(e,t){return new o(-32600,`Invalid request${t?`: ${t}`:""}`,e)}static methodNotFound(e){return new o(-32601,`"Method not found": ${e}`,{method:e})}static invalidParams(e,t){return new o(-32602,`Invalid params${t?`: ${t}`:""}`,e)}static internalError(e,t){return new o(-32603,`Internal error${t?`: ${t}`:""}`,e)}static requestCancelled(e,t){return new o(-32800,`Request cancelled${t?`: ${t}`:""}`,e)}static authRequired(e,t){return new o(-32e3,`Authentication required${t?`: ${t}`:""}`,e)}static resourceNotFound(e){return new o(-32002,`Resource not found${e?`: ${e}`:""}`,e&&{uri:e})}toResult(){return{error:{code:this.code,message:this.message,data:this.data}}}toErrorResponse(){return{code:this.code,message:this.message,data:this.data}}};function Z(o){return{jsonrpc:"2.0",id:null,error:o.toErrorResponse()}}R();R();var te=class extends Error{maxMessageBytes;constructor(e){super(`Incoming ACP data exceeds the configured ${e} byte limit`),this.maxMessageBytes=e,this.name="MessageTooLargeError"}};function ue(o){let e=o??33554432;if(!Number.isSafeInteger(e)||e<=0)throw new RangeError("maxMessageBytes must be a positive safe integer");return e}var Se=class{#e=new Uint8Array(0);#n=0;#t;constructor(e){this.#t=ue(e)}get byteLength(){return this.#n}get lastByte(){return this.#e[this.#n-1]}#s(e){if(e>this.#t-this.#n)throw this.clear(),new te(this.#t)}append(e){this.#s(e.byteLength);let t=this.#n+e.byteLength;if(t>this.#e.byteLength){let c=Math.min(this.#t,Math.max(t,this.#e.byteLength*2,1024)),d=new Uint8Array(c);d.set(this.#e.subarray(0,this.#n)),this.#e=d}this.#e.set(e,this.#n),this.#n=t}take(){let e=this.#e.subarray(0,this.#n);return this.clear(),e}clear(){this.#e=new Uint8Array(0),this.#n=0}};var Dt=10,Te=class{#e;#n;constructor(e){this.#n=ue(e),this.#e=new Se(Math.min(Number.MAX_SAFE_INTEGER,this.#n+1))}*push(e){let t=0,c=e.indexOf(Dt,t);for(;c!==-1;)yield this.#t(e.subarray(t,c)),t=c+1,c=e.indexOf(Dt,t);if(t<e.byteLength){let d=e.subarray(t);this.#s(d),this.#e.append(d)}}flush(){if(this.#e.byteLength!==0)return Fn(this.#e.take())}clear(){this.#e.clear()}#t(e){return this.#s(e),this.#e.byteLength===0?Fn(e):(this.#e.append(e),Fn(this.#e.take()))}#s(e){let t=e.byteLength>0?e[e.byteLength-1]:this.#e.lastByte;if(this.#e.byteLength+e.byteLength-(t===13?1:0)>this.#n)throw this.clear(),new te(this.#n)}};function Fn(o){return o[o.byteLength-1]===13?o.subarray(0,-1):o}function qt(o,e,t={}){let c=ue(t.maxMessageBytes),d=new TextEncoder,z=new TextDecoder,f=!1,m,_=Promise.resolve(),j=k=>{let ie=JSON.stringify(k)+`
4
+ `,oe=_.then(async()=>{let v=o.getWriter();try{await v.write(d.encode(ie))}finally{v.releaseLock()}});return _=oe.catch(()=>{}),oe},S=new ReadableStream({async start(k){let ie=new Te(c),oe=async U=>{let re=z.decode(U).trim();if(!re)return;let F;try{F=JSON.parse(re)}catch{await j(Z(N.parseError()));return}L(F)||Array.isArray(F)?k.enqueue(F):await j(Z(N.invalidRequest(F)))},v=e.getReader();m=v;try{for(;;){let{value:re,done:F}=await v.read();if(f)return;if(F)break;if(re){for(let Jt of ie.push(re))if(await oe(Jt),f)return}}if(f)return;let U=ie.flush();U&&await oe(U)}catch(U){if(f)return;k.error(U),v.cancel(U).catch(()=>{});return}finally{ie.clear(),m===v&&(m=void 0),v.releaseLock()}f||k.close()},cancel(k){return f=!0,m?.cancel(k)}}),D=new WritableStream({write(k){return j(k)}});return{readable:S,writable:D}}R();var la=Ve.and(i({mode:l("form")})).and(i({message:n()})),da=Ke.and(i({mode:l("url")})).and(i({message:n()})),ua=h([ce,le]).and(i({message:n()})),za=Ue.and(i({type:l("string")})),pa=Fe.and(i({type:l("number")})),ha=Be.and(i({type:l("integer")})),fa=We.and(i({type:l("boolean")})),ma=Je.and(i({type:l("array")})),ga=$e.and(i({type:l("string")}));var _a=sn.and(i({state:l("running")})),ba=rn.and(i({usage:ge.nullish()})).and(i({state:l("idle")})),Ea=an.and(i({state:l("requires_action")})),xa=cn.and(i({state:l("unknown")})),Sa=i({stopReason:l("end_turn")}),Ta=i({stopReason:l("max_tokens")}),wa=i({stopReason:l("max_turn_requests")}),Ra=i({stopReason:l("refusal")}),Na=i({stopReason:l("cancelled")}),ja=on.and(i({error:de.nullish()})).and(i({stopReason:l("error")})),ya=i({stopReason:he().optional()}),Ca=Cn.and(i({action:l("accept")})),Ma=i({action:l("decline")}),ka=i({action:l("cancel")});function Ua(o,e,t){return qt(o,e,t)}function w(o){return o??{}}function At(o){return typeof o=="object"&&o!==null&&"readable"in o&&"writable"in o}function Gt(){let o=new TransformStream,e=new TransformStream;return[{readable:e.readable,writable:o.writable},{readable:o.readable,writable:e.writable}]}var Ba={agent:{initialize:u.initialize,authenticate:u.authenticate,logout:u.logout,providers:{list:u.providers_list,set:u.providers_set,disable:u.providers_disable},session:{new:u.session_new,load:u.session_load,list:u.session_list,delete:u.session_delete,fork:u.session_fork,resume:u.session_resume,close:u.session_close,setMode:u.session_set_mode,setConfigOption:u.session_set_config_option,prompt:u.session_prompt,cancel:u.session_cancel},nes:{start:u.nes_start,suggest:u.nes_suggest,accept:u.nes_accept,reject:u.nes_reject,close:u.nes_close},document:{didOpen:u.document_did_open,didChange:u.document_did_change,didClose:u.document_did_close,didSave:u.document_did_save,didFocus:u.document_did_focus}},client:{session:{requestPermission:p.session_request_permission,update:p.session_update},fs:{writeTextFile:p.fs_write_text_file,readTextFile:p.fs_read_text_file},terminal:{create:p.terminal_create,output:p.terminal_output,release:p.terminal_release,waitForExit:p.terminal_wait_for_exit,kill:p.terminal_kill},elicitation:{create:p.elicitation_create,complete:p.elicitation_complete}},protocol:{cancelRequest:ke.cancel_request}},Pt=Symbol("startActiveSession"),Ne=class{cx;currentRequestId;constructor(e,t){this.cx=e,this.currentRequestId=t}get requestId(){return this.currentRequestId}get connectionContext(){return this.cx}sendRequest(e,t,c,d){return this.cx.sendRequest(e,t,c,d)}sendNotification(e,t){return this.cx.sendNotification(e,t)}addDynamicHandler(e){return this.cx.addDynamicHandler(e)}},ze=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}request(e,t,c){let d=Zn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},pe=class o extends Ne{constructor(e,t){super(e,t)}static create(e,t){return new o(e,t)}[Pt](e,t){return this.sendRequest(u.session_new,e,c=>this.attachSession(c),t)}buildSession(e){return typeof e=="string"?ye.create(this,{cwd:e,mcpServers:[]}):ye.create(this,e)}attachSession(e){let t=new $n,c=this.connectionContext.signal,d=()=>{t.fail(c.reason??new Error("ACP connection closed"))};c.aborted?d():c.addEventListener("abort",d);let z=$t(this.connectionContext).attach(e,t),f=new ee(()=>{c.removeEventListener("abort",d)});return Jn.create(this,e,t,[z,f])}request(e,t,c){let d=Yn[e];return this.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.sendNotification(e,t)}},je=class{connection;constructor(e){this.connection=e}get signal(){return this.connection.signal}get closed(){return this.connection.closed}close(e){this.connection.close(e)}},Bn=class extends je{connectHandlers;client;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.client=ze.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}},Wn=class extends je{connectHandlers;agent;didStartConnectHandlers=!1;constructor(e,t=[]){super(e),this.connectHandlers=t,this.agent=pe.create(e.getContext())}startConnectHandlers(){this.didStartConnectHandlers||(this.didStartConnectHandlers=!0,Me(this,this.connectHandlers))}};function Lt(o,e=[]){return new Bn(o,e)}function Ut(o,e=[]){return new Wn(o,e)}var $n=class{values=[];waiters=[];failed=!1;failure;enqueue(e){if(this.failed)return;let t=this.waiters.shift();t?t.resolve(e):this.values.push({kind:"value",value:e})}reject(e){if(!this.failed){if(this.waiters.length>0){for(let t of this.waiters.splice(0))t.reject(e);return}this.values.push({kind:"error",error:e})}}clearErrors(){this.values=this.values.filter(e=>e.kind==="value")}fail(e){if(!this.failed){this.failed=!0,this.failure=e;for(let t of this.waiters.splice(0))t.reject(e)}}next(){if(this.values.length>0){let e=this.values.shift();return e.kind==="error"?Promise.reject(e.error):Promise.resolve(e.value)}return this.failed?Promise.reject(this.failure):new Promise((e,t)=>{this.waiters.push({resolve:e,reject:t})})}};function Ot(o){return{...o,additionalDirectories:o.additionalDirectories?[...o.additionalDirectories]:void 0,mcpServers:[...o.mcpServers]}}var ye=class o{cx;request;constructor(e,t){this.cx=e,this.request=Ot(t)}static create(e,t){return new o(e,t)}toRequest(){return Ot(this.request)}withAdditionalDirectories(e){return this.request={...this.request,additionalDirectories:[...e]},this}withMcpServer(e){return this.request={...this.request,mcpServers:[...this.request.mcpServers,e]},this}async start(e){return this.cx[Pt](this.toRequest(),e)}async withSession(e){let t=await this.start();try{return await e(t)}finally{t.dispose()}}},Jn=class o{cx;sessionResponse;updates;registrations;constructor(e,t,c,d){this.cx=e,this.sessionResponse=t,this.updates=c,this.registrations=d}static create(e,t,c,d){return new o(e,t,c,d)}get sessionId(){return this.sessionResponse.sessionId}get modes(){return this.sessionResponse.modes}get meta(){return this.sessionResponse._meta}get newSessionResponse(){return this.sessionResponse}prompt(e,t){this.updates.clearErrors();let c=this.cx.request(u.session_prompt,{sessionId:this.sessionId,prompt:this.promptBlocks(e)},t);return c.then(d=>{this.updates.enqueue({kind:"stop",response:d,stopReason:d.stopReason})},d=>{this.updates.reject(d)}),c}nextUpdate(){return this.updates.next()}async readText(){let e="";for(;;){let t=await this.nextUpdate();if(t.kind==="stop")return e;let{update:c}=t;c.sessionUpdate==="agent_message_chunk"&&c.content.type==="text"&&(e+=c.content.text)}}dispose(){for(let e of this.registrations.splice(0))e.dispose();this.updates.fail(new Error("Active session disposed"))}[Symbol.dispose](){this.dispose()}promptBlocks(e){return typeof e=="string"?[{type:"text",text:e}]:Array.isArray(e)?e:[e]}};function Ft(o,e){return o?typeof o=="function"?o(e):o.parse(e):e}function x(o,e,t){return{method:o,params:e,mapResponse:t}}function O(o,e){return{method:o,params:e}}function Bt(o,e,t,c){o.onReceiveRequest(e.method,d=>Ft(e.params,d),async(d,z,f)=>{let m=await c(t(d,f,z.signal,z.id));await z.respond(e.mapResponse?e.mapResponse(m):m)})}function Wt(o,e,t,c){o.onReceiveNotification(e.method,d=>Ft(e.params,d),(d,z)=>c(t(d,z,z.signal)))}function Ce(o){let e={};for(let t of Object.values(o))e[t.method]=t;return e}var gr={initialize:x(u.initialize,dn),newSession:x(u.session_new,mn),loadSession:x(u.session_load,gn,w),unstable_forkSession:x(u.session_fork,En),listSessions:x(u.session_list,_n),deleteSession:x(u.session_delete,bn,w),resumeSession:x(u.session_resume,xn),closeSession:x(u.session_close,Sn,w),setSessionMode:x(u.session_set_mode,Tn,w),setSessionConfigOption:x(u.session_set_config_option,wn),authenticate:x(u.authenticate,un,w),unstable_listProviders:x(u.providers_list,zn),unstable_setProvider:x(u.providers_set,pn,w),unstable_disableProvider:x(u.providers_disable,hn,w),logout:x(u.logout,fn,w),prompt:x(u.session_prompt,Rn),unstable_startNes:x(u.nes_start,Nn),unstable_suggestNes:x(u.nes_suggest,jn),unstable_closeNes:x(u.nes_close,yn,w)},_r={cancel:O(u.session_cancel,Mn),unstable_didOpenDocument:O(u.document_did_open,kn),unstable_didChangeDocument:O(u.document_did_change,Dn),unstable_didCloseDocument:O(u.document_did_close,qn),unstable_didSaveDocument:O(u.document_did_save,On),unstable_didFocusDocument:O(u.document_did_focus,In),unstable_acceptNes:O(u.nes_accept,Hn),unstable_rejectNes:O(u.nes_reject,vn)},br={requestPermission:x(p.session_request_permission,He),writeTextFile:x(p.fs_write_text_file,qe,w),readTextFile:x(p.fs_read_text_file,Oe),createTerminal:x(p.terminal_create,ve),terminalOutput:x(p.terminal_output,Ae),releaseTerminal:x(p.terminal_release,Ge,w),waitForTerminalExit:x(p.terminal_wait_for_exit,Pe),killTerminal:x(p.terminal_kill,Le,w),createElicitation:x(p.elicitation_create,Qe)},Er={sessionUpdate:O(p.session_update,be),completeElicitation:O(p.elicitation_complete,ln)},Yn=Ce(gr),xr=Ce(_r),Zn=Ce(br),Sr=Ce(Er);function Tr(o,e,t,c){return{params:o,requestId:c,signal:t,client:e}}function wr(o,e,t){return{params:o,signal:t,client:e}}function Rr(o,e,t,c){return{params:o,requestId:c,signal:t,agent:e}}function Nr(o,e,t){return{params:o,signal:t,agent:e}}var Vn=class{activeSessions=new Map;handleMessage(e){if(e.kind!=="notification"||e.method!==p.session_update)return M.no(e);let t=be.parse(e.params),c={kind:"session_update",notification:t,update:t.update},d=this.activeSessions.get(t.sessionId);if(d&&d.size>0)for(let z of d)z.enqueue(c);return M.no(e)}attach(e,t){let c=this.activeSessions.get(e.sessionId)??new Set;return c.add(t),this.activeSessions.set(e.sessionId,c),new ee(()=>{c.delete(t),c.size===0&&this.activeSessions.delete(e.sessionId)})}},It=new WeakMap;function $t(o){let e=It.get(o);return e||(e=new Vn,It.set(o,e)),e}function Me(o,e){for(let t of e){let c;try{c=t(o)}catch(d){throw o.close(d),d}Promise.resolve(c).catch(d=>{o.close(d)})}}var I=Symbol("appBuilder"),we=Symbol("runAgentConnectHandlers"),Re=Symbol("runClientConnectHandlers"),se={allowBatches:!1};function jr(o){return new Kn(o)}var Kn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name)}[I](){return this.builder}[we](e){Me(e,this.connectHandlers)}connect(e,t={}){return this.connectConnection(e,t).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.client))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Yn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=xr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Tr(c,ze.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>wr(c,ze.create(d),z),t),this}connectConnection(e,t={}){if(At(e)){let _=this.openStreamConnection(e);return t.deferConnectHandlers||this[we](_.connection),_}let[c,d]=Gt(),z=e[I]().connect(d,se),f=Ut(z),m=this.openStreamConnection(c);m.rawConnection.closed.then(()=>f.close()),z.closed.then(()=>m.connection.close());try{e[Re](f),this[we](m.connection)}catch(_){throw f.close(_),m.connection.close(_),_}return m}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Lt(t,this.connectHandlers)}}};function yr(o){return new Qn(o)}var Qn=class{builder=ne.builder();connectHandlers=[];constructor(e={}){e.name&&this.builder.name(e.name),this.builder.withHandler({handleMessage:(t,c)=>$t(c).handleMessage(t),describe:()=>"client-session-update-router"})}[I](){return this.builder}[Re](e){Me(e,this.connectHandlers)}connect(e){return this.connectConnection(e).connection}connectWith(e,t){let{rawConnection:c,connection:d}=this.connectConnection(e);return c.runUntil(()=>t(d.agent))}onConnect(e){return this.connectHandlers.push(e),this}onRequest(e,t,c){if(c)return this.request({method:e,params:t},c);let d=Zn[e];if(!d)throw new Error(`Unknown ACP request method '${e}'. Pass a params parser for custom methods.`);return this.request(d,t)}onNotification(e,t,c){if(c)return this.notification({method:e,params:t},c);let d=Sr[e];if(!d)throw new Error(`Unknown ACP notification method '${e}'. Pass a params parser for custom methods.`);return this.notification(d,t)}request(e,t){return Bt(this.builder,e,(c,d,z,f)=>Rr(c,pe.create(d,f),z,f),t),this}notification(e,t){return Wt(this.builder,e,(c,d,z)=>Nr(c,pe.create(d),z),t),this}connectConnection(e){if(At(e)){let m=this.openStreamConnection(e);return this[Re](m.connection),m}let[t,c]=Gt(),d=e[I]().connect(c,se),z=Lt(d),f=this.openStreamConnection(t);f.rawConnection.closed.then(()=>z.close()),d.closed.then(()=>f.connection.close());try{e[we](z),this[Re](f.connection)}catch(m){throw z.close(m),f.connection.close(m),m}return f}openStreamConnection(e){let t=this.builder.connect(e,se);return{rawConnection:t,connection:Ut(t,this.connectHandlers)}}},Cr=new Set([u.initialize,u.authenticate,u.providers_list,u.providers_set,u.providers_disable,u.session_new,u.session_load,u.session_set_mode,u.session_set_config_option,u.session_prompt,u.session_list,u.session_delete,u.session_fork,u.session_resume,u.session_close,u.logout,u.nes_start,u.nes_suggest,u.nes_close]),Mr=new Set([u.session_cancel,u.nes_accept,u.nes_reject,u.document_did_open,u.document_did_change,u.document_did_close,u.document_did_save,u.document_did_focus]),kr=new Set([p.session_request_permission,p.fs_write_text_file,p.fs_read_text_file,p.terminal_create,p.terminal_output,p.terminal_release,p.terminal_wait_for_exit,p.terminal_kill,p.elicitation_create]),Dr=new Set([p.session_update,p.elicitation_complete]);function qr(o){let e=jr().onRequest(u.initialize,t=>o.initialize(t.params)).onRequest(u.session_new,t=>o.newSession(t.params)).onRequest(u.authenticate,async t=>await o.authenticate(t.params)??{}).onRequest(u.session_prompt,t=>o.prompt(t.params)).onNotification(u.session_cancel,t=>o.cancel(t.params));return o.loadSession&&e.onRequest(u.session_load,t=>o.loadSession(t.params)),o.listSessions&&e.onRequest(u.session_list,t=>o.listSessions(t.params)),o.deleteSession&&e.onRequest(u.session_delete,async t=>await o.deleteSession(t.params)??{}),o.unstable_forkSession&&e.onRequest(u.session_fork,t=>o.unstable_forkSession(t.params)),o.resumeSession&&e.onRequest(u.session_resume,t=>o.resumeSession(t.params)),o.closeSession&&e.onRequest(u.session_close,async t=>await o.closeSession(t.params)??{}),o.setSessionMode&&e.onRequest(u.session_set_mode,async t=>await o.setSessionMode(t.params)??{}),o.setSessionConfigOption&&e.onRequest(u.session_set_config_option,t=>o.setSessionConfigOption(t.params)),o.unstable_listProviders&&e.onRequest(u.providers_list,t=>o.unstable_listProviders(t.params)),o.unstable_setProvider&&e.onRequest(u.providers_set,async t=>await o.unstable_setProvider(t.params)??{}),o.unstable_disableProvider&&e.onRequest(u.providers_disable,async t=>await o.unstable_disableProvider(t.params)??{}),o.logout&&e.onRequest(u.logout,async t=>await o.logout(t.params)??{}),o.unstable_startNes&&e.onRequest(u.nes_start,t=>o.unstable_startNes(t.params)),o.unstable_suggestNes&&e.onRequest(u.nes_suggest,t=>o.unstable_suggestNes(t.params)),o.unstable_closeNes&&e.onRequest(u.nes_close,async t=>await o.unstable_closeNes(t.params)??{}),o.unstable_didOpenDocument&&e.onNotification(u.document_did_open,t=>o.unstable_didOpenDocument(t.params)),o.unstable_didChangeDocument&&e.onNotification(u.document_did_change,t=>o.unstable_didChangeDocument(t.params)),o.unstable_didCloseDocument&&e.onNotification(u.document_did_close,t=>o.unstable_didCloseDocument(t.params)),o.unstable_didSaveDocument&&e.onNotification(u.document_did_save,t=>o.unstable_didSaveDocument(t.params)),o.unstable_didFocusDocument&&e.onNotification(u.document_did_focus,t=>o.unstable_didFocusDocument(t.params)),o.unstable_acceptNes&&e.onNotification(u.nes_accept,t=>o.unstable_acceptNes(t.params)),o.unstable_rejectNes&&e.onNotification(u.nes_reject,t=>o.unstable_rejectNes(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||Cr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-agent-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Mr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-agent-extension-notification"}),e}function Or(o){let e=yr().onRequest(p.session_request_permission,t=>o.requestPermission(t.params)).onNotification(p.session_update,t=>o.sessionUpdate(t.params)).onRequest(p.fs_write_text_file,async t=>await o.writeTextFile?.(t.params)??{}).onRequest(p.fs_read_text_file,async t=>await o.readTextFile?.(t.params)).onRequest(p.terminal_create,async t=>await o.createTerminal?.(t.params)).onRequest(p.terminal_output,async t=>await o.terminalOutput?.(t.params)).onRequest(p.terminal_release,async t=>await o.releaseTerminal?.(t.params)??{}).onRequest(p.terminal_wait_for_exit,async t=>await o.waitForTerminalExit?.(t.params)).onRequest(p.terminal_kill,async t=>await o.killTerminal?.(t.params)??{});return o.createElicitation&&e.onRequest(p.elicitation_create,t=>o.createElicitation(t.params)),o.completeElicitation&&e.onNotification(p.elicitation_complete,t=>o.completeElicitation(t.params)),o.extMethod&&e[I]().withHandler({handleMessage:async t=>t.kind!=="request"||kr.has(t.method)?M.no(t):(await t.responder.respond(await o.extMethod(t.method,t.params)),M.yes()),describe:()=>"legacy-client-extension-request"}),o.extNotification&&e[I]().withHandler({handleMessage:async t=>t.kind!=="notification"||Dr.has(t.method)?M.no(t):(await o.extNotification(t.method,t.params),M.yes()),describe:()=>"legacy-client-extension-notification"}),e}var Ht=class{connection;constructor(e,t){this.connection=qr(e(this))[I]().connect(t,se)}sessionUpdate(e){return this.connection.sendNotification(p.session_update,e)}requestPermission(e){return this.connection.sendRequest(p.session_request_permission,e)}readTextFile(e){return this.connection.sendRequest(p.fs_read_text_file,e)}writeTextFile(e){return this.connection.sendRequest(p.fs_write_text_file,e,w)}createTerminal(e){return this.connection.sendRequest(p.terminal_create,e,t=>Xn.create(t.terminalId,e.sessionId,this.connection))}createElicitation(e){return this.connection.sendRequest(p.elicitation_create,e)}completeElicitation(e){return this.connection.sendNotification(p.elicitation_complete,e)}request(e,t,c){let d=Zn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}},Xn=class o{id;sessionId;connection;constructor(e,t,c){this.id=e,this.sessionId=t,this.connection=c}static create(e,t,c){return new o(e,t,c)}currentOutput(){return this.connection.sendRequest(p.terminal_output,{sessionId:this.sessionId,terminalId:this.id})}waitForExit(){return this.connection.sendRequest(p.terminal_wait_for_exit,{sessionId:this.sessionId,terminalId:this.id})}kill(){return this.connection.sendRequest(p.terminal_kill,{sessionId:this.sessionId,terminalId:this.id},w)}release(){return this.connection.sendRequest(p.terminal_release,{sessionId:this.sessionId,terminalId:this.id},w)}async[Symbol.asyncDispose](){await this.release()}},vt=class{connection;constructor(e,t){this.connection=Or(e(this))[I]().connect(t,se)}initialize(e){return this.connection.sendRequest(u.initialize,e)}newSession(e){return this.connection.sendRequest(u.session_new,e)}loadSession(e){return this.connection.sendRequest(u.session_load,e,w)}unstable_forkSession(e){return this.connection.sendRequest(u.session_fork,e)}listSessions(e){return this.connection.sendRequest(u.session_list,e)}deleteSession(e){return this.connection.sendRequest(u.session_delete,e,w)}resumeSession(e){return this.connection.sendRequest(u.session_resume,e)}closeSession(e){return this.connection.sendRequest(u.session_close,e,w)}setSessionMode(e){return this.connection.sendRequest(u.session_set_mode,e,w)}setSessionConfigOption(e){return this.connection.sendRequest(u.session_set_config_option,e)}authenticate(e){return this.connection.sendRequest(u.authenticate,e,w)}unstable_listProviders(e){return this.connection.sendRequest(u.providers_list,e)}unstable_setProvider(e){return this.connection.sendRequest(u.providers_set,e,w)}unstable_disableProvider(e){return this.connection.sendRequest(u.providers_disable,e,w)}logout(e){return this.connection.sendRequest(u.logout,e,w)}prompt(e){return this.connection.sendRequest(u.session_prompt,e)}cancel(e){return this.connection.sendNotification(u.session_cancel,e)}unstable_startNes(e){return this.connection.sendRequest(u.nes_start,e)}unstable_suggestNes(e){return this.connection.sendRequest(u.nes_suggest,e)}unstable_closeNes(e){return this.connection.sendRequest(u.nes_close,e,w)}unstable_didOpenDocument(e){return this.connection.sendNotification(u.document_did_open,e)}unstable_didChangeDocument(e){return this.connection.sendNotification(u.document_did_change,e)}unstable_didCloseDocument(e){return this.connection.sendNotification(u.document_did_close,e)}unstable_didSaveDocument(e){return this.connection.sendNotification(u.document_did_save,e)}unstable_didFocusDocument(e){return this.connection.sendNotification(u.document_did_focus,e)}unstable_acceptNes(e){return this.connection.sendNotification(u.nes_accept,e)}unstable_rejectNes(e){return this.connection.sendNotification(u.nes_reject,e)}request(e,t,c){let d=Yn[e];return this.connection.sendRequest(e,t,d?.mapResponse,c)}notify(e,t){return this.connection.sendNotification(e,t)}extMethod(e,t){return this.request(e,t)}extNotification(e,t){return this.notify(e,t)}get signal(){return this.connection.signal}get closed(){return this.connection.closed}};export{Vt as a,N as b,Ua as c,Ht as d,vt as e};