@maincode-ai/matilda-code 0.21.11 → 0.21.13

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 (174) hide show
  1. package/bundled/mainy/docs/configuration/model-providers.md +0 -82
  2. package/bundled/mainy/docs/configuration/settings.md +46 -7
  3. package/bundled/mainy/docs/configuration/trusted-folders.md +12 -6
  4. package/bundled/mainy/docs/features/auto-mode.md +1 -1
  5. package/bundled/mainy/docs/features/channels/_meta.ts +0 -3
  6. package/bundled/mainy/docs/features/channels/overview.md +8 -16
  7. package/bundled/mainy/docs/features/commands.md +4 -4
  8. package/bundled/mainy/docs/features/hooks.md +9 -7
  9. package/bundled/mainy/docs/features/language.md +2 -29
  10. package/bundled/mainy/docs/features/worktree.md +0 -2
  11. package/bundled/mainy/docs/integration-github-action.md +3 -3
  12. package/bundled/mainy/docs/quickstart.md +2 -2
  13. package/bundled/mainy/docs/support/troubleshooting.md +1 -1
  14. package/chunks/agent-SRAIVZEE.js +3 -0
  15. package/chunks/agent-headless-XRDOZESG.js +3 -0
  16. package/chunks/{anthropicContentGenerator-IYZILRDW.js → anthropicContentGenerator-LLDIKDMQ.js} +3 -3
  17. package/chunks/{askUserQuestion-XWHJY3DM.js → askUserQuestion-BNSWGD26.js} +1 -1
  18. package/chunks/{ca-EUJBUYX5.js → ca-NPYL24ME.js} +2 -2
  19. package/chunks/{chunk-4YVN5HXG.js → chunk-27HUYW23.js} +2 -2
  20. package/chunks/{chunk-MH2P4YXC.js → chunk-27Q5KW3A.js} +2 -2
  21. package/chunks/{chunk-NYEWHSBL.js → chunk-2HTPVSGT.js} +1 -1
  22. package/chunks/{chunk-EQGA7LH7.js → chunk-3B2HABK7.js} +1 -1
  23. package/chunks/chunk-3MTZTNAU.js +101 -0
  24. package/chunks/{chunk-WHG6N5X2.js → chunk-5OHGYMKP.js} +1 -1
  25. package/chunks/{chunk-QH7736R5.js → chunk-6EQMZNIY.js} +1 -1
  26. package/chunks/chunk-6I6VGTKD.js +8 -0
  27. package/chunks/{chunk-5427BPR2.js → chunk-6M5G5FBH.js} +1 -1
  28. package/chunks/{chunk-4FVBPNTZ.js → chunk-6T2GIM76.js} +1 -1
  29. package/chunks/chunk-7ZODGQO6.js +4 -0
  30. package/chunks/chunk-AOOZREGV.js +9 -0
  31. package/chunks/{chunk-JXUDKX6D.js → chunk-DE3HKC2W.js} +1 -1
  32. package/chunks/chunk-DHDD5YJC.js +207 -0
  33. package/chunks/{chunk-SPW5DXX4.js → chunk-EZDV7A76.js} +1 -1
  34. package/chunks/{chunk-ODZOYHIC.js → chunk-GOJCMVJJ.js} +1 -1
  35. package/chunks/{chunk-FFFZ2QMG.js → chunk-GTVCJCHR.js} +1 -1
  36. package/chunks/{chunk-Q55AVE2N.js → chunk-IJEGHQ7Z.js} +11 -11
  37. package/chunks/{chunk-SUH3UUWZ.js → chunk-JCE3JAVC.js} +1 -1
  38. package/chunks/chunk-KHHJYBR5.js +9 -0
  39. package/chunks/{chunk-GO2GA2GY.js → chunk-LUNDTQ3G.js} +1 -1
  40. package/chunks/{chunk-NIQK6NX3.js → chunk-LWARA7JY.js} +1 -1
  41. package/chunks/{chunk-YMIF2DMT.js → chunk-MEV5XQI2.js} +1 -1
  42. package/chunks/{chunk-4CSSDBOS.js → chunk-P5TG5CON.js} +10 -10
  43. package/chunks/chunk-PEKAUGYV.js +2621 -0
  44. package/chunks/chunk-PGUG43HG.js +24 -0
  45. package/chunks/{chunk-ELH4YHJR.js → chunk-PGXQZVLX.js} +1 -1
  46. package/chunks/{chunk-SNLH42QJ.js → chunk-QZI2ZGZY.js} +1 -1
  47. package/chunks/chunk-RI54U73U.js +56 -0
  48. package/chunks/chunk-RPFSFS7Z.js +39 -0
  49. package/chunks/chunk-SOEIVSM5.js +113 -0
  50. package/chunks/{chunk-4J6DC24J.js → chunk-SVSY6AWS.js} +1 -1
  51. package/chunks/{chunk-T4P4KEDW.js → chunk-TWJLOEAI.js} +2 -2
  52. package/chunks/{chunk-HYVP4472.js → chunk-V6UPUMP3.js} +1 -1
  53. package/chunks/chunk-W4QSMIWO.js +9 -0
  54. package/chunks/chunk-WC2VTVCE.js +27 -0
  55. package/chunks/{chunk-GUFIMKF5.js → chunk-YV3PUOBU.js} +1 -1
  56. package/chunks/chunk-ZX34M2GF.js +14 -0
  57. package/chunks/{computer-use-SXP25RZQ.js → computer-use-J4GAM4M6.js} +1 -1
  58. package/chunks/contextCommand-5F5M7NA4.js +3 -0
  59. package/chunks/{cron-create-2UI4AT4Q.js → cron-create-IDWSZENI.js} +1 -1
  60. package/chunks/{cron-delete-ZB6BOTFF.js → cron-delete-NQCDZDUI.js} +1 -1
  61. package/chunks/{cron-list-YYAXNHB6.js → cron-list-Z4XMC3TO.js} +1 -1
  62. package/chunks/{de-DNEPG7S7.js → de-34YZHGC6.js} +3 -3
  63. package/chunks/{devtools-5JRKK3E7.js → devtools-XRQ4YJ5S.js} +1 -1
  64. package/chunks/{dist-P6SLWL5V.js → dist-PH6JW7XD.js} +1 -1
  65. package/chunks/edit-X2S2ZXRN.js +43 -0
  66. package/chunks/{en-NOD6KQNM.js → en-QLGMD6OS.js} +3 -3
  67. package/chunks/{enter-worktree-X47BSJLE.js → enter-worktree-TUCGNCLO.js} +1 -1
  68. package/chunks/{enterPlanMode-F22ZNTYJ.js → enterPlanMode-SQEZAAIR.js} +1 -1
  69. package/chunks/{exit-worktree-XY5UMDHX.js → exit-worktree-7FLITFZI.js} +1 -1
  70. package/chunks/exitPlanMode-O5UUJ3GM.js +120 -0
  71. package/chunks/{fr-2OE5WLJ4.js → fr-EDNBQACJ.js} +3 -3
  72. package/chunks/geminiContentGenerator-FIZFLPU3.js +8 -0
  73. package/chunks/glob-GSFTYAS2.js +22 -0
  74. package/chunks/{goal-tools-6QTC3UI7.js → goal-tools-YQOA6OKU.js} +1 -1
  75. package/chunks/{grep-6TTPZ524.js → grep-VAB2VSXM.js} +1 -1
  76. package/chunks/{ja-3B6V5KS7.js → ja-LV4RLM3M.js} +3 -3
  77. package/chunks/{keychain-token-storage-54BNK6VH.js → keychain-token-storage-KQK6MNOJ.js} +1 -1
  78. package/chunks/{ls-YWZU3FYL.js → ls-IZJ3CKZY.js} +1 -1
  79. package/chunks/{lsp-4CJDKEEC.js → lsp-NGLDRHZU.js} +1 -1
  80. package/chunks/matildaAgentContentGenerator-QQHPCFJ5.js +8 -0
  81. package/chunks/matildaContentGenerator-W7Z33ONU.js +8 -0
  82. package/chunks/{matildaOAuth2-WOY7ZS43.js → matildaOAuth2-7COTQQR2.js} +1 -1
  83. package/chunks/mcp-client-DXUNIEIB.js +3 -0
  84. package/chunks/monitor-4PFIGAGG.js +32 -0
  85. package/chunks/notebook-edit-MWJYAATJ.js +17 -0
  86. package/chunks/{openaiContentGenerator-MGASUFQL.js → openaiContentGenerator-NDVJL6QL.js} +1 -1
  87. package/chunks/{pt-KP2JCPUY.js → pt-5SQ4DGL7.js} +3 -3
  88. package/chunks/read-file-WPZKPXWA.js +3 -0
  89. package/chunks/ripGrep-7LZDZFTX.js +3 -0
  90. package/chunks/{ru-K7IQQKHC.js → ru-7K24S53N.js} +3 -3
  91. package/chunks/scheduler-DK2MVKXX.js +8 -0
  92. package/chunks/{send-message-OO2HAKCC.js → send-message-TCPX5UDU.js} +1 -1
  93. package/chunks/{serve-ZQX2WBLF.js → serve-GSZPJI2O.js} +59 -48
  94. package/chunks/shell-PRS47PDP.js +3 -0
  95. package/chunks/{skill-KDM3UUML.js → skill-ETQM5NI3.js} +1 -1
  96. package/chunks/src-UB7DZRYK.js +3 -0
  97. package/chunks/{symbol-search-ALYOX5JN.js → symbol-search-HARHZ5AH.js} +1 -1
  98. package/chunks/{syntheticOutput-UASKABJH.js → syntheticOutput-WZDPECYS.js} +1 -1
  99. package/chunks/task-create-XRNIDT4T.js +3 -0
  100. package/chunks/{task-detach-I67ZE5MX.js → task-detach-TBAVUOTC.js} +1 -1
  101. package/chunks/task-list-Z6BDZZID.js +9 -0
  102. package/chunks/{task-stop-ERI5X4AO.js → task-stop-HDSARSJ6.js} +1 -1
  103. package/chunks/{task-update-CD3W556L.js → task-update-MW2VT2XV.js} +1 -1
  104. package/chunks/{team-create-F4KQRGMB.js → team-create-VMYNLZCC.js} +1 -1
  105. package/chunks/team-delete-F7QDC2TE.js +8 -0
  106. package/chunks/todoWrite-SCF5M24M.js +3 -0
  107. package/chunks/{tool-search-JFCD5W5M.js → tool-search-WX6FOE35.js} +1 -1
  108. package/chunks/tree-sitter-bash-2SWKO5B7.js +3 -0
  109. package/chunks/{web-fetch-REWGIRWQ.js → web-fetch-CKYBHGLF.js} +13 -13
  110. package/chunks/{web-search-OX2DPEVN.js → web-search-67DFNS5V.js} +1 -1
  111. package/chunks/{workflow-SEFYGBED.js → workflow-WBSRQG3N.js} +2 -2
  112. package/chunks/write-file-S5FAX4JJ.js +15 -0
  113. package/cli.js +462 -455
  114. package/locales/ca.js +1 -3
  115. package/locales/de.js +1 -3
  116. package/locales/en.js +1 -3
  117. package/locales/fr.js +1 -3
  118. package/locales/ja.js +1 -3
  119. package/locales/pt.js +1 -3
  120. package/locales/ru.js +1 -3
  121. package/package.json +2 -2
  122. package/sandbox-macos-permissive-closed.sb +0 -1
  123. package/sandbox-macos-permissive-open.sb +0 -1
  124. package/sandbox-macos-permissive-proxied.sb +0 -1
  125. package/sandbox-macos-restrictive-closed.sb +3 -1
  126. package/sandbox-macos-restrictive-open.sb +3 -1
  127. package/sandbox-macos-restrictive-proxied.sb +3 -1
  128. package/bundled/mainy/docs/features/channels/dingtalk.md +0 -134
  129. package/bundled/mainy/docs/features/channels/feishu.md +0 -186
  130. package/bundled/mainy/docs/features/channels/weixin.md +0 -106
  131. package/chunks/agent-ZFZ4HJQC.js +0 -3
  132. package/chunks/agent-headless-KH2BKLP7.js +0 -3
  133. package/chunks/chunk-25NCTG5H.js +0 -184
  134. package/chunks/chunk-2HQMJ2IU.js +0 -8
  135. package/chunks/chunk-6GBNB5Z2.js +0 -3
  136. package/chunks/chunk-GHBKFIHC.js +0 -35
  137. package/chunks/chunk-HWOQNYAO.js +0 -27
  138. package/chunks/chunk-LJR4RZZ2.js +0 -3
  139. package/chunks/chunk-NVM7W7TG.js +0 -101
  140. package/chunks/chunk-PA6532AY.js +0 -6
  141. package/chunks/chunk-QFNFLE2I.js +0 -2625
  142. package/chunks/chunk-QN6WSWMM.js +0 -9
  143. package/chunks/chunk-RK2AKQAX.js +0 -39
  144. package/chunks/chunk-U347OO7S.js +0 -9
  145. package/chunks/chunk-UIRBHC5X.js +0 -3
  146. package/chunks/chunk-W5CGKUM4.js +0 -15
  147. package/chunks/chunk-WRQLIPXW.js +0 -113
  148. package/chunks/chunk-WVY2P6WH.js +0 -26
  149. package/chunks/chunk-WZ75OGYY.js +0 -14
  150. package/chunks/chunk-XCFLI3OC.js +0 -9
  151. package/chunks/chunk-XMZIY7XX.js +0 -13
  152. package/chunks/contextCommand-3GN5CAOK.js +0 -3
  153. package/chunks/dist-ME6647DQ.js +0 -195
  154. package/chunks/dist-VG3ZDJ2A.js +0 -28
  155. package/chunks/dist-YTCHM57U.js +0 -23
  156. package/chunks/edit-KX6V4PH3.js +0 -39
  157. package/chunks/exitPlanMode-G3QLIWJ4.js +0 -90
  158. package/chunks/geminiContentGenerator-EQEGOXOV.js +0 -8
  159. package/chunks/glob-KSBEWI3E.js +0 -22
  160. package/chunks/matildaAgentContentGenerator-OV4U6DJD.js +0 -8
  161. package/chunks/matildaContentGenerator-ETIAWE22.js +0 -8
  162. package/chunks/monitor-F4K5HOZX.js +0 -32
  163. package/chunks/notebook-edit-TL7CI5EA.js +0 -17
  164. package/chunks/read-file-6EAPS2KG.js +0 -3
  165. package/chunks/ripGrep-K6SFFUIE.js +0 -3
  166. package/chunks/scheduler-TKWPD4LP.js +0 -8
  167. package/chunks/shell-AZRK5GIO.js +0 -3
  168. package/chunks/src-SGI6VLOS.js +0 -3
  169. package/chunks/task-create-EBJD55TB.js +0 -3
  170. package/chunks/task-list-5BGX4G5N.js +0 -9
  171. package/chunks/team-delete-5U3GBFKJ.js +0 -8
  172. package/chunks/todoWrite-YGG6AZ3A.js +0 -3
  173. package/chunks/tree-sitter-bash-XNCMPQBK.js +0 -3
  174. package/chunks/write-file-UAGVBZMC.js +0 -15
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ba as cu}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{d as g,f as oo}from"./chunk-OWGSC52X.js";var Dr=g(U=>{"use strict";f();Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Cr=class{};U._CodeOrName=Cr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var jt=class extends Cr{constructor(e){if(super(),!U.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};U.Name=jt;var Re=class extends Cr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof jt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Re;U.nil=new Re("");function lu(t,...e){let r=[t[0]],n=0;for(;n<e.length;)io(r,e[n]),r.push(t[++n]);return new Re(r)}U._=lu;var ao=new Re("+");function du(t,...e){let r=[qr(t[0])],n=0;for(;n<e.length;)r.push(ao),io(r,e[n]),r.push(ao,qr(t[++n]));return Ym(r),new Re(r)}U.str=du;function io(t,e){e instanceof Re?t.push(...e._items):e instanceof jt?t.push(e):t.push(eh(e))}U.addCodeArg=io;function Ym(t){let e=1;for(;e<t.length-1;){if(t[e]===ao){let r=Qm(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Qm(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof jt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof jt))return`"${t}${e.slice(1)}`}function Zm(t,e){return e.emptyStr()?t:t.emptyStr()?e:du`${t}${e}`}U.strConcat=Zm;function eh(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:qr(Array.isArray(t)?t.join(","):t)}function th(t){return new Re(qr(t))}U.stringify=th;function qr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=qr;function rh(t){return typeof t=="string"&&U.IDENTIFIER.test(t)?new Re(`.${t}`):lu`[${t}]`}U.getProperty=rh;function nh(t){if(typeof t=="string"&&U.IDENTIFIER.test(t))return new Re(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}U.getEsmExportName=nh;function sh(t){return new Re(t.toString())}U.regexpCode=sh});var lo=g($e=>{"use strict";f();Object.defineProperty($e,"__esModule",{value:!0});$e.ValueScope=$e.ValueScopeName=$e.Scope=$e.varKinds=$e.UsedValueState=void 0;var ge=Dr(),co=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zn;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zn||($e.UsedValueState=zn={}));$e.varKinds={const:new ge.Name("const"),let:new ge.Name("let"),var:new ge.Name("var")};var Ln=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ge.Name?e:this.name(e)}name(e){return new ge.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};$e.Scope=Ln;var Un=class extends ge.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ge._)`.${new ge.Name(r)}[${n}]`}};$e.ValueScopeName=Un;var oh=(0,ge._)`\n`,uo=class extends Ln{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?oh:ge.nil}}get(){return this._scope}name(e){return new Un(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,a=(n=r.key)!==null&&n!==void 0?n:r.ref,i=this._values[o];if(i){let u=i.get(a);if(u)return u}else i=this._values[o]=new Map;i.set(a,s);let c=this._scope[o]||(this._scope[o]=[]),d=c.length;return c[d]=r.ref,s.setValue(r,{property:o,itemIndex:d}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ge._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=ge.nil;for(let a in e){let i=e[a];if(!i)continue;let c=n[a]=n[a]||new Map;i.forEach(d=>{if(c.has(d))return;c.set(d,zn.Started);let u=r(d);if(u){let l=this.opts.es5?$e.varKinds.var:$e.varKinds.const;o=(0,ge._)`${o}${l} ${d} = ${u};${this.opts._n}`}else if(u=s?.(d))o=(0,ge._)`${o}${u}${this.opts._n}`;else throw new co(d);c.set(d,zn.Completed)})}return o}};$e.ValueScope=uo});var O=g(I=>{"use strict";f();Object.defineProperty(I,"__esModule",{value:!0});I.or=I.and=I.not=I.CodeGen=I.operators=I.varKinds=I.ValueScopeName=I.ValueScope=I.Scope=I.Name=I.regexpCode=I.stringify=I.getProperty=I.nil=I.strConcat=I.str=I._=void 0;var V=Dr(),xe=lo(),ft=Dr();Object.defineProperty(I,"_",{enumerable:!0,get:function(){return ft._}});Object.defineProperty(I,"str",{enumerable:!0,get:function(){return ft.str}});Object.defineProperty(I,"strConcat",{enumerable:!0,get:function(){return ft.strConcat}});Object.defineProperty(I,"nil",{enumerable:!0,get:function(){return ft.nil}});Object.defineProperty(I,"getProperty",{enumerable:!0,get:function(){return ft.getProperty}});Object.defineProperty(I,"stringify",{enumerable:!0,get:function(){return ft.stringify}});Object.defineProperty(I,"regexpCode",{enumerable:!0,get:function(){return ft.regexpCode}});Object.defineProperty(I,"Name",{enumerable:!0,get:function(){return ft.Name}});var Hn=lo();Object.defineProperty(I,"Scope",{enumerable:!0,get:function(){return Hn.Scope}});Object.defineProperty(I,"ValueScope",{enumerable:!0,get:function(){return Hn.ValueScope}});Object.defineProperty(I,"ValueScopeName",{enumerable:!0,get:function(){return Hn.ValueScopeName}});Object.defineProperty(I,"varKinds",{enumerable:!0,get:function(){return Hn.varKinds}});I.operators={GT:new V._Code(">"),GTE:new V._Code(">="),LT:new V._Code("<"),LTE:new V._Code("<="),EQ:new V._Code("==="),NEQ:new V._Code("!=="),NOT:new V._Code("!"),OR:new V._Code("||"),AND:new V._Code("&&"),ADD:new V._Code("+")};var nt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},fo=class extends nt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?xe.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Zt(this.rhs,e,r)),this}get names(){return this.rhs instanceof V._CodeOrName?this.rhs.names:{}}},Fn=class extends nt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof V.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Zt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof V.Name?{}:{...this.lhs.names};return Gn(e,this.rhs)}},po=class extends Fn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},mo=class extends nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ho=class extends nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},yo=class extends nt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},_o=class extends nt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Zt(this.code,e,r),this}get names(){return this.code instanceof V._CodeOrName?this.code.names:{}}},Mr=class extends nt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(ah(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ct(e,r.names),{})}},st=class extends Mr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},go=class extends Mr{},Qt=class extends st{};Qt.kind="else";var At=class t extends st{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Qt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(fu(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Zt(this.condition,e,r),this}get names(){let e=super.names;return Gn(e,this.condition),this.else&&Ct(e,this.else.names),e}};At.kind="if";var It=class extends st{};It.kind="for";var $o=class extends It{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Zt(this.iteration,e,r),this}get names(){return Ct(super.names,this.iteration.names)}},vo=class extends It{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?xe.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Gn(super.names,this.from);return Gn(e,this.to)}},Kn=class extends It{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Zt(this.iterable,e,r),this}get names(){return Ct(super.names,this.iterable.names)}},Vr=class extends st{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Vr.kind="func";var xr=class extends Mr{render(e){return"return "+super.render(e)}};xr.kind="return";var wo=class extends st{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ct(e,this.catch.names),this.finally&&Ct(e,this.finally.names),e}},zr=class extends st{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};zr.kind="catch";var Lr=class extends st{render(e){return"finally"+super.render(e)}};Lr.kind="finally";var bo=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
3
+ import{ba as cu}from"./chunk-27Q5KW3A.js";import{b as f}from"./chunk-GZPNIYVZ.js";import{d as g,f as oo}from"./chunk-OWGSC52X.js";var Dr=g(U=>{"use strict";f();Object.defineProperty(U,"__esModule",{value:!0});U.regexpCode=U.getEsmExportName=U.getProperty=U.safeStringify=U.stringify=U.strConcat=U.addCodeArg=U.str=U._=U.nil=U._Code=U.Name=U.IDENTIFIER=U._CodeOrName=void 0;var Cr=class{};U._CodeOrName=Cr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var jt=class extends Cr{constructor(e){if(super(),!U.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};U.Name=jt;var Re=class extends Cr{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof jt&&(r[n.str]=(r[n.str]||0)+1),r),{})}};U._Code=Re;U.nil=new Re("");function lu(t,...e){let r=[t[0]],n=0;for(;n<e.length;)io(r,e[n]),r.push(t[++n]);return new Re(r)}U._=lu;var ao=new Re("+");function du(t,...e){let r=[qr(t[0])],n=0;for(;n<e.length;)r.push(ao),io(r,e[n]),r.push(ao,qr(t[++n]));return Ym(r),new Re(r)}U.str=du;function io(t,e){e instanceof Re?t.push(...e._items):e instanceof jt?t.push(e):t.push(eh(e))}U.addCodeArg=io;function Ym(t){let e=1;for(;e<t.length-1;){if(t[e]===ao){let r=Qm(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Qm(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof jt||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof jt))return`"${t}${e.slice(1)}`}function Zm(t,e){return e.emptyStr()?t:t.emptyStr()?e:du`${t}${e}`}U.strConcat=Zm;function eh(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:qr(Array.isArray(t)?t.join(","):t)}function th(t){return new Re(qr(t))}U.stringify=th;function qr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=qr;function rh(t){return typeof t=="string"&&U.IDENTIFIER.test(t)?new Re(`.${t}`):lu`[${t}]`}U.getProperty=rh;function nh(t){if(typeof t=="string"&&U.IDENTIFIER.test(t))return new Re(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}U.getEsmExportName=nh;function sh(t){return new Re(t.toString())}U.regexpCode=sh});var lo=g($e=>{"use strict";f();Object.defineProperty($e,"__esModule",{value:!0});$e.ValueScope=$e.ValueScopeName=$e.Scope=$e.varKinds=$e.UsedValueState=void 0;var ge=Dr(),co=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zn;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zn||($e.UsedValueState=zn={}));$e.varKinds={const:new ge.Name("const"),let:new ge.Name("let"),var:new ge.Name("var")};var Ln=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ge.Name?e:this.name(e)}name(e){return new ge.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};$e.Scope=Ln;var Un=class extends ge.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ge._)`.${new ge.Name(r)}[${n}]`}};$e.ValueScopeName=Un;var oh=(0,ge._)`\n`,uo=class extends Ln{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?oh:ge.nil}}get(){return this._scope}name(e){return new Un(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,a=(n=r.key)!==null&&n!==void 0?n:r.ref,i=this._values[o];if(i){let u=i.get(a);if(u)return u}else i=this._values[o]=new Map;i.set(a,s);let c=this._scope[o]||(this._scope[o]=[]),d=c.length;return c[d]=r.ref,s.setValue(r,{property:o,itemIndex:d}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,ge._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=ge.nil;for(let a in e){let i=e[a];if(!i)continue;let c=n[a]=n[a]||new Map;i.forEach(d=>{if(c.has(d))return;c.set(d,zn.Started);let u=r(d);if(u){let l=this.opts.es5?$e.varKinds.var:$e.varKinds.const;o=(0,ge._)`${o}${l} ${d} = ${u};${this.opts._n}`}else if(u=s?.(d))o=(0,ge._)`${o}${u}${this.opts._n}`;else throw new co(d);c.set(d,zn.Completed)})}return o}};$e.ValueScope=uo});var O=g(I=>{"use strict";f();Object.defineProperty(I,"__esModule",{value:!0});I.or=I.and=I.not=I.CodeGen=I.operators=I.varKinds=I.ValueScopeName=I.ValueScope=I.Scope=I.Name=I.regexpCode=I.stringify=I.getProperty=I.nil=I.strConcat=I.str=I._=void 0;var V=Dr(),xe=lo(),ft=Dr();Object.defineProperty(I,"_",{enumerable:!0,get:function(){return ft._}});Object.defineProperty(I,"str",{enumerable:!0,get:function(){return ft.str}});Object.defineProperty(I,"strConcat",{enumerable:!0,get:function(){return ft.strConcat}});Object.defineProperty(I,"nil",{enumerable:!0,get:function(){return ft.nil}});Object.defineProperty(I,"getProperty",{enumerable:!0,get:function(){return ft.getProperty}});Object.defineProperty(I,"stringify",{enumerable:!0,get:function(){return ft.stringify}});Object.defineProperty(I,"regexpCode",{enumerable:!0,get:function(){return ft.regexpCode}});Object.defineProperty(I,"Name",{enumerable:!0,get:function(){return ft.Name}});var Hn=lo();Object.defineProperty(I,"Scope",{enumerable:!0,get:function(){return Hn.Scope}});Object.defineProperty(I,"ValueScope",{enumerable:!0,get:function(){return Hn.ValueScope}});Object.defineProperty(I,"ValueScopeName",{enumerable:!0,get:function(){return Hn.ValueScopeName}});Object.defineProperty(I,"varKinds",{enumerable:!0,get:function(){return Hn.varKinds}});I.operators={GT:new V._Code(">"),GTE:new V._Code(">="),LT:new V._Code("<"),LTE:new V._Code("<="),EQ:new V._Code("==="),NEQ:new V._Code("!=="),NOT:new V._Code("!"),OR:new V._Code("||"),AND:new V._Code("&&"),ADD:new V._Code("+")};var nt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},fo=class extends nt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?xe.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Zt(this.rhs,e,r)),this}get names(){return this.rhs instanceof V._CodeOrName?this.rhs.names:{}}},Fn=class extends nt{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof V.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Zt(this.rhs,e,r),this}get names(){let e=this.lhs instanceof V.Name?{}:{...this.lhs.names};return Gn(e,this.rhs)}},po=class extends Fn{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},mo=class extends nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},ho=class extends nt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},yo=class extends nt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},_o=class extends nt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Zt(this.code,e,r),this}get names(){return this.code instanceof V._CodeOrName?this.code.names:{}}},Mr=class extends nt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(ah(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ct(e,r.names),{})}},st=class extends Mr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},go=class extends Mr{},Qt=class extends st{};Qt.kind="else";var At=class t extends st{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Qt(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(fu(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Zt(this.condition,e,r),this}get names(){let e=super.names;return Gn(e,this.condition),this.else&&Ct(e,this.else.names),e}};At.kind="if";var It=class extends st{};It.kind="for";var $o=class extends It{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Zt(this.iteration,e,r),this}get names(){return Ct(super.names,this.iteration.names)}},vo=class extends It{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?xe.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Gn(super.names,this.from);return Gn(e,this.to)}},Kn=class extends It{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Zt(this.iterable,e,r),this}get names(){return Ct(super.names,this.iterable.names)}},Vr=class extends st{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Vr.kind="func";var xr=class extends Mr{render(e){return"return "+super.render(e)}};xr.kind="return";var wo=class extends st{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Ct(e,this.catch.names),this.finally&&Ct(e,this.finally.names),e}},zr=class extends st{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};zr.kind="catch";var Lr=class extends st{render(e){return"finally"+super.render(e)}};Lr.kind="finally";var bo=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
4
4
  `:""},this._extScope=e,this._scope=new xe.Scope({parent:e}),this._nodes=[new go]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new fo(e,o,n)),o}const(e,r,n){return this._def(xe.varKinds.const,e,r,n)}let(e,r,n){return this._def(xe.varKinds.let,e,r,n)}var(e,r,n){return this._def(xe.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Fn(e,r,n))}add(e,r){return this._leafNode(new po(e,I.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==V.nil&&this._leafNode(new _o(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,V.addCodeArg)(r,s));return r.push("}"),new V._Code(r)}if(e,r,n){if(this._blockNode(new At(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new At(e))}else(){return this._elseNode(new Qt)}endIf(){return this._endBlockNode(At,Qt)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new $o(e),r)}forRange(e,r,n,s,o=this.opts.es5?xe.varKinds.var:xe.varKinds.let){let a=this._scope.toName(e);return this._for(new vo(o,a,r,n),()=>s(a))}forOf(e,r,n,s=xe.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let a=r instanceof V.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,V._)`${a}.length`,i=>{this.var(o,(0,V._)`${a}[${i}]`),n(o)})}return this._for(new Kn("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?xe.varKinds.var:xe.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,V._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Kn("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(It)}label(e){return this._leafNode(new mo(e))}break(e){return this._leafNode(new ho(e))}return(e){let r=new xr;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(xr)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new wo;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new zr(o),r(o)}return n&&(this._currNode=s.finally=new Lr,this.code(n)),this._endBlockNode(zr,Lr)}throw(e){return this._leafNode(new yo(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=V.nil,n,s){return this._blockNode(new Vr(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Vr)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof At))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};I.CodeGen=bo;function Ct(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Gn(t,e){return e instanceof V._CodeOrName?Ct(t,e.names):t}function Zt(t,e,r){if(t instanceof V.Name)return n(t);if(!s(t))return t;return new V._Code(t._items.reduce((o,a)=>(a instanceof V.Name&&(a=n(a)),a instanceof V._Code?o.push(...a._items):o.push(a),o),[]));function n(o){let a=r[o.str];return a===void 0||e[o.str]!==1?o:(delete e[o.str],a)}function s(o){return o instanceof V._Code&&o._items.some(a=>a instanceof V.Name&&e[a.str]===1&&r[a.str]!==void 0)}}function ah(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function fu(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,V._)`!${Eo(t)}`}I.not=fu;var ih=pu(I.operators.AND);function ch(...t){return t.reduce(ih)}I.and=ch;var uh=pu(I.operators.OR);function lh(...t){return t.reduce(uh)}I.or=lh;function pu(t){return(e,r)=>e===V.nil?r:r===V.nil?e:(0,V._)`${Eo(e)} ${t} ${Eo(r)}`}function Eo(t){return t instanceof V.Name?t:(0,V._)`(${t})`}});var M=g(q=>{"use strict";f();Object.defineProperty(q,"__esModule",{value:!0});q.checkStrictMode=q.getErrorPath=q.Type=q.useFunc=q.setEvaluated=q.evaluatedPropsToName=q.mergeEvaluated=q.eachItem=q.unescapeJsonPointer=q.escapeJsonPointer=q.escapeFragment=q.unescapeFragment=q.schemaRefOrVal=q.schemaHasRulesButRef=q.schemaHasRules=q.checkUnknownRules=q.alwaysValidSchema=q.toHash=void 0;var W=O(),dh=Dr();function fh(t){let e={};for(let r of t)e[r]=!0;return e}q.toHash=fh;function ph(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(yu(t,e),!_u(e,t.self.RULES.all))}q.alwaysValidSchema=ph;function yu(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||vu(t,`unknown keyword: "${o}"`)}q.checkUnknownRules=yu;function _u(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}q.schemaHasRules=_u;function mh(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}q.schemaHasRulesButRef=mh;function hh({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,W._)`${r}`}return(0,W._)`${t}${e}${(0,W.getProperty)(n)}`}q.schemaRefOrVal=hh;function yh(t){return gu(decodeURIComponent(t))}q.unescapeFragment=yh;function _h(t){return encodeURIComponent(Po(t))}q.escapeFragment=_h;function Po(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}q.escapeJsonPointer=Po;function gu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}q.unescapeJsonPointer=gu;function gh(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}q.eachItem=gh;function mu({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,a,i)=>{let c=a===void 0?o:a instanceof W.Name?(o instanceof W.Name?t(s,o,a):e(s,o,a),a):o instanceof W.Name?(e(s,a,o),o):r(o,a);return i===W.Name&&!(c instanceof W.Name)?n(s,c):c}}q.mergeEvaluated={props:mu({mergeNames:(t,e,r)=>t.if((0,W._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,W._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,W._)`${r} || {}`).code((0,W._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,W._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,W._)`${r} || {}`),To(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$u}),items:mu({mergeNames:(t,e,r)=>t.if((0,W._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,W._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,W._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,W._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $u(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,W._)`{}`);return e!==void 0&&To(t,r,e),r}q.evaluatedPropsToName=$u;function To(t,e,r){Object.keys(r).forEach(n=>t.assign((0,W._)`${e}${(0,W.getProperty)(n)}`,!0))}q.setEvaluated=To;var hu={};function $h(t,e){return t.scopeValue("func",{ref:e,code:hu[e.code]||(hu[e.code]=new dh._Code(e.code))})}q.useFunc=$h;var So;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(So||(q.Type=So={}));function vh(t,e,r){if(t instanceof W.Name){let n=e===So.Num;return r?n?(0,W._)`"[" + ${t} + "]"`:(0,W._)`"['" + ${t} + "']"`:n?(0,W._)`"/" + ${t}`:(0,W._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,W.getProperty)(t).toString():"/"+Po(t)}q.getErrorPath=vh;function vu(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}q.checkStrictMode=vu});var Oe=g(ko=>{"use strict";f();Object.defineProperty(ko,"__esModule",{value:!0});var ce=O(),wh={data:new ce.Name("data"),valCxt:new ce.Name("valCxt"),instancePath:new ce.Name("instancePath"),parentData:new ce.Name("parentData"),parentDataProperty:new ce.Name("parentDataProperty"),rootData:new ce.Name("rootData"),dynamicAnchors:new ce.Name("dynamicAnchors"),vErrors:new ce.Name("vErrors"),errors:new ce.Name("errors"),this:new ce.Name("this"),self:new ce.Name("self"),scope:new ce.Name("scope"),json:new ce.Name("json"),jsonPos:new ce.Name("jsonPos"),jsonLen:new ce.Name("jsonLen"),jsonPart:new ce.Name("jsonPart")};ko.default=wh});var Ur=g(ue=>{"use strict";f();Object.defineProperty(ue,"__esModule",{value:!0});ue.extendErrors=ue.resetErrorsCount=ue.reportExtraError=ue.reportError=ue.keyword$DataError=ue.keywordError=void 0;var z=O(),Wn=M(),me=Oe();ue.keywordError={message:({keyword:t})=>(0,z.str)`must pass "${t}" keyword validation`};ue.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,z.str)`"${t}" keyword must be ${e} ($data)`:(0,z.str)`"${t}" keyword is invalid ($data)`};function bh(t,e=ue.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:a,allErrors:i}=s,c=Eu(t,e,r);n??(a||i)?wu(o,c):bu(s,(0,z._)`[${c}]`)}ue.reportError=bh;function Eh(t,e=ue.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:a}=n,i=Eu(t,e,r);wu(s,i),o||a||bu(n,me.default.vErrors)}ue.reportExtraError=Eh;function Sh(t,e){t.assign(me.default.errors,e),t.if((0,z._)`${me.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,z._)`${me.default.vErrors}.length`,e),()=>t.assign(me.default.vErrors,null)))}ue.resetErrorsCount=Sh;function Ph({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let a=t.name("err");t.forRange("i",s,me.default.errors,i=>{t.const(a,(0,z._)`${me.default.vErrors}[${i}]`),t.if((0,z._)`${a}.instancePath === undefined`,()=>t.assign((0,z._)`${a}.instancePath`,(0,z.strConcat)(me.default.instancePath,o.errorPath))),t.assign((0,z._)`${a}.schemaPath`,(0,z.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,z._)`${a}.schema`,r),t.assign((0,z._)`${a}.data`,n))})}ue.extendErrors=Ph;function wu(t,e){let r=t.const("err",e);t.if((0,z._)`${me.default.vErrors} === null`,()=>t.assign(me.default.vErrors,(0,z._)`[${r}]`),(0,z._)`${me.default.vErrors}.push(${r})`),t.code((0,z._)`${me.default.errors}++`)}function bu(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,z._)`new ${t.ValidationError}(${e})`):(r.assign((0,z._)`${n}.errors`,e),r.return(!1))}var qt={keyword:new z.Name("keyword"),schemaPath:new z.Name("schemaPath"),params:new z.Name("params"),propertyName:new z.Name("propertyName"),message:new z.Name("message"),schema:new z.Name("schema"),parentSchema:new z.Name("parentSchema")};function Eu(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,z._)`{}`:Th(t,e,r)}function Th(t,e,r={}){let{gen:n,it:s}=t,o=[kh(s,r),Rh(t,r)];return Oh(t,e,o),n.object(...o)}function kh({errorPath:t},{instancePath:e}){let r=e?(0,z.str)`${t}${(0,Wn.getErrorPath)(e,Wn.Type.Str)}`:t;return[me.default.instancePath,(0,z.strConcat)(me.default.instancePath,r)]}function Rh({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,z.str)`${e}/${t}`;return r&&(s=(0,z.str)`${s}${(0,Wn.getErrorPath)(r,Wn.Type.Str)}`),[qt.schemaPath,s]}function Oh(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:a,it:i}=t,{opts:c,propertyName:d,topSchemaRef:u,schemaPath:l}=i;n.push([qt.keyword,s],[qt.params,typeof e=="function"?e(t):e||(0,z._)`{}`]),c.messages&&n.push([qt.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([qt.schema,a],[qt.parentSchema,(0,z._)`${u}${l}`],[me.default.data,o]),d&&n.push([qt.propertyName,d])}});var Pu=g(er=>{"use strict";f();Object.defineProperty(er,"__esModule",{value:!0});er.boolOrEmptySchema=er.topBoolOrEmptySchema=void 0;var Nh=Ur(),jh=O(),Ah=Oe(),Ih={message:"boolean schema is false"};function Ch(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Su(t,!1):typeof r=="object"&&r.$async===!0?e.return(Ah.default.data):(e.assign((0,jh._)`${n}.errors`,null),e.return(!0))}er.topBoolOrEmptySchema=Ch;function qh(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Su(t)):r.var(e,!0)}er.boolOrEmptySchema=qh;function Su(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Nh.reportError)(s,Ih,void 0,e)}});var Ro=g(tr=>{"use strict";f();Object.defineProperty(tr,"__esModule",{value:!0});tr.getRules=tr.isJSONType=void 0;var Dh=["string","number","integer","boolean","null","object","array"],Mh=new Set(Dh);function Vh(t){return typeof t=="string"&&Mh.has(t)}tr.isJSONType=Vh;function xh(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}tr.getRules=xh});var Oo=g(pt=>{"use strict";f();Object.defineProperty(pt,"__esModule",{value:!0});pt.shouldUseRule=pt.shouldUseGroup=pt.schemaHasRulesForType=void 0;function zh({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Tu(t,n)}pt.schemaHasRulesForType=zh;function Tu(t,e){return e.rules.some(r=>ku(t,r))}pt.shouldUseGroup=Tu;function ku(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}pt.shouldUseRule=ku});var Fr=g(le=>{"use strict";f();Object.defineProperty(le,"__esModule",{value:!0});le.reportTypeError=le.checkDataTypes=le.checkDataType=le.coerceAndCheckDataType=le.getJSONTypes=le.getSchemaTypes=le.DataType=void 0;var Lh=Ro(),Uh=Oo(),Fh=Ur(),N=O(),Ru=M(),rr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(rr||(le.DataType=rr={}));function Kh(t){let e=Ou(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}le.getSchemaTypes=Kh;function Ou(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Lh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}le.getJSONTypes=Ou;function Gh(t,e){let{gen:r,data:n,opts:s}=t,o=Hh(e,s.coerceTypes),a=e.length>0&&!(o.length===0&&e.length===1&&(0,Uh.schemaHasRulesForType)(t,e[0]));if(a){let i=jo(e,n,s.strictNumbers,rr.Wrong);r.if(i,()=>{o.length?Wh(t,e,o):Ao(t)})}return a}le.coerceAndCheckDataType=Gh;var Nu=new Set(["string","number","integer","boolean","null"]);function Hh(t,e){return e?t.filter(r=>Nu.has(r)||e==="array"&&r==="array"):[]}function Wh(t,e,r){let{gen:n,data:s,opts:o}=t,a=n.let("dataType",(0,N._)`typeof ${s}`),i=n.let("coerced",(0,N._)`undefined`);o.coerceTypes==="array"&&n.if((0,N._)`${a} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,N._)`${s}[0]`).assign(a,(0,N._)`typeof ${s}`).if(jo(e,s,o.strictNumbers),()=>n.assign(i,s))),n.if((0,N._)`${i} !== undefined`);for(let d of r)(Nu.has(d)||d==="array"&&o.coerceTypes==="array")&&c(d);n.else(),Ao(t),n.endIf(),n.if((0,N._)`${i} !== undefined`,()=>{n.assign(s,i),Jh(t,i)});function c(d){switch(d){case"string":n.elseIf((0,N._)`${a} == "number" || ${a} == "boolean"`).assign(i,(0,N._)`"" + ${s}`).elseIf((0,N._)`${s} === null`).assign(i,(0,N._)`""`);return;case"number":n.elseIf((0,N._)`${a} == "boolean" || ${s} === null
5
5
  || (${a} == "string" && ${s} && ${s} == +${s})`).assign(i,(0,N._)`+${s}`);return;case"integer":n.elseIf((0,N._)`${a} === "boolean" || ${s} === null
6
6
  || (${a} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(i,(0,N._)`+${s}`);return;case"boolean":n.elseIf((0,N._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(i,!1).elseIf((0,N._)`${s} === "true" || ${s} === 1`).assign(i,!0);return;case"null":n.elseIf((0,N._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(i,null);return;case"array":n.elseIf((0,N._)`${a} === "string" || ${a} === "number"
@@ -18,7 +18,7 @@ import{ba as cu}from"./chunk-MH2P4YXC.js";import{b as f}from"./chunk-GZPNIYVZ.js
18
18
  `)}formatDetailed(e,r=Date.now()){let n=this.getSummary(r),s=n.totalToolCalls>0?n.successRate??n.successfulToolCalls/n.totalToolCalls*100:0,o=[];o.push(`\u{1F4CB} Task Completed: ${e}`),o.push(`\u23F1\uFE0F Duration: ${this.fmtDuration(n.totalDurationMs)} | \u{1F501} Rounds: ${n.rounds}`);let a="Poor execution";s>=95?a="Excellent execution":s>=85?a="Good execution":s>=70&&(a="Fair execution"),o.push(`\u2705 Quality: ${a} (${s.toFixed(1)}% tool success)`);let i=n.totalDurationMs,c="Long execution - consider breaking down tasks";if(i<1e4?c="Fast completion - under 10 seconds":i<6e4?c="Good speed - under a minute":i<3e5&&(c="Moderate duration - a few minutes"),o.push(`\u{1F680} Speed: ${c}`),o.push(`\u{1F527} Tools: ${n.totalToolCalls} calls, ${s.toFixed(1)}% success (${n.successfulToolCalls} ok, ${n.failedToolCalls} failed)`),typeof n.totalTokens=="number"){let u=[`in ${n.inputTokens??0}`,`out ${n.outputTokens??0}`];o.push(`\u{1F522} Tokens: ${n.totalTokens.toLocaleString()} (${u.join(", ")})`)}if(n.toolUsage&&n.toolUsage.length){let u=[...n.toolUsage].sort((l,y)=>y.count-l.count).slice(0,5);o.push(`
19
19
  Top tools:`);for(let l of u){let y=typeof l.averageDurationMs=="number"?`, avg ${this.fmtDuration(Math.round(l.averageDurationMs))}`:"";o.push(` - ${l.name}: ${l.count} calls (${l.success} ok, ${l.failure} fail${y}${l.lastError?`, last error: ${l.lastError}`:""})`)}}let d=this.generatePerformanceTips(n);if(d.length){o.push(`
20
20
  \u{1F4A1} Performance Insights:`);for(let u of d.slice(0,3))o.push(` - ${u}`)}return o.join(`
21
- `)}fmtDuration(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;if(e<36e5){let s=Math.floor(e/6e4),o=Math.floor(e%6e4/1e3);return`${s}m ${o}s`}let r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return`${r}h ${n}m`}generatePerformanceTips(e){let r=[],n=e.totalToolCalls;if((e.totalToolCalls>0?e.successRate??e.successfulToolCalls/e.totalToolCalls*100:0)<80&&r.push("Low tool success rate - review inputs and error messages"),e.totalDurationMs>6e4&&r.push("Long execution time - consider breaking down complex tasks"),typeof e.totalTokens=="number"&&e.totalTokens>1e5&&r.push("High token usage - consider optimizing prompts or narrowing scope"),typeof e.totalTokens=="number"&&n>0){let c=e.totalTokens/n;c>5e3&&r.push(`High token usage per tool call (~${Math.round(c)} tokens/call)`)}let o=c=>/web|fetch|search/i.test(c);(e.toolUsage||[]).some(c=>o(c.name)&&c.lastError&&/timeout|network/i.test(c.lastError))&&r.push("Network operations had failures - consider increasing timeout or checking connectivity");let i=(e.toolUsage||[]).filter(c=>(c.averageDurationMs??0)>1e4).sort((c,d)=>(d.averageDurationMs??0)-(c.averageDurationMs??0));return i.length&&r.push(`Consider optimizing ${i[0].name} operations (avg ${this.fmtDuration(Math.round(i[0].averageDurationMs))})`),r}};f();var Jm=class{constructor(e){this.params=e}toolLocations(){return[]}getDefaultPermission(){return Promise.resolve("allow")}getConfirmationDetails(e){let r={type:"info",title:`Confirm ${this.constructor.name.replace(/Invocation$/,"")}`,prompt:this.getDescription(),onConfirm:async(n,s)=>{}};return Promise.resolve(r)}},au=class{constructor(e,r,n,s,o,a=!0,i=!1,c=!1,d=!1,u){this.name=e;this.displayName=r;this.description=n;this.kind=s;this.parameterSchema=o;this.isOutputMarkdown=a;this.canUpdateOutput=i;this.shouldDefer=c;this.alwaysLoad=d;this.searchHint=u}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchema}}get maxOutputChars(){}get truncateKeep(){return"both"}toAutoClassifierInput(e){return""}validateToolParams(e){return null}async buildAndExecute(e,r,n,s){return this.build(e).execute(r,n,s)}silentBuild(e){try{return this.build(e)}catch(r){return r instanceof Error?r:new Error(String(r))}}async validateBuildAndExecute(e,r){let n=this.silentBuild(e);if(n instanceof Error){let s=n.message;return{llmContent:`Error: Invalid parameters provided. Reason: ${s}`,returnDisplay:s,error:{message:s,type:"invalid_tool_params"}}}try{return await n.execute(r)}catch(s){let o=s instanceof Error?s.message:String(s);return{llmContent:`Error: Tool call execution failed. Reason: ${o}`,returnDisplay:o,error:{message:o,type:"execution_failed"}}}}},Bm=class extends au{build(e){let r=this.validateToolParams(e);if(r)throw new Error(r);return this.createInvocation(e)}validateToolParams(e){let r=to.validate(this.schema.parametersJsonSchema,e);return r||this.validateToolParamValues(e)}validateToolParamValues(e){return null}};function VN(t){return typeof t=="object"&&t!==null&&"name"in t&&"build"in t&&typeof t.build=="function"}function xN(t){function e(n){if(!n.startsWith("#/"))return null;let s=n.substring(2).split("/"),o=t;for(let a of s){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,a))return null;o=o[a]}return o}function r(n,s,o){if(typeof n!="object"||n===null)return!1;if(Array.isArray(n)){for(let a of n)if(r(a,s,o))return!0;return!1}if("$ref"in n&&typeof n.$ref=="string"){let a=n.$ref;if(a==="#/"||o.has(a))return!0;if(s.has(a))return!1;let i=e(a);if(i){s.add(a),o.add(a);let c=r(i,s,o);return o.delete(a),c}}for(let a in n)if(Object.prototype.hasOwnProperty.call(n,a)&&r(n[a],s,o))return!0;return!1}return r(t,new Set,new Set)}var JP=(d=>(d.ProceedOnce="proceed_once",d.ProceedAlways="proceed_always",d.ProceedAlwaysServer="proceed_always_server",d.ProceedAlwaysTool="proceed_always_tool",d.ProceedAlwaysProject="proceed_always_project",d.ProceedAlwaysUser="proceed_always_user",d.ModifyWithEditor="modify_with_editor",d.RestorePrevious="restore_previous",d.Cancel="cancel",d))(JP||{}),BP=(u=>(u.Read="read",u.Edit="edit",u.Delete="delete",u.Move="move",u.Search="search",u.Execute="execute",u.Think="think",u.Fetch="fetch",u.Agent="agent",u.Other="other",u))(BP||{}),zN=["edit","delete","move","execute"],LN=new Set(["read","search","fetch"]);f();var iu={EDIT:"edit",WRITE_FILE:"write_file",READ_FILE:"read_file",GREP:"grep_search",GLOB:"glob",SHELL:"run_shell_command",TODO_WRITE:"todo_write",MEMORY:"save_memory",AGENT:"agent",SKILL:"skill",EXIT_PLAN_MODE:"exit_plan_mode",ENTER_PLAN_MODE:"enter_plan_mode",GET_GOAL:"get_goal",UPDATE_GOAL:"update_goal",WEB_FETCH:"web_fetch",WEB_SEARCH:"web_search",SYMBOL_SEARCH:"symbol_search",LS:"list_directory",LSP:"lsp",ASK_USER_QUESTION:"ask_user_question",CRON_CREATE:"cron_create",CRON_LIST:"cron_list",CRON_DELETE:"cron_delete",TASK_STOP:"task_stop",TASK_DETACH:"task_detach",TASK_CREATE:"task_create",TASK_UPDATE:"task_update",TASK_LIST:"task_list",TEAM_CREATE:"team_create",TEAM_DELETE:"team_delete",SEND_MESSAGE:"send_message",STRUCTURED_OUTPUT:"structured_output",MONITOR:"monitor",NOTEBOOK_EDIT:"notebook_edit",TOOL_SEARCH:"tool_search",ENTER_WORKTREE:"enter_worktree",EXIT_WORKTREE:"exit_worktree",WORKFLOW:"workflow"},no={EDIT:"Edit",WRITE_FILE:"WriteFile",READ_FILE:"ReadFile",GREP:"Grep",GLOB:"Glob",SHELL:"Shell",TODO_WRITE:"TodoWrite",MEMORY:"SaveMemory",AGENT:"Agent",SKILL:"Skill",EXIT_PLAN_MODE:"ExitPlanMode",ENTER_PLAN_MODE:"EnterPlanMode",GET_GOAL:"Goal",UPDATE_GOAL:"UpdateGoal",WEB_FETCH:"WebFetch",WEB_SEARCH:"WebSearch",SYMBOL_SEARCH:"SymbolSearch",LS:"ListFiles",LSP:"Lsp",ASK_USER_QUESTION:"AskUserQuestion",CRON_CREATE:"CronCreate",CRON_LIST:"CronList",CRON_DELETE:"CronDelete",TASK_STOP:"TaskStop",TASK_DETACH:"TaskDetach",TASK_CREATE:"TaskCreate",TASK_UPDATE:"TaskUpdate",TASK_LIST:"TaskList",TEAM_CREATE:"TeamCreate",TEAM_DELETE:"TeamDelete",SEND_MESSAGE:"SendMessage",STRUCTURED_OUTPUT:"StructuredOutput",MONITOR:"Monitor",NOTEBOOK_EDIT:"NotebookEdit",TOOL_SEARCH:"ToolSearch",ENTER_WORKTREE:"EnterWorktree",EXIT_WORKTREE:"ExitWorktree",WORKFLOW:"Workflow"},Xm={search_file_content:iu.GREP,replace:iu.EDIT,task:iu.AGENT};function KN(t){return Object.prototype.hasOwnProperty.call(Xm,t)?Xm[t]??t:t}var GN={SearchFiles:no.GREP,FindFiles:no.GLOB,ReadFolder:no.LS,Task:no.AGENT};export{uu as a,Kr as b,Yo as c,Dm as d,to as e,Wm as f,Jm as g,au as h,Bm as i,VN as j,xN as k,JP as l,BP as m,zN as n,LN as o,iu as p,no as q,Xm as r,KN as s,GN as t};
21
+ `)}fmtDuration(e){if(e<1e3)return`${Math.round(e)}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;if(e<36e5){let s=Math.floor(e/6e4),o=Math.floor(e%6e4/1e3);return`${s}m ${o}s`}let r=Math.floor(e/36e5),n=Math.floor(e%36e5/6e4);return`${r}h ${n}m`}generatePerformanceTips(e){let r=[],n=e.totalToolCalls;if((e.totalToolCalls>0?e.successRate??e.successfulToolCalls/e.totalToolCalls*100:0)<80&&r.push("Low tool success rate - review inputs and error messages"),e.totalDurationMs>6e4&&r.push("Long execution time - consider breaking down complex tasks"),typeof e.totalTokens=="number"&&e.totalTokens>1e5&&r.push("High token usage - consider optimizing prompts or narrowing scope"),typeof e.totalTokens=="number"&&n>0){let c=e.totalTokens/n;c>5e3&&r.push(`High token usage per tool call (~${Math.round(c)} tokens/call)`)}let o=c=>/web|fetch|search/i.test(c);(e.toolUsage||[]).some(c=>o(c.name)&&c.lastError&&/timeout|network/i.test(c.lastError))&&r.push("Network operations had failures - consider increasing timeout or checking connectivity");let i=(e.toolUsage||[]).filter(c=>(c.averageDurationMs??0)>1e4).sort((c,d)=>(d.averageDurationMs??0)-(c.averageDurationMs??0));return i.length&&r.push(`Consider optimizing ${i[0].name} operations (avg ${this.fmtDuration(Math.round(i[0].averageDurationMs))})`),r}};f();var Jm=class{constructor(e){this.params=e}toolLocations(){return[]}getDefaultPermission(){return Promise.resolve("allow")}getConfirmationDetails(e){let r={type:"info",title:`Confirm ${this.constructor.name.replace(/Invocation$/,"")}`,prompt:this.getDescription(),onConfirm:async(n,s)=>{}};return Promise.resolve(r)}},au=class{constructor(e,r,n,s,o,a=!0,i=!1,c=!1,d=!1,u){this.name=e;this.displayName=r;this.description=n;this.kind=s;this.parameterSchema=o;this.isOutputMarkdown=a;this.canUpdateOutput=i;this.shouldDefer=c;this.alwaysLoad=d;this.searchHint=u}get schema(){return{name:this.name,description:this.description,parametersJsonSchema:this.parameterSchema}}get maxOutputChars(){}get truncateKeep(){return"both"}get boundsOwnOutput(){return!1}toAutoClassifierInput(e){return""}validateToolParams(e){return null}async buildAndExecute(e,r,n,s){return this.build(e).execute(r,n,s)}silentBuild(e){try{return this.build(e)}catch(r){return r instanceof Error?r:new Error(String(r))}}async validateBuildAndExecute(e,r){let n=this.silentBuild(e);if(n instanceof Error){let s=n.message;return{llmContent:`Error: Invalid parameters provided. Reason: ${s}`,returnDisplay:s,error:{message:s,type:"invalid_tool_params"}}}try{return await n.execute(r)}catch(s){let o=s instanceof Error?s.message:String(s);return{llmContent:`Error: Tool call execution failed. Reason: ${o}`,returnDisplay:o,error:{message:o,type:"execution_failed"}}}}},Bm=class extends au{build(e){let r=this.validateToolParams(e);if(r)throw new Error(r);return this.createInvocation(e)}validateToolParams(e){let r=to.validate(this.schema.parametersJsonSchema,e);return r||this.validateToolParamValues(e)}validateToolParamValues(e){return null}};function VN(t){return typeof t=="object"&&t!==null&&"name"in t&&"build"in t&&typeof t.build=="function"}function xN(t){function e(n){if(!n.startsWith("#/"))return null;let s=n.substring(2).split("/"),o=t;for(let a of s){if(typeof o!="object"||o===null||!Object.prototype.hasOwnProperty.call(o,a))return null;o=o[a]}return o}function r(n,s,o){if(typeof n!="object"||n===null)return!1;if(Array.isArray(n)){for(let a of n)if(r(a,s,o))return!0;return!1}if("$ref"in n&&typeof n.$ref=="string"){let a=n.$ref;if(a==="#/"||o.has(a))return!0;if(s.has(a))return!1;let i=e(a);if(i){s.add(a),o.add(a);let c=r(i,s,o);return o.delete(a),c}}for(let a in n)if(Object.prototype.hasOwnProperty.call(n,a)&&r(n[a],s,o))return!0;return!1}return r(t,new Set,new Set)}var JP=(d=>(d.ProceedOnce="proceed_once",d.ProceedAlways="proceed_always",d.ProceedAlwaysServer="proceed_always_server",d.ProceedAlwaysTool="proceed_always_tool",d.ProceedAlwaysProject="proceed_always_project",d.ProceedAlwaysUser="proceed_always_user",d.ModifyWithEditor="modify_with_editor",d.RestorePrevious="restore_previous",d.Cancel="cancel",d))(JP||{}),BP=(u=>(u.Read="read",u.Edit="edit",u.Delete="delete",u.Move="move",u.Search="search",u.Execute="execute",u.Think="think",u.Fetch="fetch",u.Agent="agent",u.Other="other",u))(BP||{}),zN=["edit","delete","move","execute"],LN=new Set(["read","search","fetch"]);f();var iu={EDIT:"edit",WRITE_FILE:"write_file",READ_FILE:"read_file",GREP:"grep_search",GLOB:"glob",SHELL:"run_shell_command",TODO_WRITE:"todo_write",MEMORY:"save_memory",AGENT:"agent",SKILL:"skill",EXIT_PLAN_MODE:"exit_plan_mode",ENTER_PLAN_MODE:"enter_plan_mode",GET_GOAL:"get_goal",UPDATE_GOAL:"update_goal",WEB_FETCH:"web_fetch",WEB_SEARCH:"web_search",SYMBOL_SEARCH:"symbol_search",LS:"list_directory",LSP:"lsp",ASK_USER_QUESTION:"ask_user_question",CRON_CREATE:"cron_create",CRON_LIST:"cron_list",CRON_DELETE:"cron_delete",TASK_STOP:"task_stop",TASK_DETACH:"task_detach",TASK_CREATE:"task_create",TASK_UPDATE:"task_update",TASK_LIST:"task_list",TEAM_CREATE:"team_create",TEAM_DELETE:"team_delete",SEND_MESSAGE:"send_message",STRUCTURED_OUTPUT:"structured_output",MONITOR:"monitor",NOTEBOOK_EDIT:"notebook_edit",TOOL_SEARCH:"tool_search",ENTER_WORKTREE:"enter_worktree",EXIT_WORKTREE:"exit_worktree",WORKFLOW:"workflow"},no={EDIT:"Edit",WRITE_FILE:"WriteFile",READ_FILE:"ReadFile",GREP:"Grep",GLOB:"Glob",SHELL:"Shell",TODO_WRITE:"TodoWrite",MEMORY:"SaveMemory",AGENT:"Agent",SKILL:"Skill",EXIT_PLAN_MODE:"ExitPlanMode",ENTER_PLAN_MODE:"EnterPlanMode",GET_GOAL:"Goal",UPDATE_GOAL:"UpdateGoal",WEB_FETCH:"WebFetch",WEB_SEARCH:"WebSearch",SYMBOL_SEARCH:"SymbolSearch",LS:"ListFiles",LSP:"Lsp",ASK_USER_QUESTION:"AskUserQuestion",CRON_CREATE:"CronCreate",CRON_LIST:"CronList",CRON_DELETE:"CronDelete",TASK_STOP:"TaskStop",TASK_DETACH:"TaskDetach",TASK_CREATE:"TaskCreate",TASK_UPDATE:"TaskUpdate",TASK_LIST:"TaskList",TEAM_CREATE:"TeamCreate",TEAM_DELETE:"TeamDelete",SEND_MESSAGE:"SendMessage",STRUCTURED_OUTPUT:"StructuredOutput",MONITOR:"Monitor",NOTEBOOK_EDIT:"NotebookEdit",TOOL_SEARCH:"ToolSearch",ENTER_WORKTREE:"EnterWorktree",EXIT_WORKTREE:"ExitWorktree",WORKFLOW:"Workflow"},Xm={search_file_content:iu.GREP,replace:iu.EDIT,task:iu.AGENT};function KN(t){return Object.prototype.hasOwnProperty.call(Xm,t)?Xm[t]??t:t}var GN={SearchFiles:no.GREP,FindFiles:no.GLOB,ReadFolder:no.LS,Task:no.AGENT};export{uu as a,Kr as b,Yo as c,Dm as d,to as e,Wm as f,Jm as g,au as h,Bm as i,VN as j,xN as k,JP as l,BP as m,zN as n,LN as o,iu as p,no as q,Xm as r,KN as s,GN as t};
22
22
  /**
23
23
  * @license
24
24
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as o}from"./chunk-GZPNIYVZ.js";o();function l(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var c=/<[^<>]*>/g;function r(t){return t!==void 0&&/\s/.test(t)}function a(t){let e=t.codePointAt(0);return e===void 0?!1:e===173||e===1564||e===12644||e===65279||e===65440||e>=0&&e<=31||e>=127&&e<=159||e>=4447&&e<=4448||e>=6068&&e<=6069||e>=6155&&e<=6159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e>=65024&&e<=65039||e>=65520&&e<=65528||e>=113824&&e<=113827||e>=119155&&e<=119162||e>=917504&&e<=921599}function x(t){let e="";for(let i of t)a(i)||(e+=i);return e.toLowerCase()}function d(t){let e=x(t),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let n=1;for(;n<i&&r(e[n]);)n++;let s=!1;for(e[n]==="/"&&(s=!0,n++);n<i&&r(e[n]);)n++;let f="system-reminder";if(e.slice(n,n+f.length)===f){if(n+=f.length,n<i-1&&r(e[n])){for(;n<i&&r(e[n]);)n++;for(;n<i&&e[n]!==">";)n++}for(;n<i&&r(e[n]);)n++;for(e[n]==="/"&&n++;n<i&&r(e[n]);)n++;if(!(n!==i-1||e[n]!==">"))return s?"closing":"other"}}function g(t){let e=d(t);return e==="closing"?"<\\/system-reminder>":e==="other"?l(t):t}function u(t){return t.replace(c,g)}export{l as a,u as b};
3
+ import{b as o}from"./chunk-GZPNIYVZ.js";o();function x(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var c=/<[^<>]*>/g;function r(t){return t!==void 0&&/\s/.test(t)}function d(t){let e=t.codePointAt(0);return e===void 0?!1:e===173||e===1564||e===12644||e===65279||e===65440||e>=0&&e<=31||e>=127&&e<=159||e>=4447&&e<=4448||e>=6068&&e<=6069||e>=6155&&e<=6159||e>=8203&&e<=8207||e>=8234&&e<=8238||e>=8288&&e<=8303||e>=65024&&e<=65039||e>=65520&&e<=65528||e>=113824&&e<=113827||e>=119155&&e<=119162||e>=917504&&e<=921599}function l(t){let e="";for(let i of t)d(i)||(e+=i);return e.toLowerCase()}function u(t){let e=l(t),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let n=1;for(;n<i&&r(e[n]);)n++;let s=!1;for(e[n]==="/"&&(s=!0,n++);n<i&&r(e[n]);)n++;let f="system-reminder";if(e.slice(n,n+f.length)===f){if(n+=f.length,n<i-1&&r(e[n])){for(;n<i&&r(e[n]);)n++;for(;n<i&&e[n]!==">";)n++}for(;n<i&&r(e[n]);)n++;for(e[n]==="/"&&n++;n<i&&r(e[n]);)n++;if(!(n!==i-1||e[n]!==">"))return s?"closing":"other"}}function m(t){let e=u(t);return e==="closing"?"<\\/system-reminder>":e==="other"?x(t):t}function a(t){return t.replace(c,m)}function p(t){return Array.isArray(t)?t.map(g):g(t)}function g(t){return typeof t=="string"?a(t):t.text===void 0?t:{...t,text:a(t.text)}}export{x as a,a as b,p as c};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Matilda
@@ -0,0 +1,9 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{e as g}from"./chunk-ZX34M2GF.js";import{b as h}from"./chunk-7ZODGQO6.js";import{b as M}from"./chunk-TISQNFB5.js";import{c as w}from"./chunk-LUNDTQ3G.js";import{b as c,ba as b}from"./chunk-27Q5KW3A.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,27 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{c as U}from"./chunk-KHHJYBR5.js";import{c as Q}from"./chunk-VI74YQQO.js";import{a as Y,b as N}from"./chunk-3YLXGE6T.js";import{b as X}from"./chunk-LUNDTQ3G.js";import{Q as S,ba as I}from"./chunk-27Q5KW3A.js";import{b as M}from"./chunk-GZPNIYVZ.js";M();import ie from"crypto";import q from"node:path";import{promises as b}from"node:fs";import{EventEmitter as Re}from"events";import{randomUUID as se}from"node:crypto";M();import{execFile as le,spawn as de}from"node:child_process";import{promisify as he}from"node:util";import{platform as ue}from"node:os";import{resolve as Z}from"node:path";import{URL as fe,fileURLToPath as me}from"node:url";var ee=he(le);function pe(i,{allowFile:e=!1,allowedFilePaths:r}={}){let t;try{t=new fe(i)}catch{throw new Error(`Invalid URL: ${i}`)}let o=e?["http:","https:","file:"]:["http:","https:"];if(!o.includes(t.protocol))throw new Error(`Unsafe protocol: ${t.protocol}. Only ${o.join(", ")} are allowed.`);if(t.protocol==="file:"&&e){if(!r?.length)throw new Error("allowedFilePaths is required when allowFile is true");let n=Z(me(t));if(!r.map(c=>Z(c)).includes(n))throw new Error("File URL is not in the allowed file set")}if(/[\r\n\x00-\x1f]/.test(i))throw new Error("URL contains invalid characters")}async function te(i,e={}){pe(i,e);let r=ue(),t,o,n=process.env.BROWSER?.trim(),s=r==="win32"?void 0:we(n,i);if(s)try{await re(s.command,s.args);return}catch(l){console.warn(`Failed to open BROWSER command ${s.command}: ${ge(l)}. Falling back to the platform browser opener.`)}if(!N({ignoreBrowserBlocklist:!0})){console.warn(`Browser launch is not available in this environment. Please open this URL manually: ${i}`);return}switch(r){case"darwin":t="open",o=[i];break;case"win32":t="powershell.exe",o=["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`Start-Process '${i.replace(/'/g,"''")}'`];break;case"linux":case"freebsd":case"openbsd":t="xdg-open",o=[i];break;default:throw new Error(`Unsupported platform: ${r}`)}let c={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};try{await ee(t,o,c)}catch{if((r==="linux"||r==="freebsd"||r==="openbsd")&&t==="xdg-open"){let a=[{command:"gnome-open",detached:!1},{command:"kde-open",detached:!1},{command:"firefox",detached:!0},{command:"chromium",detached:!0},{command:"google-chrome",detached:!0},{command:"microsoft-edge",detached:!0}];for(let{command:d,detached:p}of a)try{p?await re(d,[i]):await ee(d,[i],c);return}catch{continue}}console.warn(`Failed to open browser automatically. Please open this URL manually: ${i}`);return}}async function re(i,e){let r={env:{...process.env,SHELL:void 0},detached:!0,stdio:"ignore"};await new Promise((t,o)=>{let n=de(i,e,r),s=!1;n.once("error",c=>{s||(s=!0,o(c))}),n.once("spawn",()=>{s||(s=!0,n.unref(),t())})})}function ge(i){return i instanceof Error?i.message:String(i)}function we(i,e){if(!i)return;let r=ke(i);if(!r){console.warn("Invalid BROWSER environment variable, falling back to platform default.");return}if(Y(r.command))return;let t=!1,o=r.args.map(n=>n.includes("%s")?(t=!0,n.replace(/%s/g,()=>e)):n);return t||o.push(e),{command:r.command,args:o}}function ke(i){let e=[],r="",t;for(let s of i){if(t){s===t?t=void 0:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r&&(e.push(r),r="");continue}r+=s}if(t)return;r&&e.push(r);let[o,...n]=e;if(o)return{command:o,args:n}}function Ve(){return N()}M();import H from"node:path";import{promises as y,unlinkSync as Ee}from"node:fs";import{randomUUID as ne}from"node:crypto";var D=I("MATILDA_OAUTH"),_e="oauth_creds.json",Ce="oauth_creds.lock",ve=30*1e3,ye=35e3,Te=5e3,oe={maxAttempts:20,attemptInterval:100,maxInterval:2e3};var h=class extends Error{constructor(r,t,o){super(t);this.type=r;this.originalError=o;this.name="TokenManagerError"}};function De(i){if(!i||typeof i!="object")throw new Error("Invalid credentials format");let e=i,r=["access_token","refresh_token","token_type"];for(let t of r)if(!e[t]||typeof e[t]!="string")throw new Error(`Invalid credentials: missing ${t}`);if(!e.expiry_date||typeof e.expiry_date!="number")throw new Error("Invalid credentials: missing expiry_date");return e}var R=class i{static instance=null;memoryCache={credentials:null,fileModTime:0,lastCheck:0};refreshPromise=null;checkPromise=null;cleanupHandlersRegistered=!1;cleanupFunction=null;lockConfig=oe;constructor(){this.registerCleanupHandlers()}static getInstance(){return i.instance||(i.instance=new i),i.instance}registerCleanupHandlers(){this.cleanupHandlersRegistered||(this.cleanupFunction=()=>{try{let e=this.getLockFilePath();Ee(e)}catch{}},process.on("exit",this.cleanupFunction),this.cleanupHandlersRegistered=!0)}async getValidCredentials(e,r=!1){try{if(await this.checkAndReloadIfNeeded(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let t=this.refreshPromise;t||(t=this.performTokenRefresh(e,r),this.refreshPromise=t);try{return await t}finally{this.refreshPromise===t&&(this.refreshPromise=null)}}catch(t){throw t instanceof h?t:new h("REFRESH_FAILED",`Failed to get valid credentials: ${t instanceof Error?t.message:String(t)}`,t)}}async checkAndReloadIfNeeded(e){if(this.checkPromise){await this.checkPromise;return}if(this.refreshPromise)return;let r=Date.now();if(!(r-this.memoryCache.lastCheck<Te)){this.checkPromise=this.performFileCheck(e,r);try{await this.checkPromise}finally{this.checkPromise=null}}}withTimeout(e,r,t="Operation"){let o;return Promise.race([e.finally(()=>{o&&clearTimeout(o)}),new Promise((n,s)=>{o=setTimeout(()=>s(new Error(`${t} timed out after ${r}ms`)),r)})])}async performFileCheck(e,r){this.memoryCache.lastCheck=r;try{let t=this.getCredentialFilePath(),n=(await this.withTimeout(y.stat(t),3e3,"File operation")).mtimeMs;n>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=n)}catch(t){if(t instanceof Error&&"code"in t&&t.code!=="ENOENT")throw this.updateCacheState(null,0,r),new h("FILE_ACCESS_ERROR",`Failed to access credentials file: ${t.message}`,t);this.memoryCache.fileModTime=0}}async forceFileCheck(e){try{let r=this.getCredentialFilePath(),o=(await y.stat(r)).mtimeMs;o>this.memoryCache.fileModTime&&(await this.reloadCredentialsFromFile(e),this.memoryCache.fileModTime=o,this.memoryCache.lastCheck=Date.now())}catch(r){if(r instanceof Error&&"code"in r&&r.code!=="ENOENT")throw this.updateCacheState(null,0),new h("FILE_ACCESS_ERROR",`Failed to access credentials file during refresh: ${r.message}`,r);this.memoryCache.fileModTime=0}}async reloadCredentialsFromFile(e){try{let r=this.getCredentialFilePath(),t=await y.readFile(r,"utf-8"),o=JSON.parse(t),n=De(o),s=this.memoryCache.credentials;this.memoryCache.credentials=n;try{e&&e.setCredentials(n)}catch(c){throw this.memoryCache.credentials=s,c}}catch(r){r instanceof Error&&r.message.includes("Invalid credentials")&&D.warn(`Failed to validate credentials file: ${r.message}`),this.memoryCache.credentials=null}}async performTokenRefresh(e,r=!1){let t=Date.now(),o=this.getLockFilePath(),n=!1;try{let s=e.getCredentials();if(!s.refresh_token)throw new h("NO_REFRESH_TOKEN","No refresh token available for token refresh");await this.acquireLock(o),n=!0;let c=Date.now()-t;if(c>5e3&&D.warn(`Token refresh lock acquisition took ${c}ms`),await this.forceFileCheck(e),!r&&this.memoryCache.credentials&&this.isTokenValid(this.memoryCache.credentials))return this.memoryCache.credentials;let l=await e.refreshAccessToken(),a=Date.now()-t;if(a>1e4&&D.warn(`Token refresh operation took ${a}ms`),!l||L(l)){let w=l;throw new h("REFRESH_FAILED",`Token refresh failed: ${w?.error||"Unknown error"} - ${w?.error_description||"No details provided"}`)}let d=l;if(!d.access_token)throw new h("REFRESH_FAILED","Failed to refresh access token: no token returned");let p={access_token:d.access_token,token_type:d.token_type,refresh_token:d.refresh_token||s.refresh_token,resource_url:d.resource_url,expiry_date:Date.now()+d.expires_in*1e3};return this.memoryCache.credentials=p,e.setCredentials(p),await this.saveCredentialsToFile(p),p}catch(s){throw s instanceof F?(D.debug("SharedTokenManager: Clearing memory cache due to credentials clear requirement"),this.memoryCache.credentials=null,this.memoryCache.fileModTime=0,this.refreshPromise=null,new h("REFRESH_FAILED",s.message,s)):s instanceof h?s:s instanceof Error&&(s.message.includes("fetch")||s.message.includes("network")||s.message.includes("timeout"))?new h("NETWORK_ERROR",`Network error during token refresh: ${s.message}`,s):new h("REFRESH_FAILED",`Unexpected error during token refresh: ${s instanceof Error?s.message:String(s)}`,s)}finally{n&&await this.releaseLock(o)}}async saveCredentialsToFile(e){let r=this.getCredentialFilePath(),t=H.dirname(r);try{await this.withTimeout(y.mkdir(t,{recursive:!0,mode:448}),5e3,"File operation")}catch(n){throw new h("FILE_ACCESS_ERROR",`Failed to create credentials directory: ${n instanceof Error?n.message:String(n)}`,n)}let o=JSON.stringify(e,null,2);try{await X(r,o,{mode:384,forceMode:!0,noFollow:!0});let n=await this.withTimeout(y.stat(r),5e3,"File operation");this.memoryCache.fileModTime=n.mtimeMs}catch(n){throw new h("FILE_ACCESS_ERROR",`Failed to write credentials file: ${n instanceof Error?n.message:String(n)}`,n)}}isTokenValid(e){return!e.expiry_date||!e.access_token?!1:Date.now()<e.expiry_date-ve}getCredentialFilePath(){return H.join(S.getGlobalMatildaDir(),_e)}getLockFilePath(){return H.join(S.getGlobalMatildaDir(),Ce)}async acquireLock(e){let{maxAttempts:r,attemptInterval:t,maxInterval:o}=this.lockConfig,n=ne(),s=t;for(let c=0;c<r;c++)try{await y.writeFile(e,n,{flag:"wx"});return}catch(l){if(l.code==="EEXIST"){try{let a=await y.stat(e),d=Date.now()-a.mtimeMs;if(d>ye){let p=`${e}.stale.${ne()}`;try{await y.rename(e,p),await y.unlink(p),D.warn(`Removed stale lock file: ${e} (age: ${d}ms)`);continue}catch(w){D.warn(`Failed to remove stale lock file ${e}: ${w instanceof Error?w.message:String(w)}`)}}}catch(a){D.warn(`Failed to stat lock file ${e}: ${a instanceof Error?a.message:String(a)}`)}await new Promise(a=>setTimeout(a,s)),s=Math.min(s*1.5,o)}else throw new h("FILE_ACCESS_ERROR",`Failed to create lock file: ${l instanceof Error?l.message:String(l)}`,l)}throw new h("LOCK_TIMEOUT","Failed to acquire file lock for token refresh: timeout exceeded")}async releaseLock(e){try{await y.unlink(e)}catch(r){r.code!=="ENOENT"&&D.warn(`Failed to release lock file ${e}: ${r instanceof Error?r.message:String(r)}`)}}updateCacheState(e,r,t){this.memoryCache={credentials:e,fileModTime:r,lastCheck:t??Date.now()}}clearCache(){this.updateCacheState(null,0,0),this.refreshPromise=null,this.checkPromise=null}getCurrentCredentials(){return this.memoryCache.credentials}isRefreshInProgress(){return this.refreshPromise!==null}setLockConfig(e){this.lockConfig={...oe,...e}}cleanup(){this.cleanupFunction&&this.cleanupHandlersRegistered&&(this.cleanupFunction(),process.removeListener("exit",this.cleanupFunction),this.cleanupHandlersRegistered=!1,this.cleanupFunction=null)}getDebugInfo(){let e=!!this.memoryCache.credentials,r=e?!this.isTokenValid(this.memoryCache.credentials):!1;return{hasCredentials:e,credentialsExpired:r,isRefreshing:this.isRefreshInProgress(),cacheAge:Date.now()-this.memoryCache.lastCheck}}};var u=I("MATILDA_OAUTH"),G="https://chat.matilda.ai",Ae=`${G}/api/v1/oauth2/device/code`,K=`${G}/api/v1/oauth2/token`,z="f0304373b74a44d2b584a3fb70ca9e56",Me="openid profile email model.completion",be="urn:ietf:params:oauth:grant-type:device_code",Pe=3e4,Se="oauth_creds.json";function Fe(){return ie.randomBytes(32).toString("base64url")}function Oe(i){let e=ie.createHash("sha256");return e.update(i),e.digest("base64url")}function xe(){let i=Fe(),e=Oe(i);return{code_verifier:i,code_challenge:e}}function B(i){return Object.keys(i).map(e=>`${encodeURIComponent(e)}=${encodeURIComponent(i[e])}`).join("&")}function W(i,e){let r=e?"Token refresh timeout":"Token refresh failed";return new Error(`${r}: ${U(i,{url:K})}`,{cause:i})}var F=class extends Error{constructor(r,t){super(r);this.originalError=t;this.name="CredentialsClearRequiredError"}},j=class extends Error{status;oauthError;description;constructor(e){super(`Device token poll failed: ${e.oauthError??"Unknown error"} - ${e.description??"(no description)"}`),this.name="MatildaOAuthPollError",this.oauthError=e.oauthError,this.description=e.description,this.status=e.status}};function V(i){return"device_code"in i}function Ie(i){return"access_token"in i&&i.access_token!==null&&i.access_token!==void 0&&typeof i.access_token=="string"&&i.access_token.length>0}function Le(i){return"status"in i&&i.status==="pending"}function L(i){return"error"in i}var J=class{credentials={};sharedManager;constructor(){this.sharedManager=R.getInstance()}setCredentials(e){this.credentials=e}getCredentials(){return this.credentials}async getAccessToken(){try{return{token:(await this.sharedManager.getValidCredentials(this)).access_token}}catch(e){return u.warn("Failed to get access token from shared manager:",e),{token:void 0}}}async requestDeviceAuthorization(e,r){let t={client_id:z,scope:e.scope,code_challenge:e.code_challenge,code_challenge_method:e.code_challenge_method},o=await fetch(Ae,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json","x-request-id":se()},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let s=await o.text();throw new Error(`Device authorization failed: ${o.status} ${o.statusText}. Response: ${s}`)}let n=await o.json();if(V(n))u.debug("Device authorization result (sanitized):",{ok:!0,expires_in:n.expires_in});else{let s=n;u.debug("Device authorization result (sanitized):",{ok:!1,error:s?.error})}if(!V(n)){let s=n;throw new Error(`Device authorization failed: ${s?.error||"Unknown error"} - ${s?.error_description||"No details provided"}`)}return n}async pollDeviceToken(e,r){let t={grant_type:be,client_id:z,device_code:e.device_code,code_verifier:e.code_verifier},o=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(t),...r?.signal?{signal:r.signal}:{}});if(!o.ok){let n=await o.text(),s=null;try{s=JSON.parse(n)}catch{let l=new Error(`Device token poll failed: ${o.status} ${o.statusText}. Response: ${n}`);throw l.status=o.status,l}if(o.status===400&&s.error==="authorization_pending")return{status:"pending"};if(o.status===429&&s.error==="slow_down")return{status:"pending",slowDown:!0};throw new j({oauthError:s.error,description:s.error_description,status:o.status})}return await o.json()}async refreshAccessToken(){if(!this.credentials.refresh_token)throw new Error("No refresh token available");let e={grant_type:"refresh_token",refresh_token:this.credentials.refresh_token,client_id:z},{signal:r,cleanup:t}=Q([],{timeoutMs:Pe});u.debug("Refreshing access token...");try{let o;try{o=await fetch(K,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:B(e),signal:r})}catch(a){throw W(a,r.aborted)}if(!o.ok){let a;try{a=await o.text()}catch(d){throw W(d,r.aborted)}throw o.status===400||o.status===401?(await ae(),new F("Refresh token expired or invalid. Please use '/auth' to re-authenticate.",{status:o.status,response:a})):new Error(`Token refresh failed: ${o.status} ${o.statusText}. Response: ${a}`)}let n;try{n=await o.text()}catch(a){throw W(a,r.aborted)}let s;try{s=JSON.parse(n)}catch{throw new Error(`Legacy OAuth refresh returned invalid JSON: ${n||"(empty response body)"}`)}if(L(s)){let a=s;throw new Error(`Token refresh failed: ${a?.error||"Unknown error"} - ${a?.error_description||"No details provided"}`)}let c=s,l={access_token:c.access_token,token_type:c.token_type,refresh_token:c.refresh_token||this.credentials.refresh_token,resource_url:c.resource_url,expiry_date:Date.now()+c.expires_in*1e3};return this.setCredentials(l),s}finally{t()}}},$e=(t=>(t.AuthUri="auth-uri",t.AuthProgress="auth-progress",t.AuthCancel="auth-cancel",t))($e||{}),P=new Re;async function wr(i,e){let r=new J,t=R.getInstance();try{let o=await t.getValidCredentials(r);return r.setCredentials(o),r}catch(o){if(o instanceof h)switch(o.type){case"NO_REFRESH_TOKEN":u.debug("No refresh token available, proceeding with device flow");break;case"REFRESH_FAILED":u.debug("Token refresh failed, proceeding with device flow");break;case"NETWORK_ERROR":u.warn("Network error during token refresh, trying device flow");break;default:u.warn("Token manager error:",o.message)}if(e?.requireCachedCredentials)throw new Error("Matilda OAuth credentials expired. Please use /auth to re-authenticate with matilda-oauth.");let n=await Ue(r,i);if(!n.success){n.reason==="timeout"&&P.emit("auth-progress","timeout","Authentication timed out. Please try again or select a different authentication method.");let s=n.message||(()=>{switch(n.reason){case"timeout":return"Legacy OAuth authentication timed out";case"cancelled":return"Legacy OAuth authentication was cancelled by user";case"rate_limit":return"Too many requests for legacy OAuth authentication, please try again later.";case"error":default:return"Legacy OAuth authentication failed"}})();throw new Error(s)}return r}}function Ne(i){let e="Legacy OAuth Device Authorization",r=i,n=Math.min(Math.max(e.length+4,70),80),s=n-4,c=(m,T)=>{if(m.startsWith("http://")||m.startsWith("https://")){let v=[];for(let x=0;x<m.length;x+=T)v.push(m.substring(x,x+T));return v}let A=m.split(" "),C=[],_="";for(let v of A)_.length+v.length+1<=T?_+=(_?" ":"")+v:(_&&C.push(_),_=v.length>T?v.substring(0,T):v);return _&&C.push(_),C},l=" "+e+" ",a=n-2-l.length,d=Math.floor(a/2),p=a-d,w="+"+"-".repeat(d)+l+"-".repeat(p)+"+",k="|"+" ".repeat(n-2)+"|",O="+"+"-".repeat(n-2)+"+",g=c("Please visit the following URL in your browser to authorize:",s),f=c(r,s),E="Waiting for authorization to complete...";process.stderr.write(`
4
+ `+w+`
5
+ `),process.stderr.write(k+`
6
+ `);for(let m of g)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
7
+ `);process.stderr.write(k+`
8
+ `);for(let m of f)process.stderr.write("| "+m+" ".repeat(s-m.length)+` |
9
+ `);process.stderr.write(k+`
10
+ `),process.stderr.write("| "+E+" ".repeat(s-E.length)+` |
11
+ `),process.stderr.write(k+`
12
+ `),process.stderr.write(O+`
13
+
14
+ `)}async function Ue(i,e){let r=!1,t=()=>{r=!0};P.once("auth-cancel",t);let o=()=>{if(!r)return null;let c="Authentication cancelled by user.";return u.debug(`
15
+ `+c),P.emit("auth-progress","error",c),{success:!1,reason:"cancelled",message:c}},n=(c,l)=>{P.emit("auth-progress",c,l)},s=async c=>{try{await te(c)}catch(l){let a=l instanceof Error?l.message:String(l);u.warn(`Failed to open browser automatically: ${a}`),u.info(`Please open this URL manually: ${c}`)}};try{let{code_verifier:c,code_challenge:l}=xe(),a=await i.requestDeviceAuthorization({scope:Me,code_challenge:l,code_challenge_method:"S256"});if(!V(a)){let k=a;throw new Error(`Device authorization failed: ${k?.error||"Unknown error"} - ${k?.error_description||"No details provided"}`)}P.emit("auth-uri",a),(e.isBrowserLaunchSuppressed()||!e.isInteractive())&&Ne(a.verification_uri_complete),e.isBrowserLaunchSuppressed()||await s(a.verification_uri_complete),n("polling","Waiting for authorization..."),u.debug(`Waiting for authorization...
16
+ `);let d=2e3,p=Math.ceil(a.expires_in/(d/1e3));for(let k=0;k<p;k++){let O=o();if(O)return O;try{u.debug("polling for token...");let g=await i.pollDeviceToken({device_code:a.device_code,code_verifier:c});if(Ie(g)){let f=g,E={access_token:f.access_token,refresh_token:f.refresh_token||void 0,token_type:f.token_type,resource_url:f.resource_url,expiry_date:f.expires_in?Date.now()+f.expires_in*1e3:void 0};return i.setCredentials(E),await He(E),n("success","Authentication successful! Access token obtained."),u.debug("Authentication successful! Access token obtained."),{success:!0}}if(Le(g)){g.slowDown?(d=Math.min(d*1.5,1e4),u.debug(`
17
+ Server requested to slow down, increasing poll interval to ${d}ms'`)):d=2e3,n("polling",`Polling... (attempt ${k+1}/${p})`),await new Promise(m=>{let A=0,C=setInterval(()=>{if(A+=100,r){clearInterval(C),m();return}if(A>=d){clearInterval(C),m();return}},100)});let E=o();if(E)return E;continue}if(L(g)){let f=g;throw new Error(`Token polling failed: ${f?.error||"Unknown error"} - ${f?.error_description||"No details provided"}`)}}catch(g){let f=g instanceof Error?g.message:String(g),E=g instanceof Error?g.status:null,m=(C,_,v="error")=>(n(v,_),{success:!1,reason:C,message:_}),T=o();if(T)return T;if(f.includes("Failed to cache credentials"))return m("error",f);if(f.includes("401")||E===401)return m("error","Device code expired or invalid, please restart the authorization process.");if(f.includes("429")||E===429)return m("rate_limit","Too many requests. The server is rate limiting our requests. Please select a different authentication method or try again later.","rate_limit");let A=`Error polling for token: ${f}`;n("error",A),await new Promise(C=>setTimeout(C,d))}}let w="Authorization timeout, please restart the process.";return n("timeout",w),{success:!1,reason:"timeout",message:w}}catch(c){let a=`Device authorization flow failed: ${U(c,{url:G})}`;return n("error",a),{success:!1,reason:"error",message:a}}finally{P.off("auth-cancel",t)}}var $=384;async function He(i,e){let r=ce();try{await b.mkdir(q.dirname(r),{recursive:!0});let t=JSON.stringify(i,null,2),o=`${r}.tmp.${process.pid}.${se()}`;try{await b.writeFile(o,t,{mode:$,...e?.signal?{signal:e.signal}:{}});try{await b.chmod(o,$)}catch(n){if(process.platform!=="win32")throw new Error(`cacheMatildaCredentials: refusing to publish credentials \u2014 chmod 0o${$.toString(8)} on temp file failed: ${n instanceof Error?n.message:String(n)}`);u.warn(`cacheMatildaCredentials: chmod 0o${$.toString(8)} on Windows temp file ${o} failed; relying on NTFS ACL: ${n instanceof Error?n.message:String(n)}`)}await b.rename(o,r)}catch(n){try{await b.unlink(o)}catch{}throw n}try{R.getInstance().clearCache()}catch(n){u.warn(`cacheMatildaCredentials: SharedTokenManager.clearCache failed; in-process callers may serve stale credentials until the next mtime poll: ${n instanceof Error?n.message:String(n)}`)}}catch(t){let o=t instanceof Error?t.message:String(t);throw(t instanceof Error&&"code"in t?t.code:void 0)==="EACCES"?new Error(`Failed to cache credentials: Permission denied (EACCES). Current user has no permission to access \`${r}\`. Please check permissions.`):new Error(`Failed to cache credentials: error when creating folder \`${q.dirname(r)}\` and writing to \`${r}\`. ${o}. Please check permissions.`)}}async function ae(){try{let i=ce();await b.unlink(i),u.debug("Cached legacy OAuth credentials cleared successfully.")}catch(i){if(i instanceof Error&&"code"in i&&i.code==="ENOENT")return;u.warn("Warning: Failed to clear cached legacy OAuth credentials:",i)}finally{try{R.getInstance().clearCache()}catch{}}}function ce(){return q.join(S.getGlobalMatildaDir(),Se)}var kr=ae;export{te as a,Ve as b,R as c,Fe as d,Oe as e,xe as f,F as g,j as h,V as i,Ie as j,Le as k,L as l,J as m,$e as n,P as o,wr as p,$ as q,He as r,ae as s,kr as t};
18
+ /**
19
+ * @license
20
+ * Copyright 2025 Google LLC
21
+ * SPDX-License-Identifier: Apache-2.0
22
+ */
23
+ /**
24
+ * @license
25
+ * Copyright 2025 Matilda
26
+ * SPDX-License-Identifier: Apache-2.0
27
+ */