@maincode-ai/matilda-code 0.21.4 → 0.21.5-nightly.20260908.0d3c624bb

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 (97) hide show
  1. package/chunks/agent-HVAPKXWX.js +3 -0
  2. package/chunks/agent-headless-PUPP3RC4.js +3 -0
  3. package/chunks/{anthropicContentGenerator-EFVV6ZTA.js → anthropicContentGenerator-EAQDRKHH.js} +1 -1
  4. package/chunks/{askUserQuestion-MFLZ7MGJ.js → askUserQuestion-7II3GVHO.js} +1 -1
  5. package/chunks/{chunk-FUNLOUYI.js → chunk-2HFKTFO5.js} +1 -1
  6. package/chunks/{chunk-2NN5YPDR.js → chunk-4RJUXDH5.js} +1 -1
  7. package/chunks/chunk-5QAKUC2D.js +14 -0
  8. package/chunks/{chunk-3FI7EEYS.js → chunk-6UGZQN4B.js} +466 -465
  9. package/chunks/{chunk-5U3A6KMU.js → chunk-BGZJUBRA.js} +1 -1
  10. package/chunks/{chunk-SUORCDGS.js → chunk-BH56I7SB.js} +1 -1
  11. package/chunks/{chunk-C2ZWB2NT.js → chunk-FQ44TPC5.js} +1 -1
  12. package/chunks/{chunk-LQWORCPO.js → chunk-FW6Z25AA.js} +1 -1
  13. package/chunks/{chunk-ENMM2K4Q.js → chunk-GADNIYGB.js} +1 -1
  14. package/chunks/chunk-I5TKBEKD.js +32 -0
  15. package/chunks/{chunk-LCYHQMKE.js → chunk-JFE3NGGK.js} +2 -2
  16. package/chunks/{chunk-4R2OFVPK.js → chunk-L5ASITMV.js} +1 -1
  17. package/chunks/{chunk-MNGFXISD.js → chunk-LNTO3FNQ.js} +1 -1
  18. package/chunks/{chunk-QEI3OETI.js → chunk-MW3LAIJW.js} +1 -1
  19. package/chunks/{chunk-IMYUVCF7.js → chunk-N6BOYL6K.js} +1 -1
  20. package/chunks/{chunk-QLEJOI4X.js → chunk-O3OUYCSO.js} +1 -1
  21. package/chunks/{chunk-LPWRRSAI.js → chunk-O5WFAAJF.js} +1 -1
  22. package/chunks/{chunk-6QP5C76Y.js → chunk-OVC5Z3EX.js} +1 -1
  23. package/chunks/{chunk-NDR7ZFUA.js → chunk-OXHC3R2R.js} +1 -1
  24. package/chunks/{chunk-FT76AZPN.js → chunk-RQIV43CR.js} +1 -1
  25. package/chunks/{chunk-EMWHQSMS.js → chunk-SOKNPND5.js} +1 -1
  26. package/chunks/{chunk-IOCF4XSR.js → chunk-SWEYYDZO.js} +1 -1
  27. package/chunks/{chunk-QCIDUZV6.js → chunk-U3O6TMV7.js} +1 -1
  28. package/chunks/{chunk-R3H6IWFK.js → chunk-UHDKX2CR.js} +1 -1
  29. package/chunks/{chunk-UY2R3ZQ4.js → chunk-VB4MJSMC.js} +1 -1
  30. package/chunks/{chunk-XKDGRW3K.js → chunk-VBOVIARK.js} +1 -1
  31. package/chunks/{chunk-QRCRXDZ5.js → chunk-VUJBVDPG.js} +2 -2
  32. package/chunks/{chunk-OMZ5SGMK.js → chunk-X4ML2NEE.js} +1 -1
  33. package/chunks/{chunk-S4K76QPI.js → chunk-XITA5WMN.js} +1 -1
  34. package/chunks/{chunk-MJEXA2MA.js → chunk-YTGWPLEA.js} +1 -1
  35. package/chunks/{computer-use-SPPVJT3E.js → computer-use-AU7ESBHR.js} +1 -1
  36. package/chunks/contextCommand-7JB3K3SS.js +3 -0
  37. package/chunks/{cron-create-JHL5JGIM.js → cron-create-HASFXYQL.js} +1 -1
  38. package/chunks/{cron-delete-K2R3KI2W.js → cron-delete-AW4S5IYT.js} +1 -1
  39. package/chunks/{cron-list-R3YHZBHA.js → cron-list-U5U5GO6A.js} +1 -1
  40. package/chunks/{edit-SLOTIPQ6.js → edit-UCNE7J7J.js} +1 -1
  41. package/chunks/{enter-worktree-Y6PQ27LA.js → enter-worktree-XMDJZHYY.js} +1 -1
  42. package/chunks/{enterPlanMode-XXL4BNEQ.js → enterPlanMode-XMH7YSWI.js} +1 -1
  43. package/chunks/{exit-worktree-ZO3CQN6M.js → exit-worktree-66I5GTOI.js} +1 -1
  44. package/chunks/{exitPlanMode-BNBCFLEU.js → exitPlanMode-B53RZAXG.js} +1 -1
  45. package/chunks/{geminiContentGenerator-H3MOBIG3.js → geminiContentGenerator-3QYSDHWO.js} +1 -1
  46. package/chunks/glob-JPWXHPZY.js +22 -0
  47. package/chunks/{grep-MFAMPUHG.js → grep-5RIPV774.js} +1 -1
  48. package/chunks/{keychain-token-storage-EAJ6RT4S.js → keychain-token-storage-5MWTIAEL.js} +1 -1
  49. package/chunks/{ls-4QPI2E7A.js → ls-IBIDQ5NV.js} +1 -1
  50. package/chunks/{lsp-P3GKBOP3.js → lsp-ELR2BGT4.js} +1 -1
  51. package/chunks/matildaAgentContentGenerator-2GOFJGOD.js +8 -0
  52. package/chunks/matildaContentGenerator-CCBXB5RF.js +8 -0
  53. package/chunks/{matildaOAuth2-LKOMJUC6.js → matildaOAuth2-5EYRIK66.js} +1 -1
  54. package/chunks/monitor-4FVSFXU5.js +32 -0
  55. package/chunks/notebook-edit-RTTGOHIQ.js +17 -0
  56. package/chunks/{openaiContentGenerator-CCKR4OUB.js → openaiContentGenerator-PEGNNLRN.js} +1 -1
  57. package/chunks/read-file-4TZCSTH7.js +3 -0
  58. package/chunks/ripGrep-MQNNJXAW.js +3 -0
  59. package/chunks/scheduler-4W7W3FPL.js +8 -0
  60. package/chunks/{send-message-K3T7GVHO.js → send-message-GFPVOTSZ.js} +1 -1
  61. package/chunks/{serve-C7WLVE45.js → serve-46RPFORU.js} +31 -31
  62. package/chunks/shell-VTOAVULB.js +3 -0
  63. package/chunks/{skill-D77VBROC.js → skill-FH6R4ZTW.js} +1 -1
  64. package/chunks/src-DBI2FFHO.js +3 -0
  65. package/chunks/{symbol-search-3A66G4MP.js → symbol-search-ZV6W6DPK.js} +1 -1
  66. package/chunks/{syntheticOutput-LLA4WQR7.js → syntheticOutput-XKGS6F2D.js} +1 -1
  67. package/chunks/task-create-T43QIG2F.js +3 -0
  68. package/chunks/{task-list-6I64SK7E.js → task-list-V27WHHHJ.js} +1 -1
  69. package/chunks/{task-stop-UKRXMCZV.js → task-stop-NON26GAN.js} +1 -1
  70. package/chunks/{task-update-XZWORLJB.js → task-update-DE7CUGPY.js} +1 -1
  71. package/chunks/{team-create-6SK4CNZ5.js → team-create-3NMISCGY.js} +1 -1
  72. package/chunks/{team-delete-DEPXAMUE.js → team-delete-LIEVUGIX.js} +1 -1
  73. package/chunks/{todoWrite-DKJAYA4S.js → todoWrite-YIMKFWIL.js} +1 -1
  74. package/chunks/{tool-search-7D46IF5G.js → tool-search-HFOHXFK5.js} +1 -1
  75. package/chunks/{update-goal-EUJYH23K.js → update-goal-2ZJ53Q3T.js} +1 -1
  76. package/chunks/{web-fetch-UGTFUOQN.js → web-fetch-EVO7GDEB.js} +1 -1
  77. package/chunks/{web-search-FURCBRRK.js → web-search-SJMJGGPE.js} +1 -1
  78. package/chunks/{workflow-DG73Y76U.js → workflow-JD3LGT4M.js} +2 -2
  79. package/chunks/write-file-UUWQNGF2.js +15 -0
  80. package/cli.js +353 -353
  81. package/package.json +2 -2
  82. package/chunks/agent-U4F2PPZK.js +0 -3
  83. package/chunks/agent-headless-HVLXIG5E.js +0 -3
  84. package/chunks/chunk-QWBNNEV2.js +0 -14
  85. package/chunks/contextCommand-B6PO2N2B.js +0 -3
  86. package/chunks/glob-JHSJXAWH.js +0 -22
  87. package/chunks/matildaAgentContentGenerator-TUOJCDZF.js +0 -32
  88. package/chunks/matildaContentGenerator-K32UBTHC.js +0 -8
  89. package/chunks/monitor-LW5DPUYE.js +0 -32
  90. package/chunks/notebook-edit-XQHVR3VY.js +0 -17
  91. package/chunks/read-file-URGJTANM.js +0 -3
  92. package/chunks/ripGrep-WLBUDFPP.js +0 -3
  93. package/chunks/scheduler-KIVES2O5.js +0 -8
  94. package/chunks/shell-FC3JNLXK.js +0 -3
  95. package/chunks/src-JTFAM72X.js +0 -3
  96. package/chunks/task-create-ZZTSVXZN.js +0 -3
  97. package/chunks/write-file-NQP7YPXV.js +0 -15
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Y as cu}from"./chunk-QWBNNEV2.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 qr=class{};U._CodeOrName=qr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var jt=class extends qr{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 qr{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=[Cr(t[0])],n=0;for(;n<e.length;)r.push(ao),io(r,e[n]),r.push(ao,Cr(t[++n]));return Xm(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(Zm(e))}U.addCodeArg=io;function Xm(t){let e=1;for(;e<t.length-1;){if(t[e]===ao){let r=Ym(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Ym(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 Qm(t,e){return e.emptyStr()?t:t.emptyStr()?e:du`${t}${e}`}U.strConcat=Qm;function Zm(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Cr(Array.isArray(t)?t.join(","):t)}function eh(t){return new Re(Cr(t))}U.stringify=eh;function Cr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Cr;function th(t){return typeof t=="string"&&U.IDENTIFIER.test(t)?new Re(`.${t}`):lu`[${t}]`}U.getProperty=th;function rh(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=rh;function nh(t){return new Re(t.toString())}U.regexpCode=nh});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 sh=(0,ge._)`\n`,uo=class extends Ln{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sh: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)||(oh(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qt(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&&qt(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 qt(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 qt(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&&qt(e,this.catch.names),this.finally&&qt(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{Z as cu}from"./chunk-5QAKUC2D.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 qr=class{};U._CodeOrName=qr;U.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var jt=class extends qr{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 qr{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=[Cr(t[0])],n=0;for(;n<e.length;)r.push(ao),io(r,e[n]),r.push(ao,Cr(t[++n]));return Xm(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(Zm(e))}U.addCodeArg=io;function Xm(t){let e=1;for(;e<t.length-1;){if(t[e]===ao){let r=Ym(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Ym(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 Qm(t,e){return e.emptyStr()?t:t.emptyStr()?e:du`${t}${e}`}U.strConcat=Qm;function Zm(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Cr(Array.isArray(t)?t.join(","):t)}function eh(t){return new Re(Cr(t))}U.stringify=eh;function Cr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}U.safeStringify=Cr;function th(t){return typeof t=="string"&&U.IDENTIFIER.test(t)?new Re(`.${t}`):lu`[${t}]`}U.getProperty=th;function rh(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=rh;function nh(t){return new Re(t.toString())}U.regexpCode=nh});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 sh=(0,ge._)`\n`,uo=class extends Ln{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?sh: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)||(oh(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qt(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&&qt(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 qt(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 qt(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&&qt(e,this.catch.names),this.finally&&qt(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 qt(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?qt(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 oh(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 ah=pu(I.operators.AND);function ih(...t){return t.reduce(ah)}I.and=ih;var ch=pu(I.operators.OR);function uh(...t){return t.reduce(ch)}I.or=uh;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(C=>{"use strict";f();Object.defineProperty(C,"__esModule",{value:!0});C.checkStrictMode=C.getErrorPath=C.Type=C.useFunc=C.setEvaluated=C.evaluatedPropsToName=C.mergeEvaluated=C.eachItem=C.unescapeJsonPointer=C.escapeJsonPointer=C.escapeFragment=C.unescapeFragment=C.schemaRefOrVal=C.schemaHasRulesButRef=C.schemaHasRules=C.checkUnknownRules=C.alwaysValidSchema=C.toHash=void 0;var W=O(),lh=Dr();function dh(t){let e={};for(let r of t)e[r]=!0;return e}C.toHash=dh;function fh(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(yu(t,e),!_u(e,t.self.RULES.all))}C.alwaysValidSchema=fh;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}"`)}C.checkUnknownRules=yu;function _u(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}C.schemaHasRules=_u;function ph(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}C.schemaHasRulesButRef=ph;function mh({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)}`}C.schemaRefOrVal=mh;function hh(t){return gu(decodeURIComponent(t))}C.unescapeFragment=hh;function yh(t){return encodeURIComponent(Po(t))}C.escapeFragment=yh;function Po(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}C.escapeJsonPointer=Po;function gu(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}C.unescapeJsonPointer=gu;function _h(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}C.eachItem=_h;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}}C.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}C.evaluatedPropsToName=$u;function To(t,e,r){Object.keys(r).forEach(n=>t.assign((0,W._)`${e}${(0,W.getProperty)(n)}`,!0))}C.setEvaluated=To;var hu={};function gh(t,e){return t.scopeValue("func",{ref:e,code:hu[e.code]||(hu[e.code]=new lh._Code(e.code))})}C.useFunc=gh;var So;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(So||(C.Type=So={}));function $h(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)}C.getErrorPath=$h;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)}}C.checkStrictMode=vu});var Oe=g(ko=>{"use strict";f();Object.defineProperty(ko,"__esModule",{value:!0});var ce=O(),vh={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=vh});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 wh(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=wh;function bh(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=bh;function Eh(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=Eh;function Sh({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=Sh;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 Ct={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._)`{}`:Ph(t,e,r)}function Ph(t,e,r={}){let{gen:n,it:s}=t,o=[Th(s,r),kh(t,r)];return Rh(t,e,o),n.object(...o)}function Th({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 kh({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)}`),[Ct.schemaPath,s]}function Rh(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([Ct.keyword,s],[Ct.params,typeof e=="function"?e(t):e||(0,z._)`{}`]),c.messages&&n.push([Ct.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Ct.schema,a],[Ct.parentSchema,(0,z._)`${u}${l}`],[me.default.data,o]),d&&n.push([Ct.propertyName,d])}});var Pu=g(er=>{"use strict";f();Object.defineProperty(er,"__esModule",{value:!0});er.boolOrEmptySchema=er.topBoolOrEmptySchema=void 0;var Oh=Ur(),Nh=O(),jh=Oe(),Ah={message:"boolean schema is false"};function Ih(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Su(t,!1):typeof r=="object"&&r.$async===!0?e.return(jh.default.data):(e.assign((0,Nh._)`${n}.errors`,null),e.return(!0))}er.topBoolOrEmptySchema=Ih;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,Oh.reportError)(s,Ah,void 0,e)}});var Ro=g(tr=>{"use strict";f();Object.defineProperty(tr,"__esModule",{value:!0});tr.getRules=tr.isJSONType=void 0;var Ch=["string","number","integer","boolean","null","object","array"],Dh=new Set(Ch);function Mh(t){return typeof t=="string"&&Dh.has(t)}tr.isJSONType=Mh;function Vh(){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=Vh});var Oo=g(pt=>{"use strict";f();Object.defineProperty(pt,"__esModule",{value:!0});pt.shouldUseRule=pt.shouldUseGroup=pt.schemaHasRulesForType=void 0;function xh({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Tu(t,n)}pt.schemaHasRulesForType=xh;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 zh=Ro(),Lh=Oo(),Uh=Ur(),N=O(),Ru=M(),rr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(rr||(le.DataType=rr={}));function Fh(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=Fh;function Ou(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zh.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}le.getJSONTypes=Ou;function Kh(t,e){let{gen:r,data:n,opts:s}=t,o=Gh(e,s.coerceTypes),a=e.length>0&&!(o.length===0&&e.length===1&&(0,Lh.schemaHasRulesForType)(t,e[0]));if(a){let i=jo(e,n,s.strictNumbers,rr.Wrong);r.if(i,()=>{o.length?Hh(t,e,o):Ao(t)})}return a}le.coerceAndCheckDataType=Kh;var Nu=new Set(["string","number","integer","boolean","null"]);function Gh(t,e){return e?t.filter(r=>Nu.has(r)||e==="array"&&r==="array"):[]}function Hh(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),Wh(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"
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{f}from"./chunk-R3H6IWFK.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-5U3A6KMU.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
3
+ import{f}from"./chunk-UHDKX2CR.js";import{f as u}from"./chunk-QKYGQLWC.js";import{g as m,i as c,p as l,q as p}from"./chunk-BGZJUBRA.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();var o=2e3;function T(e){return e.length<=o?e:`${e.slice(0,o)}
4
4
  \u2026 (${e.length-o} more characters)`}var s=class extends m{constructor(t,r){super(r);this.config=t}getDescription(){return`Create task: ${this.params.subject}`}async getDefaultPermission(){return"ask"}getConfirmationDetails(t){let r={type:"info",title:"Confirm TaskCreate",prompt:`Create task: ${this.params.subject}
5
5
 
6
6
  `+T(this.params.description),onConfirm:async()=>{}};return Promise.resolve(r)}async execute(){let t=u(this.config.getTeamContext()?.teamName);if(!t){let a="No active team. Create a team first.";return{llmContent:a,returnDisplay:a,error:{message:a}}}let r=await f(t,{subject:this.params.subject,description:this.params.description,activeForm:this.params.activeForm,metadata:this.params.metadata}),i=`Task #${r.id} created: "${r.subject}"`;return{llmContent:i,returnDisplay:i}}},d=class e extends c{constructor(t){super(e.Name,p.TASK_CREATE,"Create a new task in the team task list. Tasks are automatically assigned to idle teammates.","other",{type:"object",properties:{subject:{type:"string",description:"Short title for the task.",maxLength:200},description:{type:"string",description:"Detailed description of the task.",maxLength:1e4},activeForm:{type:"string",maxLength:200,description:'Present tense label for UI (e.g., "Running tests").'},metadata:{type:"object",description:"Optional arbitrary metadata."}},required:["subject","description"],additionalProperties:!1});this.config=t}static Name=l.TASK_CREATE;createInvocation(t){return new s(this.config,t)}toAutoClassifierInput(t){return{subject:t.subject,description:t.description}}};export{T as a,d as b};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as c}from"./chunk-4F4DA5UI.js";import{k as i}from"./chunk-SDTWBD62.js";import{e as l}from"./chunk-5U3A6KMU.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function C(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
3
+ import{a as c}from"./chunk-4F4DA5UI.js";import{k as i}from"./chunk-SDTWBD62.js";import{e as l}from"./chunk-BGZJUBRA.js";import{b as m}from"./chunk-GZPNIYVZ.js";m();import{readFile as y}from"node:fs/promises";function S(t){return t?`side-query:${t}`:"side-query"}function T(t,e){return e??t.getFastModel?.()??t.getModel()??c}function x(t){let e=t?.thinkingConfig;return{...t??{},thinkingConfig:e?{includeThoughts:!1,...e}:{includeThoughts:!1}}}async function C(t){let e=t.getOutputLanguageFilePath?.();if(e)try{let n=(await y(e,"utf8")).trim();return n?["Follow the user-visible output language preference below for this side query.",n].join(`
4
4
 
5
5
  `):void 0}catch{return}}function h(t,e){return e?t===void 0?e:typeof t=="string"?`${t}
6
6
 
@@ -1,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{b as g}from"./chunk-TISQNFB5.js";import{c as p}from"./chunk-IOCF4XSR.js";import{D as f,L as d,Y as m}from"./chunk-QWBNNEV2.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=m("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new g,h.set(e,t)),t}function c(e){return s.join(d.getGlobalTempDir(),f(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await p(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
3
+ import{b as g}from"./chunk-TISQNFB5.js";import{c as p}from"./chunk-SWEYYDZO.js";import{E as f,M as d,Z as m}from"./chunk-5QAKUC2D.js";import{b as u}from"./chunk-GZPNIYVZ.js";u();import*as a from"node:fs/promises";import*as s from"node:path";var x=m("CRON_TASKS_FILE"),T="scheduled_tasks.json",L=`~/.matilda/tmp/<project-hash>/${T}`,E=15,w=2e3,b=3e3,P=0,h=new Map;function C(e){let t=h.get(e);return t||(t=new g,h.set(e,t)),t}function c(e){return s.join(d.getGlobalTempDir(),f(e),T)}async function k(e){let t=c(e),i;try{i=await a.readFile(t,"utf-8")}catch(o){if(o.code==="ENOENT")return[];throw o}let r;try{r=JSON.parse(i)}catch{throw new Error(`Malformed JSON in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`)}if(!Array.isArray(r))throw new Error(`Expected a JSON array in ${t} \u2014 fix or delete the file; refusing to treat it as an empty schedule.`);let n=r.filter(A);return n.length!==r.length&&x.warn(`Dropped ${r.length-n.length} invalid task entr${r.length-n.length===1?"y":"ies"} from ${t}; a later write will persist without ${r.length-n.length===1?"it":"them"}.`),n}async function D(e,t){let i=c(e);await a.mkdir(s.dirname(i),{recursive:!0}),await p(i,t,{noFollow:!0})}async function _(e){let t=`${e}.lock`;await a.mkdir(s.dirname(t),{recursive:!0});let i=Date.now()+b;for(;;){if(Date.now()>i)throw new Error(`Timed out waiting for scheduled-tasks lock (${t})`);try{return await a.writeFile(t,String(process.pid),{flag:"wx"}),async()=>{await a.unlink(t).catch(()=>{})}}catch(r){if(r.code!=="EEXIST")throw r}try{let r=await a.stat(t);if(Date.now()-r.mtimeMs>w){let n=`${t}.stale.${process.pid}.${P++}`;try{await a.rename(t,n)}catch{continue}let o=await a.stat(n).catch(()=>null);o&&Date.now()-o.mtimeMs<=w&&await a.link(n,t).catch(()=>{}),await a.unlink(n).catch(()=>{});continue}}catch{continue}await new Promise(r=>setTimeout(r,E))}}async function y(e,t){let i=c(e);return C(i).runExclusive(async()=>{let r=await _(i);try{let n=await k(e),o=t(n);o!==n&&await D(e,o)}finally{await r()}})}async function F(e,t){await y(e,i=>[...i,t])}async function J(e,t){let i=new Set(t);if(!(await k(e)).some(o=>i.has(o.id)))return 0;let n=0;return await y(e,o=>{let l=o.filter(S=>!i.has(S.id));return n=o.length-l.length,n===0?o:l}),n}function A(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id=="string"&&typeof t.cron=="string"&&typeof t.prompt=="string"&&typeof t.recurring=="boolean"&&typeof t.createdAt=="number"&&(t.lastFiredAt===null||typeof t.lastFiredAt=="number")}export{L as a,c as b,k as c,y as d,F as e,J as f};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Mh as T}from"./chunk-3FI7EEYS.js";import{L as b}from"./chunk-QWBNNEV2.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
3
+ import{Nh as T}from"./chunk-6UGZQN4B.js";import{M as b}from"./chunk-5QAKUC2D.js";import{b as o}from"./chunk-GZPNIYVZ.js";import{b as w}from"./chunk-OWGSC52X.js";o();var B=e=>{process.stdout.write(e.endsWith(`
4
4
  `)?e:`${e}
5
5
  `)},m=e=>{process.stderr.write(e.endsWith(`
6
6
  `)?e:`${e}
@@ -0,0 +1,32 @@
1
+ // Force strict mode and setup for ESM
2
+ "use strict";
3
+ import{M as F,N as U,O as D,g as x,la as _}from"./chunk-JFE3NGGK.js";import{b as m,e as w}from"./chunk-4J6DC24J.js";import{k as O,n as I}from"./chunk-SDTWBD62.js";import{p as b,r as $}from"./chunk-5QAKUC2D.js";import{b as G}from"./chunk-GZPNIYVZ.js";G();var H="2026-06-23",J="auto",V="instant",X=12e4,h=18e4,K=5e4,R=16e3,S=class extends Error{code="EMATILDA_STREAM_INCOMPLETE";constructor(){super("Matilda agent stream ended without an authoritative done signal."),this.name="MatildaAgentStreamProtocolError"}},z=["Treat this as Matilda Code traffic.","Prefer the code specialist path for implementation, debugging, refactoring, tests, repo edits, and code review.","Use the fast instruct path for simple coordination, status, clarification, or non-code conversational replies.","Keep the response concise and action-oriented."].join(" "),Y=["You are powering Matilda Code, an interactive terminal coding agent.","Matilda Code owns the local agent loop: codebase reads, edits, shell commands, approvals, memory, subagents, skills, and MCP tools run through the CLI.","Use the conversation context and tool results as facts. Do not claim to have inspected files, run commands, or edited code unless that action appears in the provided context.",`When the user gives a vague starter such as "let's code" without a concrete development task, ask a concise clarifying question instead of inventing an app or dumping code.`].join(" ");function Q(n){let e=(n||"https://matilda.maincode.com/api/v1").trim().replace(/\/+$/,"");return/\/api\/v1$/i.test(e)?e.replace(/\/api\/v1$/i,"/api"):/\/api$/i.test(e)?e:`${e}/api`}function y(n){try{let e=JSON.parse(n);return e&&typeof e=="object"?e:void 0}catch{return}}var Z="Your message was blocked by our content safety system.";function q(n){let e=y(n);if(!e||e.error!=="content_blocked")return;let t=Array.isArray(e.categories)?e.categories.filter(o=>typeof o=="string"):[],s=typeof e.assistant_message=="string"&&e.assistant_message.trim().length>0?e.assistant_message:typeof e.message=="string"?e.message:Z;return{categories:t,severity:typeof e.severity=="string"?e.severity:void 0,assistantMessage:s}}function u(n,e){let s=y(n)?.[e];return typeof s=="string"?s:void 0}function L(n){return P(n)}function P(n){return typeof n=="string"?n:Array.isArray(n)?n.map(e=>{if(typeof e=="string")return e;if(!e||typeof e!="object")return"";let t=e;return typeof t.text=="string"?t.text:t.image_url?"[image omitted: Matilda native chat accepts text only]":t.input_audio?"[audio omitted: Matilda native chat accepts text only]":t.file?"[file omitted: Matilda native chat accepts text only]":""}).filter(Boolean).join(`
4
+ `):""}function f(n,e){if(n.length<=e)return n;let t=`
5
+ [...omitted to fit Matilda native agent context...]
6
+ `,s=e-t.length,o=Math.floor(s*.6),i=s-o;return`${n.slice(0,o)}${t}${n.slice(-i)}`}function ee(n){return(n.candidates?.[0]?.content?.parts??[]).map(t=>typeof t=="string"?t:"thought"in t&&t.thought?"":"text"in t&&t.text||"").join("")}function te(n){let e=y(n),t=typeof e?.output_tokens=="number"?e.output_tokens:void 0;if(t!==void 0)return{promptTokenCount:0,candidatesTokenCount:t,totalTokenCount:t,usageIsIncomplete:!0}}function C(n){return JSON.stringify(n).length}function ne(n){if(C(n)<=h)return n;let e=`
7
+ [...omitted to fit Matilda native request limit...]
8
+ `;for(let t=0;t<n.messages.length;t+=1){let s=n.messages[t];!s||s.content.length<=R||(n.messages[t]={...s,content:f(s.content,R)})}if(C(n)<=h)return n;for(;n.messages.length>2&&C(n)>h;){n.messages.splice(1,1);let t=n.messages[0];t&&!t.content.includes(e.trim())&&(n.messages[0]={...t,content:`${t.content}${e}`})}for(;C(n)>h;){let t=n.messages.length>1?n.messages.length-1:0,s=n.messages[t];if(!s||s.content.length<=1e3)break;let o=C(n)-h,i=Math.max(1e3,s.content.length-o-e.length-2e3);n.messages[t]={...s,content:f(s.content,i)}}return C(n)<=h||n.clientTools&&delete n.clientTools,n}function se(n){let e=y(n.data);if(!e)return;let t=typeof e.name=="string"?e.name:void 0;if(!t)return;let s=e.args&&typeof e.args=="object"?e.args:{};return{id:typeof e.id=="string"?e.id:void 0,name:t,args:s}}function oe(n){let e=y(n.data);if(n.event==="thinking"){let t=u(n.data,"content");return t?`**Thinking** ${t}`:void 0}if(n.event==="generation_status"){let t=u(n.data,"phase");return t?`**Planning** ${t}`:void 0}if(n.event==="status"){let t=u(n.data,"state");if(!t)return;let s=typeof e?.position=="number"?` position ${e.position}`:"";return`**Status** ${t}${s}`}if(n.event==="tool_start"){let t=u(n.data,"tool");if(!t)return;let s=u(n.data,"input")??(e?.args?JSON.stringify(e.args):void 0);return`**Remote tool** Starting ${t}${s?` with ${s}`:""}`}if(n.event==="tool_progress"){let t=u(n.data,"tool"),s=u(n.data,"message");return t&&s?`**Remote tool** ${t}: ${s}`:void 0}if(n.event==="tool_result"){let t=u(n.data,"tool"),s=u(n.data,"status"),o=u(n.data,"output")??u(n.data,"result");return t?`**Remote tool** ${t} ${s??"completed"}${o?`: ${f(o,600)}`:""}`:void 0}}function T(n,e,t){let s=new w;return s.candidates=[{content:{parts:n?[{text:n}]:[],role:"model"},index:0,safetyRatings:[]}],s.createTime=Date.now().toString(),s.modelVersion=e,t&&(s.usageMetadata=t),s}function ae(n,e){let t=new w;return t.candidates=[{content:{parts:n?[{text:n,thought:!0}]:[],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,t}function ie(n,e){let t=new w;return t.candidates=[{content:{parts:[{functionCall:n}],role:"model"},index:0,safetyRatings:[]}],t.createTime=Date.now().toString(),t.modelVersion=e,Object.defineProperty(t,"functionCalls",{value:[n],writable:!0,configurable:!0,enumerable:!0}),t}function j(n){let e=T("",n);return e.matildaReplace=!0,e}function re(n){return n.matildaReplace===!0}function W(n,e,t){let s=T("",n,t);return s.candidates=[{content:{parts:[],role:"model"},finishReason:e,index:0,safetyRatings:[]}],s}async function*le(n,e){let t=n.body?.getReader();if(!t)throw new Error("Matilda agent stream returned no response body");let s=new TextDecoder,o="",i="message",r=[],d=!1,c,a=()=>{e<=0||(c&&clearTimeout(c),c=setTimeout(()=>{d=!0,t.cancel().catch(()=>{})},e))},l=()=>{c&&(clearTimeout(c),c=void 0)},g=()=>{if(r.length===0){i="message";return}let A={event:i,data:r.join(`
9
+ `)};return i="message",r=[],a(),A};a();try{for(;;){let{done:M,value:p}=await t.read();if(M||d)break;a(),o+=s.decode(p,{stream:!0});let E=o.split(`
10
+ `);o=E.pop()??"";for(let k of E){let v=k.endsWith("\r")?k.slice(0,-1):k;if(v.length===0){let N=g();N&&(yield N)}else v.startsWith("event:")?i=v.slice(6).trim():v.startsWith("data:")&&r.push(v.slice(5).trimStart())}}if(o+=s.decode(),o.length>0)for(let M of o.split(`
11
+ `)){let p=M.endsWith("\r")?M.slice(0,-1):M;p.startsWith("event:")?i=p.slice(6).trim():p.startsWith("data:")&&r.push(p.slice(5).trimStart())}let A=g();A&&(yield A)}finally{l()}if(d)throw Object.assign(new Error(`No Matilda agent SSE events for ${e}ms`),{code:"ETIMEDOUT"})}var B=class{constructor(e,t){this.contentGeneratorConfig=e;this.cliConfig=t}async generateContent(e,t){let s=await this.generateContentStream(e,t),o="",i,r=m.STOP,d=!1;for await(let a of s){re(a)?o="":o+=ee(a),a.usageMetadata&&(i=a.usageMetadata);let l=a.candidates?.[0]?.finishReason;l&&(d=!0,r=l)}if(!d)throw new S;let c=T(o,this.modelFor(e),i);return c.candidates=[{content:{parts:o?[{text:o}]:[],role:"model"},index:0,safetyRatings:[]}],r&&(c.candidates[0].finishReason=r),c}async generateContentStream(e,t){return this.streamNativeChat(e)}async countTokens(e){return{totalTokens:Math.ceil(JSON.stringify(e.contents??"").length/4)}}async embedContent(e){throw new Error("Matilda agent SDK transport does not support embeddings.")}useSummarizedThinking(){return!1}async*streamNativeChat(e){let t=this.modelFor(e),s=await this.fetchNativeChat(e),o=!1,i=!1,r,d,c=!1;for await(let a of le(s,X))if(a.data!=="[DONE]"){if(a.event==="token"){let l=u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="thinking"||a.event==="generation_status"||a.event==="status"||a.event==="tool_start"||a.event==="tool_progress"||a.event==="tool_result"){let l=oe(a);l&&(i=!0,yield ae(l,t))}else if(a.event==="client_tool_call"){let l=se(a);l&&(i=!0,yield ie(l,t))}else if(a.event==="usage")d=te(a.data)??d;else if(a.event==="replace")yield j(t);else if(a.event==="safety_replace"){yield j(t);let l=u(a.data,"message")??u(a.data,"content");l&&(i=!0,yield T(l,t))}else if(a.event==="truncated")c=!0,r=m.MAX_TOKENS;else if(a.event==="done"){if(c=!0,r=u(a.data,"reason")==="max_tokens"?m.MAX_TOKENS:r??m.STOP,!i)throw new Error("Matilda agent returned an empty response.");yield W(t,r,d),o=!0}else if(a.event==="error"){let l=y(a.data),g=typeof l?.error=="string"?l.error:"Unknown Matilda agent stream error";throw new Error(`Matilda agent stream error: ${g}`)}}if(!o){if(e.config?.abortSignal?.aborted)return;if(!i)throw new Error("Matilda agent returned an empty response.");if(c)yield W(t,r??m.STOP,d);else throw new S}}async fetchNativeChat(e){let t=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()}),s=await this.postNativeChat(e,t);if(s.status!==401)return this.assertOkResponse(s);let o;try{o=await _({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:t,forceRefresh:!0,signal:e.config?.abortSignal,channel:this.cliConfig.getChannel?.()})}catch(r){throw new b(r instanceof Error?r.message:String(r))}if(!o||o===t)throw new b("Matilda session expired. Please sign in again.");let i=await O("retry",()=>this.postNativeChat(e,o));return this.assertOkResponse(i)}async postNativeChat(e,t){return fetch(`${Q(this.contentGeneratorConfig.baseUrl)}/chat`,{method:"POST",headers:this.buildHeaders(t),body:JSON.stringify(this.buildNativeRequest(e)),signal:e.config?.abortSignal})}async assertOkResponse(e){if(e.ok)return e;let t=await e.text();if(e.status===422){let o=q(t);if(o)throw new $(`Matilda agent request blocked (422): ${t}`,o.categories,o.severity,o.assistantMessage)}let s=`Matilda agent request failed (${e.status}): ${t}`;throw e.status===401?new b(s):new Error(s)}buildHeaders(e){let t={"Content-Type":"application/json",Accept:"text/event-stream","X-Matilda-API-Version":H,"X-Matilda-Client":"matilda-code","User-Agent":`MatildaCode/${this.cliConfig.getCliVersion?.()||"unknown"}`};for(let[s,o]of Object.entries(this.contentGeneratorConfig.customHeaders??{}))s.toLowerCase()!=="x-matilda-response-mode"&&!U(s)&&(t[s]=o);return D(this.contentGeneratorConfig,e)&&Object.assign(t,F(this.cliConfig),I()),e&&(t.Authorization=`Bearer ${e}`),t}buildNativeRequest(e){let t=this.inferPurpose(e),s=this.clientToolsFromRequest(e),o={messages:this.buildNativeMessages(e,t),responseMode:this.responseModeForPurpose(t)};return s.length>0&&(o.clientTools=s),ne(o)}buildNativeMessages(e,t){let s=this.openAIMessagesFromRequest(e),i=[{role:"user",content:this.buildSystemContext(e,t)}];for(let d of s){if(d.role==="system")continue;let c=this.nativeMessageFromOpenAIMessage(d);c&&i.push(c)}i.length===1&&i.push({role:"user",content:`${this.purposeLabel(t)}:
12
+ (empty prompt)`});let r=i[i.length-1];return r?.role!=="user"?i.push({role:"user",content:`${this.purposeLabel(t)}:
13
+ Continue from the previous assistant response.`}):r.content.startsWith(`${this.purposeLabel(t)}:
14
+ `)||(i[i.length-1]={...r,content:`${this.purposeLabel(t)}:
15
+ ${r.content}`}),i}buildSystemContext(e,t){let s=["Agent: Matilda Code",t==="code"?`Routing intent:
16
+ ${z}`:void 0,`Instructions:
17
+ ${this.instructionsFromRequest(e)}`].filter(o=>!!o);return f(s.join(`
18
+
19
+ `),K)}nativeMessageFromOpenAIMessage(e){let t=this.describeMessage(e);if(t.trim())return{role:e.role==="assistant"?"assistant":"user",content:t}}inferPurpose(e){if(this.contentGeneratorConfig.matildaAgentPurpose)return this.contentGeneratorConfig.matildaAgentPurpose;if(this.contentGeneratorConfig.matildaAgentResponseMode==="instant")return"general";if(this.contentGeneratorConfig.matildaAgentResponseMode==="deep")return"analysis";let s=(this.userMessagesFromRequest(e).at(-1)?.trim()??"").toLowerCase().replace(/\s+/g," ");return/^(hi|hey|hello|thanks|thank you|ok|okay|cool|nice|what'?s up)[.!?]*$/.test(s)||/^(ok|okay)?\s*(let'?s|lets)\s+(code|build|start|get started)[.!?]*$/.test(s)?"general":"code"}responseModeForPurpose(e){return this.contentGeneratorConfig.matildaAgentResponseMode?this.contentGeneratorConfig.matildaAgentResponseMode:e==="general"?V:e==="analysis"?"deep":J}purposeLabel(e){return e==="code"?"Code task":e==="analysis"?"Analysis task":"Task"}instructionsFromRequest(e){let t=this.openAIMessagesFromRequest(e).filter(s=>s.role==="system").map(s=>P(s.content)).filter(s=>s.trim().length>0);return[Y,...t,this.localAgentContext()].join(`
20
+
21
+ `)}localAgentContext(){let e=["Local agent context:","- CLI: Matilda Code terminal agent."],t=this.cliConfig.getModel?.();t&&e.push(`- Active model: ${t}`);let s=this.cliConfig.getApprovalMode?.();s&&e.push(`- Approval mode: ${s}`);let o=this.cliConfig.getSandbox?.();e.push(o?`- Sandbox: ${o.command} (${o.image}).`:"- Sandbox: disabled.");let i=[["allow",this.cliConfig.getPermissionsAllow?.()??[]],["ask",this.cliConfig.getPermissionsAsk?.()??[]],["deny",this.cliConfig.getPermissionsDeny?.()??[]]];for(let[l,g]of i)g.length>0&&e.push(`- Permission ${l} rules: ${g.join(", ")}`);let r=this.cliConfig.getIdeMode?.()?"IDE/ACP":this.cliConfig.isInteractive?.()?"interactive TUI":"headless";e.push(`- Interface mode: ${r}`);let d=this.cliConfig.getProjectRoot?.();d&&e.push(`- Project root: ${d}`);let c=this.cliConfig.getWorkingDir?.();c&&c!==d&&e.push(`- Working directory: ${c}`);let a=this.cliConfig.getToolRegistry?.()?.getAllToolNames?.().slice(0,30)??[];return a.length>0&&e.push(`- Local tools available through the CLI loop: ${a.join(", ")}`),e.join(`
22
+ `)}clientToolsFromRequest(e){let t=[];for(let s of e.config?.tools??[])"functionDeclarations"in s&&t.push(...(s.functionDeclarations??[]).filter(o=>!!o.name));return t.map(s=>({name:s.name,...s.description?{description:s.description}:{},...s.parametersJsonSchema?{parameters:s.parametersJsonSchema}:s.parameters?{parameters:s.parameters}:{}}))}userMessagesFromRequest(e){return this.openAIMessagesFromRequest(e).filter(t=>t.role==="user").map(t=>L(t.content)).filter(t=>t.trim().length>0)}openAIMessagesFromRequest(e){let t={model:this.modelFor(e),modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0};return x.convertGeminiRequestToOpenAI(e,t,{cleanOrphanToolCalls:!1})}describeMessage(e){if(e.role==="user")return`User:
23
+ ${f(L(e.content),R)}`;if(e.role==="assistant"){let t=P(e.content),s="tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.map(o=>`Tool request: ${o.function.name}(${o.function.arguments})`).join(`
24
+ `):"";return`Assistant:
25
+ ${f([t,s].filter(Boolean).join(`
26
+ `),R)}`}return e.role==="tool"?`Tool result ${e.tool_call_id}:
27
+ ${f(P(e.content),R)}`:""}modelFor(e){return e.model||this.contentGeneratorConfig.model}};export{re as a,B as b};
28
+ /**
29
+ * @license
30
+ * Copyright 2026 Matilda Team
31
+ * SPDX-License-Identifier: Apache-2.0
32
+ */
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d as on}from"./chunk-DC7LAFZZ.js";import{b as Wt,d as qt,g as yt,j as Yt,k as Jt,s as en,v as ue}from"./chunk-QLEJOI4X.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as Xt,d as Qt}from"./chunk-SDTWBD62.js";import{Bb as de,Jc as ht,Kc as Ct,Mb as ft,Mc as Tt,Pa as Co,Pb as gt,Ra as To,Rb as mt,Sa as X,Wa as xe,Xa as ke,Ya as Ie,a as _,ab as pt,eb as Oe,f as U,fb as V,na as ut,tb as we,ub as Pe}from"./chunk-6QP5C76Y.js";import{b as rn}from"./chunk-3YLXGE6T.js";import{L as ve,P as zt,R as dt,Y as O,c as Vt,d as ae,e as le,j as at}from"./chunk-QWBNNEV2.js";import{b as lt,c as v,f as ct,g as ce,h as M,i as be,k as jt,l as x,n as J}from"./chunk-FWDMPRKU.js";import{b as g}from"./chunk-GZPNIYVZ.js";import{f as ho}from"./chunk-OWGSC52X.js";g();function Q(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function De(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function yo(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+De(t)):(t.prompt||0)+De(t)}function Ao(t){let e=Math.max(0,t.thoughtsTokens||0),n=De({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}g();g();var So=/[A-Za-z\u00C0-\u024F]/g;function Eo(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function St(t){let e=t.codePointAt(0);return e!==void 0&&Eo(e)}function _o(t){let e=t.match(So)?.length??0;if(e<24)return!1;let n=0;for(let o of t)St(o)&&n++;return n===0||e>=n*8}function Le(t){if(!t||!_o(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!St(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&St(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}g();var Z=O("TAGGED_THINKING_PARSER"),fe=["<think>","<thinking>"],ge=["</think>","</thinking>"],Mo=Math.max(...fe.map(t=>t.length),...ge.map(t=>t.length));function pe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Ue(t,e,n){let o=t.length-e;return o<=0||o>Mo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Ne(t,e,n){return n.find(o=>t.startsWith(o,e))}function _t(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function sn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Le(_t(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var Et=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Ne(o,s,fe);if(a){Z.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Ne(o,s,ge);if(l){Z.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),pe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,fe)||Ue(o,s,ge)))break}else{let a=Ne(o,s,ge);if(a){Z.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Ne(o,s,fe);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,fe)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(pe(r,i,this.mode),this.buffer=this.buffer.slice(s),Z.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),sn(r)):(this.buffer="",this.mode==="thought"&&i&&Z.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),pe(r,i,this.mode),Z.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),sn(r))}};function an(t){return new Et().parse(t,!0)}var P=O("CONVERTER"),gn="(attached media from previous tool call)";function mn(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),r>n&&(n>0||o>0||p>0)&&(d=Math.max(d,r-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,f=r;return(f===0&&(m>0||d>0)||f>0&&m>0&&f<m+d)&&(f=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:f,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ro=64,ln=1024;function cn(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=ln&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Ro?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ln&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function hn(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(e)}async function vo(t,e="auto"){let n=[];for(let o of t){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=hn(i.parameters)),s&&(s=qt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function bo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),Io(t.contents,o,e),o=fn(o),n.cleanOrphanToolCalls&&(o=Ko(o),o=fn(o)),o}function xo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let f of o)typeof f=="string"?i.push(f):"text"in f&&f.text?"thought"in f&&f.thought?r.push(f.text):i.push(f.text):"functionCall"in f&&f.functionCall&&(s.push({id:f.functionCall.id||`call_${a}`,type:"function",function:{name:f.functionCall.name||"",arguments:JSON.stringify(f.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=Go(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=t.createTime?Number(t.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Tn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Io(t,e,n){if(Array.isArray(t))for(let o of t)dn(o,e,n);else t&&dn(t,e,n)}function dn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Do(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let h=Cn(d,n);if(h&&r==="user"&&i.push(h),"functionCall"in d&&d.functionCall&&r==="assistant"){let m=d.functionCall.id;if(m){if(c.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let m=d.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let f=wo(d.functionResponse,n);if(f){if(n.splitToolMedia&&Array.isArray(f.content)){let C=[],T=[];for(let y of f.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(S=>S.text).join(`
3
+ import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d as on}from"./chunk-DC7LAFZZ.js";import{b as Wt,d as qt,g as yt,j as Yt,k as Jt,s as en,v as ue}from"./chunk-O3OUYCSO.js";import{b as A,e as B}from"./chunk-4J6DC24J.js";import{a as Xt,d as Qt}from"./chunk-SDTWBD62.js";import{Bb as de,Jc as ht,Kc as Ct,Mb as ft,Mc as Tt,Pa as Co,Pb as gt,Ra as To,Rb as mt,Sa as X,Wa as xe,Xa as ke,Ya as Ie,a as _,ab as pt,eb as Oe,f as U,fb as V,na as ut,tb as we,ub as Pe}from"./chunk-OVC5Z3EX.js";import{b as rn}from"./chunk-3YLXGE6T.js";import{M as ve,Q as zt,S as dt,Z as O,c as Vt,d as ae,e as le,j as at}from"./chunk-5QAKUC2D.js";import{b as lt,c as v,f as ct,g as ce,h as M,i as be,k as jt,l as x,n as J}from"./chunk-FWDMPRKU.js";import{b as g}from"./chunk-GZPNIYVZ.js";import{f as ho}from"./chunk-OWGSC52X.js";g();function Q(t){return!Number.isFinite(t)||t<=0?0:Math.ceil(t/4)}function De(t){let e=t.candidates||0,n=t.thoughts||0;return n>e?e+n:Math.max(e,n)}function yo(t){return t.total&&t.total>0?Math.max(t.total,(t.prompt||0)+De(t)):(t.prompt||0)+De(t)}function Ao(t){let e=Math.max(0,t.thoughtsTokens||0),n=De({candidates:t.outputTokens||0,thoughts:e}),o=Math.max(t.totalTokens||0,(t.inputTokens||0)+n);return{...t,outputTokens:n,thoughtsTokens:e,totalTokens:o}}g();g();var So=/[A-Za-z\u00C0-\u024F]/g;function Eo(t){return t>=1024&&t<=1279||t>=1280&&t<=1327||t>=11744&&t<=11775||t>=42560&&t<=42655||t>=12352&&t<=12543||t>=13312&&t<=19903||t>=19968&&t<=40959||t>=63744&&t<=64255||t>=44032&&t<=55215}function St(t){let e=t.codePointAt(0);return e!==void 0&&Eo(e)}function _o(t){let e=t.match(So)?.length??0;if(e<24)return!1;let n=0;for(let o of t)St(o)&&n++;return n===0||e>=n*8}function Le(t){if(!t||!_o(t))return t;let e="",n=0,o=[...t];for(;n<o.length;){if(!St(o[n])){e+=o[n],n++;continue}let r=n;for(;r>0&&o[r-1]===" ";)r--;let i=n+1;for(;i<o.length&&St(o[i]);)i++;for(;i<o.length&&o[i]===" ";)i++;let s=r>0?o[r-1]:"",a=i<o.length?o[i]:"";(/[A-Za-z0-9]/.test(s)&&/[A-Za-z0-9]/.test(a)||o[r]===" "||o[i-1]===" ")&&(e+=" "),n=i,r<n&&o[r]===" "&&e.endsWith(" ")&&(e=e.slice(0,-1))}return e.replace(/ {2,}/g," ")}g();var Z=O("TAGGED_THINKING_PARSER"),fe=["<think>","<thinking>"],ge=["</think>","</thinking>"],Mo=Math.max(...fe.map(t=>t.length),...ge.map(t=>t.length));function pe(t,e,n){e&&t.push(n==="thought"?{text:e,thought:!0}:{text:e})}function Ue(t,e,n){let o=t.length-e;return o<=0||o>Mo?!1:n.some(r=>r.startsWith(t.slice(e,e+o)))}function Ne(t,e,n){return n.find(o=>t.startsWith(o,e))}function _t(t){if(!t)return t;let e=t;return e=e.replace(/<\/?think(?:ing)?>/gi,""),e=e.replace(/[A-Za-z]*long[_-]?message[_-]?THINKING/gi,""),e=e.replace(/\bM?long[_-]?message\b/gi,""),e=e.replace(/(^|[\s>])THINKING(?=[\sA-Z<]|$)/g,"$1"),e!==t&&(e=e.replace(/[ \t]{2,}/g," ")),e}function sn(t){let e=[];for(let n of t){if(n.thought===!0||typeof n.text!="string"){e.push(n);continue}let o=Le(_t(n.text));(o.length>0||/^\s+$/.test(n.text))&&e.push({text:o.length>0?o:n.text})}return e}var Et=class{mode="text";buffer="";parse(e,n=!1){this.buffer+=e;let o=this.buffer.toLowerCase(),r=[],i="",s=0;for(;s<this.buffer.length;){if(this.mode==="text"){let a=Ne(o,s,fe);if(a){Z.debug(`taggedThinking: detected open tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="thought",s+=a.length;continue}let l=Ne(o,s,ge);if(l){Z.debug(`taggedThinking: dropping orphan close tag "${l}" at offset ${s}`),pe(r,i,this.mode),i="",s+=l.length;continue}if(!n&&(Ue(o,s,fe)||Ue(o,s,ge)))break}else{let a=Ne(o,s,ge);if(a){Z.debug(`taggedThinking: detected close tag "${a}" at offset ${s}`),pe(r,i,this.mode),i="",this.mode="text",s+=a.length;continue}let l=Ne(o,s,fe);if(l){s+=l.length;continue}if(!n&&(Ue(o,s,ge)||Ue(o,s,fe)))break}i+=this.buffer[s],s+=1}return s<this.buffer.length?(pe(r,i,this.mode),this.buffer=this.buffer.slice(s),Z.debug(`taggedThinking: emitted ${r.length} part(s), buffered ${this.buffer.length} char(s)`),sn(r)):(this.buffer="",this.mode==="thought"&&i&&Z.warn(`taggedThinking: flushing ${i.length} chars of unclosed thought on stream end`),pe(r,i,this.mode),Z.debug(`taggedThinking: emitted ${r.length} part(s), flush complete`),sn(r))}};function an(t){return new Et().parse(t,!0)}var P=O("CONVERTER"),gn="(attached media from previous tool call)";function mn(t,e={}){let n=t.prompt_tokens||0,o=t.completion_tokens||0,r=t.total_tokens||0,i=t.prompt_tokens_details,s=i?.cached_tokens??i?.cachedTokens??t.cached_tokens??t.prompt_cache_hit_tokens??t.cache_read_input_tokens??0,a=t.completion_tokens_details,l=a?.reasoning_tokens??a?.reasoningTokens??t.reasoning_tokens??0,c=Math.max(0,e.estimatedReasoningTokens??0),u=Math.max(0,e.estimatedContentTokens??0),p=l>0?l:c,d=o;p>0&&(o>=p?d=o:d=o+p),(u>0||c>0)&&(d=Math.max(d,u+(l>0?0:c),u+p)),r>n&&(n>0||o>0||p>0)&&(d=Math.max(d,r-n)),p===0&&c>0&&(p=c),p>d&&(p=d);let h=t.usage_is_incomplete===!0||o>0&&n===0||r>0&&n===0&&o===0,m=n,f=r;return(f===0&&(m>0||d>0)||f>0&&m>0&&f<m+d)&&(f=m+d),{promptTokenCount:m,candidatesTokenCount:d,totalTokenCount:f,cachedContentTokenCount:s,thoughtsTokenCount:p,...h?{usageIsIncomplete:!0}:{}}}var Ro=64,ln=1024;function cn(t,e){if(t.length===0)return"";if(e.emittedText.length===0)return e.emittedText=t,e.emittedLength=t.length,t;if(e.cumulativeMode){if(t.startsWith(e.emittedText)){let n=t.slice(e.emittedText.length);return e.emittedText=t,e.emittedLength=t.length,n}return e.emittedText.startsWith(t)?(P.debug(`normalizeStreamingTextDelta: cumulative rewind suppression (emitted=${e.emittedText.length}b, chunk=${t.length}b)`),""):(P.debug("normalizeStreamingTextDelta: exiting cumulative mode (chunk does not match prior accumulated text)"),e.cumulativeMode=!1,e.emittedText=t,e.emittedLength+=t.length,t)}if(t.length>e.emittedText.length&&t.startsWith(e.emittedText)){let n=e.emittedText.length,r=n>=ln&&e.emittedLength>n?e.emittedLength:n;if(t.length>r){let i=t.slice(r);return e.emittedText=t,e.emittedLength=t.length,e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (prefix overlap, baseline=${n}b sliceFrom=${r}b -> curr=${t.length}b)`),i}}return t===e.emittedText?t.length>=Ro?(e.cumulativeMode=!0,P.debug(`normalizeStreamingTextDelta: entered cumulative mode (exact repeat, ${t.length}b)`),""):(e.emittedLength+=t.length,t):(e.emittedText.length<ln&&(e.emittedText+=t),e.emittedLength+=t.length,t)}function hn(t){if(!t||typeof t!="object")return t;let e=JSON.parse(JSON.stringify(t)),n=o=>{if(typeof o!="object"||o===null)return o;if(Array.isArray(o))return o.map(n);let r={};for(let[i,s]of Object.entries(o))if(i==="type"&&typeof s=="string"){let a=s.toLowerCase();a==="integer"?r[i]="integer":a==="number"?r[i]="number":r[i]=a}else i==="minimum"||i==="maximum"||i==="multipleOf"?typeof s=="string"&&!isNaN(Number(s))?r[i]=Number(s):r[i]=s:i==="minLength"||i==="maxLength"||i==="minItems"||i==="maxItems"?typeof s=="string"&&!isNaN(Number(s))?r[i]=parseInt(s,10):r[i]=s:typeof s=="object"?r[i]=n(s):r[i]=s;return r};return n(e)}async function vo(t,e="auto"){let n=[];for(let o of t){let r;if("tool"in o?r=await o.tool():r=o,r.functionDeclarations){for(let i of r.functionDeclarations)if(i.name&&i.description){let s;i.parametersJsonSchema?s={...i.parametersJsonSchema}:i.parameters&&(s=hn(i.parameters)),s&&(s=qt(s,e)),n.push({type:"function",function:{name:i.name,description:i.description,parameters:s}})}}}return n}function bo(t,e,n={cleanOrphanToolCalls:!0}){let o=[];return ko(t,o),Io(t.contents,o,e),o=fn(o),n.cleanOrphanToolCalls&&(o=Ko(o),o=fn(o)),o}function xo(t,e){let n=t.candidates?.[0],o=n?.content?.parts||[],r=[],i=[],s=[],a=0;for(let f of o)typeof f=="string"?i.push(f):"text"in f&&f.text?"thought"in f&&f.thought?r.push(f.text):i.push(f.text):"functionCall"in f&&f.functionCall&&(s.push({id:f.functionCall.id||`call_${a}`,type:"function",function:{name:f.functionCall.name||"",arguments:JSON.stringify(f.functionCall.args||{})}}),a+=1);let l={role:"assistant",content:i.join("")||null,refusal:null},c=r.join("");c&&(l.reasoning_content=c),s.length>0&&(l.tool_calls=s);let u=Go(n?.finishReason),p=t.usageMetadata,d={prompt_tokens:p?.promptTokenCount||0,completion_tokens:p?.candidatesTokenCount||0,total_tokens:p?.totalTokenCount||0};p?.cachedContentTokenCount!==void 0&&(d.prompt_tokens_details={cached_tokens:p.cachedContentTokenCount});let h=t.createTime?Number(t.createTime):Date.now(),m=Number.isFinite(h)?Math.floor(h/1e3):Math.floor(Date.now()/1e3);return{id:t.responseId||`gemini-${Date.now()}`,object:"chat.completion",created:m,model:t.modelVersion||e.model,choices:[{index:0,message:l,finish_reason:u,logprobs:null}],usage:d}}function ko(t,e){if(!t.config?.systemInstruction)return;let n=Tn(t.config.systemInstruction);n&&e.push({role:"system",content:n})}function Io(t,e,n){if(Array.isArray(t))for(let o of t)dn(o,e,n);else t&&dn(t,e,n)}function dn(t,e,n){if(typeof t=="string"){e.push({role:"user",content:t});return}if(!Do(t))return;let o=t.parts||[],r=t.role==="model"?"assistant":"user",i=[],s=[],a=[],l=0,c=new Set,u=new Set,p=[];for(let d of o){if(typeof d=="string"){i.push({type:"text",text:d});continue}"text"in d&&"thought"in d&&d.thought&&r==="assistant"&&d.text&&s.push(d.text),"text"in d&&d.text&&!("thought"in d&&d.thought)&&i.push({type:"text",text:d.text});let h=Cn(d,n);if(h&&r==="user"&&i.push(h),"functionCall"in d&&d.functionCall&&r==="assistant"){let m=d.functionCall.id;if(m){if(c.has(m)){P.debug(`Dropping duplicate functionCall id=${m} while converting content`);continue}c.add(m)}a.push({id:m||`call_${l}`,type:"function",function:{name:d.functionCall.name||"",arguments:JSON.stringify(d.functionCall.args||{})}}),l+=1}if(d.functionResponse&&r==="user"){let m=d.functionResponse.id;if(m){if(u.has(m))continue;u.add(m)}let f=wo(d.functionResponse,n);if(f){if(n.splitToolMedia&&Array.isArray(f.content)){let C=[],T=[];for(let y of f.content)y&&(y.type==="image_url"||y.type==="input_audio"||y.type==="video_url"||y.type==="file")?C.push(y):y&&y.type==="text"&&T.push(y);if(C.length>0){let y=T.map(S=>S.text).join(`
4
4
  `);f.content=y||"[media attached in following user message]",p.push(...C)}}e.push(f)}}}if(p.length>0&&e.push({role:"user",content:[{type:"text",text:gn},...p]}),r==="assistant"){if(i.length===0&&a.length===0&&s.length===0)return;let h={role:"assistant",content:i.filter(f=>f.type==="text").map(f=>f.text).join("")||(s.length>0?"":null)};a.length>0&&(h.tool_calls=a);let m=s.join("");m&&(h.reasoning_content=m),e.push(h);return}i.length>0&&e.push({role:"user",content:i})}function Oo(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof t=="object"){let e=t,n=e.output;if(typeof n=="string")return n;let o=e.error;if(typeof o=="string")return o}try{return JSON.stringify(t)??String(t)}catch{return String(t)}}function wo(t,e){let n=Oo(t.response),o=[];n&&o.push({type:"text",text:n});for(let r of t.parts||[]){if("text"in r&&typeof r.text=="string"){r.text.length>0&&o.push({type:"text",text:r.text});continue}let i=Cn(r,e);i&&o.push(i)}return o.length===0?{role:"tool",tool_call_id:t.id||"",content:""}:{role:"tool",tool_call_id:t.id||"",content:o}}function Cn(t,e){let{modalities:n}=e;if(t.inlineData?.mimeType&&t.inlineData?.data){let o=t.inlineData.mimeType,r=un(o),i=t.inlineData.displayName||o;if(r==="image")return n.image?{type:"image_url",image_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("image",i,e);if(o==="application/pdf")return n.pdf?{type:"file",file:{filename:t.inlineData.displayName||"document.pdf",file_data:`data:${o};base64,${t.inlineData.data}`}}:z("pdf",i,e);if(r==="audio"){if(!n.audio)return z("audio",i,e);let s=Po(o);if(s)return{type:"input_audio",input_audio:{data:`data:${o};base64,${t.inlineData.data}`,format:s}}}return r==="video"?n.video?{type:"video_url",video_url:{url:`data:${o};base64,${t.inlineData.data}`}}:z("video",i,e):{type:"text",text:`Unsupported inline media type: ${o} (${i}).`}}if(t.fileData?.mimeType&&t.fileData?.fileUri){let o=t.fileData.displayName||"file",r=t.fileData.fileUri,i=t.fileData.mimeType,s=un(i);if(s==="image")return n.image?{type:"image_url",image_url:{url:r}}:z("image",o,e);if(i==="application/pdf")return n.pdf?{type:"file",file:{filename:o,file_data:r}}:z("pdf",o,e);if(s==="video")return n.video?{type:"video_url",video_url:{url:r}}:z("video",o,e);let a=t.fileData.displayName?` (${t.fileData.displayName})`:"";return{type:"text",text:`Unsupported file media type: ${i}${a}.`}}return null}function z(t,e,n){P.warn(`Model '${n.model}' does not support ${t} input. Replacing with text placeholder: ${e}`);let o;return t==="pdf"?o=`This model does not support PDF input directly. The read_file tool cannot extract PDF content either. To extract text from the PDF file, try using skills if applicable, or guide user to install pdf skill by running this slash command:
5
5
  /extensions install https://github.com/anthropics/skills:document-skills`:o=`This model does not support ${t} input. The read_file tool cannot process this type of file either. To handle this file, try using skills if applicable, or any tools installed at system wide, or let the user know you cannot process this type of file.`,{type:"text",text:`[Unsupported ${t} file: "${e}". ${o}]`}}function un(t){return t.startsWith("image/")?"image":t.startsWith("audio/")?"audio":t.startsWith("video/")?"video":"file"}function Po(t){return t.includes("wav")?"wav":t.includes("mp3")||t.includes("mpeg")?"mp3":null}function Do(t){return typeof t=="object"&&t!==null&&"role"in t&&"parts"in t&&Array.isArray(t.parts)}function Tn(t){return typeof t=="string"?t:Array.isArray(t)?t.map(e=>Tn(e)).filter(Boolean).join(`
6
6
  `):typeof t=="object"&&t!==null&&"parts"in t&&t.parts?.map(n=>typeof n=="string"?n:"text"in n&&n.text||"").filter(Boolean).join(`
@@ -8,7 +8,7 @@ import{a as j,d as Zt}from"./chunk-4F4DA5UI.js";import{a as tn,b as At,c as nn,d
8
8
  ${n}`:n;return{...o,text:a}}return e}};g();function Hn(t){switch(t){case"openai":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}function Bn(t){switch(t){case"openai":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}var F=class extends Error{constructor(e){super(e),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},je=class extends F{code="STRICT_MISSING_CREDENTIALS";constructor(e,n,o){let r=e||"(unknown)",i=n||"(unknown)";super(`Missing credentials for modelProviders model '${i}'. `+(o?`Current configured envKey: '${o}'. Set that environment variable, or update modelProviders.${r}[].envKey.`:`Configure modelProviders.${r}[].envKey and set that environment variable.`))}},ze=class extends F{code="STRICT_MISSING_MODEL_ID";constructor(e){super(`Missing model id for strict modelProviders resolution (authType: ${e}).`)}},We=class extends F{code="MISSING_API_KEY";constructor(e){super(`Missing API key for ${e.authType} auth. Current model: '${e.model||"(unknown)"}', baseUrl: '${e.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${e.envKey}'.`)}},qe=class extends F{code="MISSING_MODEL";constructor(e){super(`Missing model for ${e.authType} auth. Set the environment variable '${e.envKey}'.`)}},Ye=class extends F{code="MISSING_BASE_URL";constructor(e){super(`Missing baseUrl for modelProviders model '${e.model||"(unknown)"}'. Configure modelProviders.${e.authType||"(unknown)"}[].baseUrl.`)}},Je=class extends F{code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};g();import Kr from"node:process";g();var Vn={image:!0,pdf:!0,audio:!0,video:!0},Fr=[[/^gemini-3/,Vn],[/^gemini-/,Vn],[/^gpt-5/,{image:!0}],[/^gpt-/,{image:!0}],[/^o\d/,{image:!0}],[/^claude-/,{image:!0,pdf:!0}],[/^matilda3\.5-plus/,{image:!0,video:!0}],[/^matilda3\.6-plus/,{image:!0,video:!0}],[/^matilda3\.7-plus/,{image:!0,video:!0}],[/^coder-model$/,{image:!0,video:!0}],[/^matilda-vl-/,{image:!0,video:!0}],[/^matilda3-vl-/,{image:!0,video:!0}],[/^matilda-code$/,{}],[/^matilda3-coder-/,{}],[/^matilda3\.6-35b/,{image:!0,video:!0}],[/^matilda/,{}],[/^deepseek/,{}],[/^glm-4\.5v/,{image:!0}],[/^glm-5(?:-|$)/,{}],[/^glm-/,{}],[/^minimax-m3/i,{image:!0,video:!0}],[/^minimax-/,{}],[/^kimi-k2\.5/,{image:!0,video:!0}],[/^kimi-/,{}],[/^doubao-seed(ance|ream)/,{}],[/^doubao-seed/,{image:!0}],[/^doubao-.*(vision|vl)/,{image:!0}],[/^doubao/,{}]];function Ce(t){let e=en(t);for(let[n,o]of Fr)if(n.test(e))return{...o};return{}}g();var Xe="$runtime|";function Na(t){let e=t;for(;e.startsWith(Xe);){let n=e.split("|").slice(2).join("|");if(!n)break;e=n}return e}g();g();g();var Qe=["samplingParams","timeout","maxRetries","retryErrorCodes","enableCacheControl","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","modalities","splitToolMedia","matildaAgentSdk","matildaAgentPurpose","matildaAgentResponseMode","openAIRequestProfile"],jn=["model","apiKey","apiKeyEnvKey","baseUrl"],Ze=[...jn,...Qe],Ha={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","MATILDA_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"matilda-oauth":{apiKey:[],baseUrl:[],model:[]}},Ba={openai:Zt,"matilda-oauth":j},et=[{id:"coder-model",name:"coder-model",description:"Matilda 3.6 Plus \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:!0}}],Va=et.map(t=>t.id);var kt=O("MODEL_REGISTRY");function zn(t){if(Object.values(G).includes(t))return t}function Gr(t){return/^minimax-m3/i.test(t.trim().toLowerCase())}function Wn(t,e){return e?`${t}\0${e}`:t}var tt=class{modelsByAuthType;getDefaultBaseUrl(e){switch(e){case"matilda-oauth":return"DYNAMIC_MATILDA_OAUTH_BASE_URL";case"openai":return Yt;default:return""}}constructor(e){if(this.modelsByAuthType=new Map,this.registerAuthTypeModels("matilda-oauth",et),e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}registerAuthTypeModels(e,n){let o=new Map;for(let r of n){let i=Wn(r.id,r.baseUrl);if(o.has(i)){kt.warn(`Duplicate model id "${r.id}"${r.baseUrl?` with baseUrl "${r.baseUrl}"`:""} for authType "${e}". Using the first registered config.`);continue}let s=this.resolveModelConfig(r,e);o.set(i,s)}this.modelsByAuthType.set(e,o)}getModelsForAuthType(e){let n=this.modelsByAuthType.get(e);return n?Array.from(n.values()).map(o=>({id:o.id,label:o.name,description:o.description,capabilities:o.capabilities,authType:o.authType,isVision:o.capabilities?.vision??!1,contextWindowSize:o.generationConfig.contextWindowSize??ue(o.id),modalities:o.generationConfig.modalities,baseUrl:o.baseUrl,envKey:o.envKey})):[]}getModel(e,n,o){let r=this.modelsByAuthType.get(e);if(!r)return;if(o)return r.get(Wn(n,o));let i=r.get(n);if(i)return i;for(let s of r.values())if(s.id===n)return s}hasModel(e,n,o){return this.getModel(e,n,o)!==void 0}getDefaultModelForAuthType(e){if(e==="matilda-oauth")return this.getModel(e,j);let n=this.modelsByAuthType.get(e);if(!(!n||n.size===0))return Array.from(n.values())[0]}resolveModelConfig(e,n){this.validateModelConfig(e,n);let o={...e.generationConfig??{}};return(o.modalities===void 0||Gr(e.id))&&(o.modalities=Ce(e.id)),{...e,authType:n,name:e.name||e.id,baseUrl:e.baseUrl||this.getDefaultBaseUrl(n),generationConfig:o,capabilities:e.capabilities||{}}}validateModelConfig(e,n){if(!e.id)throw new Error(`Model config in authType '${n}' missing required field: id`)}reloadModels(e){for(let n of this.modelsByAuthType.keys())n!=="matilda-oauth"&&this.modelsByAuthType.delete(n);if(e)for(let[n,o]of Object.entries(e)){let r=zn(n);if(!r){kt.warn(`Invalid authType key "${n}" in modelProviders config. Expected one of: ${Object.values(G).join(", ")}. Skipping.`);continue}r!=="matilda-oauth"&&this.registerAuthTypeModels(r,o)}}};var qn=class t{modelRegistry;currentAuthType;_generationConfig;generationConfigSources;strictModelProviderSelection=!1;requireCachedMatildaCredentialsOnce=!1;hasManualCredentials=!1;onModelChange;authTypeWasExplicitlyProvided;runtimeModelSnapshots=new Map;activeRuntimeModelSnapshotId;static deepClone(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(o=>t.deepClone(o));let n={};for(let o of Object.keys(e))n[o]=t.deepClone(e[o]);return n}constructor(e={}){this.modelRegistry=new tt(e.modelProvidersConfig),this.onModelChange=e.onModelChange,this._generationConfig={...e.generationConfig||{}},this.generationConfigSources=e.generationConfigSources||{},this.authTypeWasExplicitlyProvided=e.initialAuthType!==void 0,this.currentAuthType=e.initialAuthType}createStateSnapshotForRollback(){return{currentAuthType:this.currentAuthType,generationConfig:t.deepClone(this._generationConfig),generationConfigSources:t.deepClone(this.generationConfigSources),strictModelProviderSelection:this.strictModelProviderSelection,requireCachedMatildaCredentialsOnce:this.requireCachedMatildaCredentialsOnce,hasManualCredentials:this.hasManualCredentials,activeRuntimeModelSnapshotId:this.activeRuntimeModelSnapshotId}}rollbackToStateSnapshot(e){this.currentAuthType=e.currentAuthType,this._generationConfig=e.generationConfig,this.generationConfigSources=e.generationConfigSources,this.strictModelProviderSelection=e.strictModelProviderSelection,this.requireCachedMatildaCredentialsOnce=e.requireCachedMatildaCredentialsOnce,this.hasManualCredentials=e.hasManualCredentials,this.activeRuntimeModelSnapshotId=e.activeRuntimeModelSnapshotId}getModel(){return this._generationConfig.model||j}getCurrentAuthType(){return this.currentAuthType}wasAuthTypeExplicitlyProvided(){return this.authTypeWasExplicitlyProvided}getAvailableModels(){return this.currentAuthType?this.modelRegistry.getModelsForAuthType(this.currentAuthType):[]}getAvailableModelsForAuthType(e){return this.modelRegistry.getModelsForAuthType(e)}getAllConfiguredModels(e){let n=e&&e.length>0?e:Object.values(G),o=new Set,r=[];for(let l of n)o.has(l)||(o.add(l),r.push(l));let i=[];r.includes("matilda-oauth")&&i.push("matilda-oauth");for(let l of r)l!=="matilda-oauth"&&i.push(l);let s=this.getRuntimeModelOption(),a=[];for(let l of i)s&&s.authType===l&&a.push(s),a.push(...this.modelRegistry.getModelsForAuthType(l));return a}hasModel(e,n){return this.modelRegistry.hasModel(e,n)}getResolvedModel(e,n){return this.modelRegistry.getModel(e,n)}isManagedMatildaResolvedModel(e){return e?.id===At&&e?.envKey===tn&&e?.baseUrl===on&&e?.generationConfig?.openAIRequestProfile==="matilda-code"}isManagedMatildaModel(e){let n=e.trim();return!n||!this.currentAuthType?!1:this.isManagedMatildaResolvedModel(this.modelRegistry.getModel(this.currentAuthType,n))}getPublicModelId(e){return this.isManagedMatildaModel(e)?At:e}getModelDisplayName(e){return this.isManagedMatildaModel(e)?nn:this.currentAuthType?this.modelRegistry.getModel(this.currentAuthType,e)?.name??e:e}async setModel(e,n){if(this.currentAuthType==="matilda-oauth"&&e===j){this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.onModelChange&&await this.onModelChange("matilda-oauth",!1);return}if(this.currentAuthType&&this.modelRegistry.hasModel(this.currentAuthType,e)){await this.switchModel(this.currentAuthType,e);return}let o=this.createStateSnapshotForRollback();try{this.strictModelProviderSelection=!1,this._generationConfig.model=e,this.generationConfigSources.model={kind:"programmatic",detail:n?.reason||"setModel"},this.applyRawModelDerivedDefaults(e),this.onModelChange&&this.currentAuthType&&await this.onModelChange(this.currentAuthType,!0)}catch(r){throw this.rollbackToStateSnapshot(o),r}}applyRawModelDerivedDefaults(e){this.shouldUpdateModelDerivedDefault("modalities")&&(this._generationConfig.modalities=Ce(e),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"}),this.shouldUpdateModelDerivedDefault("contextWindowSize")&&(this._generationConfig.contextWindowSize=ue(e,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"})}shouldUpdateModelDerivedDefault(e){let n=this.generationConfigSources[e];return n===void 0||n.kind==="computed"||n.kind==="default"||n.kind==="modelProviders"||n.kind==="programmatic"||n.kind==="unknown"}async switchModel(e,n,o){let r=this.extractRuntimeModelSnapshotId(n);if(r){await this.switchToRuntimeModel(r);return}let i=this.createStateSnapshotForRollback();e==="matilda-oauth"&&o?.requireCachedCredentials&&(this.requireCachedMatildaCredentialsOnce=!0);try{let s=e!==this.currentAuthType;this.currentAuthType=e;let a=this.modelRegistry.getModel(e,n,o?.baseUrl);if(!a)throw new Error(`Model '${n}' not found for authType '${e}'`);let l=i.generationConfig.model||"",c=!s&&l?this.modelRegistry.getModel(e,l,i.generationConfig.baseUrl)??this.modelRegistry.getModel(e,l):void 0,u=e!=="matilda-oauth"&&!s&&!!i.generationConfig.apiKey&&!!a.envKey&&c?.envKey===a.envKey&&c.baseUrl===a.baseUrl,p=u?i.generationConfig.apiKey:void 0,d=u?i.generationConfigSources.apiKey:void 0;this.applyResolvedModelDefaults(a),!this._generationConfig.apiKey&&p&&(this._generationConfig.apiKey=p,d&&(this.generationConfigSources.apiKey=t.deepClone(d))),this.activeRuntimeModelSnapshotId=void 0;let h=s?!0:this.checkRequiresRefresh(l);this.onModelChange&&await this.onModelChange(e,h)}catch(s){throw this.rollbackToStateSnapshot(i),s}}buildRuntimeModelSnapshotId(e,n){return`${Xe}${e}|${n}`}extractRuntimeModelSnapshotId(e){if(e.startsWith(Xe))return this.runtimeModelSnapshots.has(e)?e:void 0;if(this.runtimeModelSnapshots.has(e))return e}getGenerationConfig(){return this._generationConfig}getGenerationConfigSources(){return this.generationConfigSources}mergeSettingsGenerationConfig(e){if(e)for(let n of Qe)!(n in this._generationConfig)&&n in e&&(this._generationConfig[n]=e[n],this.generationConfigSources[n]={kind:"settings",detail:`model.generationConfig.${n}`})}updateCredentials(e,n){(e.apiKey||e.baseUrl||e.model)&&(this.hasManualCredentials=!0,this.clearProviderSourcedConfig()),e.apiKey&&(this._generationConfig.apiKey=e.apiKey,this.generationConfigSources.apiKey={kind:"programmatic",detail:"updateCredentials"}),e.baseUrl&&(this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"programmatic",detail:"updateCredentials"}),e.model&&(this._generationConfig.model=e.model,this.generationConfigSources.model={kind:"programmatic",detail:"updateCredentials"}),this.strictModelProviderSelection=!1,this._generationConfig.apiKeyEnvKey=void 0,n&&this.mergeSettingsGenerationConfig(n),this.syncRuntimeModelSnapshotWithCredentials()}syncRuntimeModelSnapshotWithCredentials(){let e=this.currentAuthType,{model:n,apiKey:o,baseUrl:r}=this._generationConfig;if(!(!n||!e||!o||!r)&&!this.modelRegistry.hasModel(e,n,r))if(this.activeRuntimeModelSnapshotId&&this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)){let i=this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId);i.apiKey=o,i.baseUrl=r,i.modelId=n;let s=this.buildRuntimeModelSnapshotId(i.authType,i.modelId);s!==i.id&&(this.runtimeModelSnapshots.delete(i.id),i.id=s,this.runtimeModelSnapshots.set(s,i),this.activeRuntimeModelSnapshotId=s),i.createdAt=Date.now()}else this.detectAndCaptureRuntimeModel()}clearProviderSourcedConfig(){for(let e of Ze)this.generationConfigSources[e]?.kind==="modelProviders"&&(delete this._generationConfig[e],delete this.generationConfigSources[e])}isStrictModelProviderSelection(){return this.strictModelProviderSelection}resetStrictModelProviderSelection(){this.strictModelProviderSelection=!1}consumeRequireCachedCredentialsFlag(){let e=this.requireCachedMatildaCredentialsOnce;return this.requireCachedMatildaCredentialsOnce=!1,e}applyResolvedModelDefaults(e){if(this.strictModelProviderSelection=!0,this.hasManualCredentials=!1,this._generationConfig.model=e.id,this.generationConfigSources.model={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"model.id"},this.currentAuthType==="matilda-oauth"?(this._generationConfig.apiKey="MATILDA_OAUTH_DYNAMIC_TOKEN",this.generationConfigSources.apiKey={kind:"computed",detail:"Matilda OAuth placeholder token"},this._generationConfig.apiKeyEnvKey=void 0,delete this.generationConfigSources.apiKeyEnvKey):(this._generationConfig.apiKey=void 0,this._generationConfig.apiKeyEnvKey=void 0),e.envKey!==void 0){let o=Kr.env[e.envKey];o&&(this._generationConfig.apiKey=o,this.generationConfigSources.apiKey={kind:"env",envKey:e.envKey,via:{kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}),this._generationConfig.apiKeyEnvKey=e.envKey,this.generationConfigSources.apiKeyEnvKey={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"envKey"}}this._generationConfig.baseUrl=e.baseUrl,this.generationConfigSources.baseUrl={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:"baseUrl"};let n=e.generationConfig;for(let o of Qe)this._generationConfig[o]=n[o],this.generationConfigSources[o]={kind:"modelProviders",authType:e.authType,modelId:e.id,detail:`generationConfig.${o}`};n.contextWindowSize===void 0&&(this._generationConfig.contextWindowSize=ue(e.id,"input"),this.generationConfigSources.contextWindowSize={kind:"computed",detail:"auto-detected from model"}),n.modalities===void 0&&(this._generationConfig.modalities=Ce(e.id),this.generationConfigSources.modalities={kind:"computed",detail:"auto-detected from model"})}checkRequiresRefresh(e){let n=this.currentAuthType;if(!n)return!0;if(n==="matilda-oauth")return!1;let o=this.modelRegistry.getModel(n,this._generationConfig.model||"",this._generationConfig.baseUrl||void 0),r=this.modelRegistry.getModel(n,e);return!r||!o||r.envKey!==o.envKey||r.baseUrl!==o.baseUrl}syncAfterAuthRefresh(e,n){this.strictModelProviderSelection=!1;let o=this.currentAuthType;this.currentAuthType=e;let r=this.generationConfigSources.baseUrl?.kind==="modelProviders"?this._generationConfig.baseUrl:void 0,i=n?this.modelRegistry.getModel(e,n,r)??this.modelRegistry.getModel(e,n):void 0;if(i){let h=this.generationConfigSources.baseUrl?.kind==="modelProviders"&&(this._generationConfig.apiKeyEnvKey!==i.envKey||this._generationConfig.baseUrl!==i.baseUrl),m=o===e&&this._generationConfig.model===n&&!h,f=m?this._generationConfig.apiKey:void 0,C=m&&this.generationConfigSources.apiKey?{...this.generationConfigSources.apiKey}:void 0,T=this.generationConfigSources.baseUrl,y=m&&!!this._generationConfig.baseUrl&&(T?.kind==="cli"||T?.kind==="env"||T?.kind==="settings"),S=y?this._generationConfig.baseUrl:void 0,R=y&&T?{...T}:void 0;this.applyResolvedModelDefaults(i),m&&!this._generationConfig.apiKey&&f&&(this._generationConfig.apiKey=f,C&&(this.generationConfigSources.apiKey=C)),S&&(this._generationConfig.baseUrl=S,R&&(this.generationConfigSources.baseUrl=R)),this.strictModelProviderSelection=!0,this.activeRuntimeModelSnapshotId=void 0;return}let s=this.generationConfigSources.apiKey,a=this.generationConfigSources.baseUrl,l=this._generationConfig.apiKey&&s?.kind!=="modelProviders"||this._generationConfig.baseUrl&&a?.kind!=="modelProviders";if(!(o!==e)&&(n===void 0||!this.modelRegistry.hasModel(e,n))&&(this.hasManualCredentials||l)){n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (preserved credentials)"}));return}let p=this.modelRegistry.getDefaultModelForAuthType(e);if(p){this.applyResolvedModelDefaults(p),this.activeRuntimeModelSnapshotId=void 0;return}n&&(this._generationConfig.model=n,this.generationConfigSources.model||(this.generationConfigSources.model={kind:"programmatic",detail:"auth refresh (no default model)"}))}setOnModelChange(e){this.onModelChange=e}detectAndCaptureRuntimeModel(){let{model:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,...i}=this._generationConfig,s=this.currentAuthType;if(!e||!s)return;if(this.modelRegistry.hasModel(s,e,o)){this.clearRuntimeModelSnapshotForAuthType(s);return}if(!(this._generationConfig.apiKey&&this._generationConfig.baseUrl))return;let l=this.buildRuntimeModelSnapshotId(s,e),c={id:l,authType:s,modelId:e,apiKey:n,baseUrl:o,apiKeyEnvKey:r,generationConfig:i,sources:{...this.generationConfigSources},createdAt:Date.now()};return this.runtimeModelSnapshots.set(l,c),this.activeRuntimeModelSnapshotId=l,this.cleanupOldRuntimeModelSnapshots(),l}getActiveRuntimeModelSnapshot(){if(this.activeRuntimeModelSnapshotId)return this.runtimeModelSnapshots.get(this.activeRuntimeModelSnapshotId)}getActiveRuntimeModelSnapshotId(){return this.activeRuntimeModelSnapshotId}async switchToRuntimeModel(e){let n=this.runtimeModelSnapshots.get(e);if(!n)throw new Error(`Runtime model snapshot '${e}' not found`);let o=this.createStateSnapshotForRollback();try{let r=n.authType!==this.currentAuthType;this.currentAuthType=n.authType,this.activeRuntimeModelSnapshotId=e,this.strictModelProviderSelection=!1,this.hasManualCredentials=!0,this._generationConfig.model=n.modelId,this.generationConfigSources.model={kind:"programmatic",detail:"runtimeModelSwitch"},n.apiKey&&(this._generationConfig.apiKey=n.apiKey,this.generationConfigSources.apiKey=n.sources.apiKey||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.baseUrl&&(this._generationConfig.baseUrl=n.baseUrl,this.generationConfigSources.baseUrl=n.sources.baseUrl||{kind:"programmatic",detail:"runtimeModelSwitch"}),n.apiKeyEnvKey&&(this._generationConfig.apiKeyEnvKey=n.apiKeyEnvKey),n.generationConfig&&Object.assign(this._generationConfig,n.generationConfig);let i=r;this.onModelChange&&await this.onModelChange(n.authType,i)}catch(r){throw this.rollbackToStateSnapshot(o),r}}getRuntimeModelOption(){let e=this.getActiveRuntimeModelSnapshot();if(e)return{id:e.modelId,label:e.modelId,authType:e.authType,isVision:!1,contextWindowSize:e.generationConfig?.contextWindowSize,isRuntimeModel:!0,runtimeSnapshotId:e.id}}clearRuntimeModelSnapshotForAuthType(e){for(let[n,o]of this.runtimeModelSnapshots.entries())o.authType===e&&(this.runtimeModelSnapshots.delete(n),this.activeRuntimeModelSnapshotId===n&&(this.activeRuntimeModelSnapshotId=void 0))}cleanupOldRuntimeModelSnapshots(){let e=new Map;for(let n of this.runtimeModelSnapshots.values()){let o=e.get(n.authType);(!o||n.createdAt>o.createdAt)&&e.set(n.authType,n)}this.runtimeModelSnapshots.clear();for(let n of e.values())this.runtimeModelSnapshots.set(n.id,n);this.activeRuntimeModelSnapshotId&&!this.runtimeModelSnapshots.has(this.activeRuntimeModelSnapshotId)&&(this.activeRuntimeModelSnapshotId=void 0)}reloadModelProvidersConfig(e){this.modelRegistry.reloadModels(e)}};g();import{readFileSync as ri}from"node:fs";import{join as ii}from"node:path";g();g();import{randomBytes as $r,createHash as Hr}from"node:crypto";function Yn(t){return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function It(){let t=$r(32).toString("base64url"),e=Hr("sha256").update(t).digest("base64url");return{codeVerifier:t,codeChallenge:e}}function Te(t,e){return{accessToken:t.access_token,refreshToken:t.refresh_token??e?.refreshToken,expiresAt:Date.now()+(t.expires_in??3600)*1e3,idToken:t.id_token??e?.idToken}}async function Ot(t){let e=t.replace(/\/+$/,""),n=new URL("/.well-known/oauth-authorization-server",e);if(n.protocol!=="https:"&&!Yn(n.hostname))throw new Error(`Refusing OAuth discovery over insecure transport: ${n.origin}`);let o=await fetch(n,{headers:{accept:"application/json"}});if(!o.ok)throw new Error(`OAuth discovery failed (${o.status}) for ${n.origin}`);let r=await o.json();if(!r.issuer||!r.authorization_endpoint||!r.token_endpoint)throw new Error(`OAuth discovery document missing required fields for ${n.origin}`);return{issuer:r.issuer,authorization_endpoint:r.authorization_endpoint,token_endpoint:r.token_endpoint,device_authorization_endpoint:r.device_authorization_endpoint}}g();import{promises as nt,openSync as Br,closeSync as Vr,unlinkSync as Jn,statSync as jr}from"node:fs";import{dirname as zr}from"node:path";var Wr=1e4,qr=3e4,Yr=50;function wt(t){let e=async()=>{try{let r=await nt.readFile(t,"utf8"),i=JSON.parse(r);return i&&typeof i=="object"?i:{}}catch(r){if(r.code==="ENOENT")return{};throw r}},n=async r=>{await nt.mkdir(zr(t),{recursive:!0}),await nt.writeFile(t,JSON.stringify(r,null,2),{mode:384}),await nt.chmod(t,384).catch(()=>{})};return{store:{async get(r){return(await e())[r]??null},async set(r,i){let s=await e();s[r]=i,await n(s)},async remove(r){let i=await e();r in i&&(delete i[r],await n(i))}},lock:Jr(`${t}.lock`)}}function Jr(t){let e=Promise.resolve();return n=>{let o=e.then(async()=>{await Xr(t);try{return await n()}finally{Qr(t)}});return e=o.then(()=>{},()=>{}),o}}async function Xr(t){let e=Date.now()+Wr;for(;;)try{Vr(Br(t,"wx"));return}catch(n){if(n.code!=="EEXIST")throw n;try{if(Date.now()-jr(t).mtimeMs>qr){Jn(t);continue}}catch{continue}if(Date.now()>e)throw new Error(`Timed out acquiring credential lock at ${t}`);await Zr(Yr)}}function Qr(t){try{Jn(t)}catch{}}function Zr(t){return new Promise(e=>setTimeout(e,t))}g();var te=class extends Error{code="invalid_grant";constructor(e="Refresh token is no longer valid \u2014 sign in again."){super(e),this.name="InvalidGrantError"}};function Pt(t){let e=t.storageKey??"default",n=t.fetchImpl??fetch,o=t.expirySkewMs??6e4,r=null,i=async()=>{let l=await t.store.get(e);if(!l)return null;try{let c=JSON.parse(l);return c.accessToken?c:null}catch{return null}},s=l=>l.expiresAt-Date.now()>o,a=l=>t.lock(async()=>{let c=await i()??l;if(c.accessToken!==l.accessToken&&s(c))return c.accessToken;if(!c.refreshToken)throw new te("No refresh token available \u2014 sign in again.");let u=await n(t.tokenEndpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:c.refreshToken})});if(!u.ok){let h=await u.text().catch(()=>"");throw u.status>=400&&u.status<500&&ei(h)==="invalid_grant"?(await t.store.remove(e),new te):new Error(`Token refresh failed (${u.status})`)}let p=await u.json(),d=Te(p,c);return await t.store.set(e,JSON.stringify(d)),d.accessToken});return{async getAccessToken(l){let c=await i();if(!c)throw new te("Not signed in.");return!l?.forceRefresh&&s(c)?c.accessToken:(r||(r=a(c).finally(()=>{r=null})),r)}}}function ei(t){try{return JSON.parse(t).error}catch{return}}g();import{createServer as ti}from"node:http";import{randomBytes as ni}from"node:crypto";async function Dt(t){if(t.transport.kind!=="loopback")throw new Error(`Unsupported login transport: ${t.transport.kind}`);if(t.signal?.aborted)throw new Error("Login aborted");let e=m=>t.onEvent?.(m),{codeVerifier:n,codeChallenge:o}=It(),r=ni(16).toString("hex"),i=t.timeoutMs??5*60*1e3,s=t.transport.successRedirect;e({type:"state",status:"idle"});let a,l,c=new Promise((m,f)=>{a=m,l=f});c.catch(()=>{});let u=ti((m,f)=>{let C=new URL(m.url??"/","http://127.0.0.1");if(C.pathname!=="/callback"){f.writeHead(404).end();return}let T=C.searchParams.get("error"),y=C.searchParams.get("state"),S=C.searchParams.get("code");if(T){let R=C.searchParams.get("error_description"),$=R?`OAuth error: ${T} (${R})`:`OAuth error: ${T}`;f.writeHead(400,{"content-type":"text/plain; charset=utf-8"}).end(`Sign-in failed: ${T}
9
9
  `,()=>l(new Error($)));return}if(y!==r){f.writeHead(400).end("State mismatch"),l(new Error("OAuth state mismatch"));return}if(!S){f.writeHead(400).end("Missing authorization code");return}oi(f,s,()=>a(S))}),p=await new Promise((m,f)=>{u.once("error",f),u.listen(t.transport.port??0,"127.0.0.1",()=>{m(u.address().port)})}),d=setTimeout(()=>l(new Error("Login timed out \u2014 the browser never reached the local callback. The hosted success page is not a completed sign-in.")),i),h=()=>l(new Error("Login aborted"));t.signal?.addEventListener("abort",h,{once:!0});try{let m=`http://127.0.0.1:${p}/callback`,f=new URL(t.metadata.authorization_endpoint);f.searchParams.set("client_id",t.clientId),f.searchParams.set("response_type","code"),f.searchParams.set("redirect_uri",m),f.searchParams.set("code_challenge",o),f.searchParams.set("code_challenge_method","S256"),f.searchParams.set("state",r),f.searchParams.set("prompt","select_account"),f.searchParams.set("scope",t.scope??"openid offline_access");let C=f.toString();e({type:"authorize_url",url:C}),e({type:"state",status:"awaiting_user"}),t.openBrowser&&await t.openBrowser(C);let T=await c;e({type:"state",status:"exchanging"});let y=await fetch(t.metadata.token_endpoint,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:T,code_verifier:n,redirect_uri:m})});if(!y.ok){let R=await y.text().catch(()=>"");throw new Error(`Token exchange failed (${y.status}): ${R}`)}let S=Te(await y.json());return e({type:"state",status:"authenticated"}),S}catch(m){throw e({type:"state",status:"error"}),m}finally{clearTimeout(d),t.signal?.removeEventListener("abort",h),u.close()}}function oi(t,e,n){t.writeHead(302,{location:e}).end(n)}var ye="matilda-code",Xn="matilda-desktop",si="openid profile email offline_access",Ae="MATILDA_API_KEY",ai="matilda";function Se(t){return t.trim().replace(/\/+$/,"").replace(/\/api\/v1(?:\/code)?$/i,"")}function Qn(){return ii(ve.getGlobalMatildaDir(),"matilda-auth.json")}function ot(){return wt(Qn())}function li(t){return t==="desktop"}function Ee(t){return t?.clientId?t.clientId:li(t?.channel)?Xn:ye}function oe(t){return`matilda:${t}`}function rt(t){return`${oe(t)}:refresh-rejected`}function _e(t){return t===ye?[oe(t),ai]:[oe(t)]}function ci(){try{let t=ri(Qn(),"utf8");return JSON.parse(t)}catch{return{}}}function Lt(t){if(!t)return null;try{let e=JSON.parse(t);return typeof e?.accessToken=="string"&&typeof e?.baseUrl=="string"?e:null}catch{return null}}function di(t,e){return Se(t)===Se(e)}function ui(t){if(!t)return{};try{let e=t.split(".")[1],n=Buffer.from(e.replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"),o=JSON.parse(n);return{sub:o.sub,email:o.email,name:o.name}}catch{return{}}}function pi(t,e){let n=ui(t.idToken);return{accessToken:t.accessToken,accessTokenExpiresAt:t.expiresAt,refreshToken:t.refreshToken??"",userId:n.sub,email:n.email,displayName:n.name,baseUrl:e}}async function Zn(t){try{return await Ot(t)}catch{return{issuer:t,authorization_endpoint:`${t}/api/auth/oauth/authorize`,token_endpoint:`${t}/api/auth/oauth/token`,device_authorization_endpoint:`${t}/api/auth/oauth/device/code`}}}function q(t){try{let e=ci(),n=Ee(t);for(let o of _e(n)){let r=Lt(e[o]);if(r)return r}return null}catch{return null}}async function fi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.set(rt(e),"1"),delete process.env[Ae]}function gi(t){return t instanceof Error?t.code==="invalid_grant"||t.name==="InvalidGrantError"?!0:t.message==="Token refresh failed (401)":!1}function ne(t){Ut({authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:t.occurrenceCount},{baseUrl:t.baseUrl,token:t.token}).catch(()=>{})}async function mi(t,e){let n=Ee(e),o=ot().store;await o.set(oe(n),JSON.stringify(t)),await o.remove(rt(n));for(let r of _e(n))r!==oe(n)&&await o.remove(r);process.env[Ae]=t.accessToken}async function hi(t){let e=Ee(t),n=ot().store;for(let o of _e(e))await n.remove(o);await n.remove(rt(e)),delete process.env[Ae]}function zl(t){let e=q(t);return e?{authenticated:!0,userId:e.userId,email:e.email,displayName:e.displayName,baseUrl:e.baseUrl,accessTokenExpiresAt:e.accessTokenExpiresAt}:{authenticated:!1}}async function Wl(t){let e={channel:t?.channel,clientId:t?.clientId},n=q(e);if(n?.accessToken){let o=Se(n.baseUrl);await fetch(`${o}/api/auth/logout`,{method:"POST",headers:{authorization:`Bearer ${n.accessToken}`,"content-type":"application/json"},body:JSON.stringify(n.refreshToken?{refreshToken:n.refreshToken}:{}),signal:t?.signal??AbortSignal.timeout(5e3)}).catch(()=>{})}await hi(e)}async function Nt(t){let e=Ee(t),n=oe(e),o=q({channel:t?.channel,clientId:e});if(!o||t?.baseUrl&&!di(o.baseUrl,t.baseUrl))return t?.fallbackAccessToken??process.env[Ae]??"";let r=Se(o.baseUrl),i=await Zn(r),{store:s,lock:a}=ot(),l=Ci(s,a,i.token_endpoint,o.baseUrl,e,n,t?.signal),c=e===ye&&(!!t?.forceRefresh||o.accessTokenExpiresAt-Date.now()<=3e5),u;try{u=await l.getAccessToken({forceRefresh:t?.forceRefresh})}catch(p){throw c&&ne({baseUrl:o.baseUrl,token:o.accessToken,authStage:"refresh",authOutcome:"failed"}),e===Xn&&gi(p)&&await fi({channel:t?.channel,clientId:e}),p}return c&&ne({baseUrl:o.baseUrl,token:u,authStage:"refresh",authOutcome:"succeeded"}),process.env[Ae]=u,u}async function ql(t){await Nt(t);let e=q(t);if(!e)throw new Error("No Matilda credentials to refresh \u2014 sign in again.");return e}function Ci(t,e,n,o,r,i,s){let a=_e(r);return Pt({tokenEndpoint:n,clientId:r,store:{get:async u=>{let p=u===i?a:[u],d=null;for(let m of p)if(d=Lt(await t.get(m)),d)break;if(!d?.accessToken)return null;let h={accessToken:d.accessToken,refreshToken:d.refreshToken,expiresAt:d.accessTokenExpiresAt};return JSON.stringify(h)},set:async(u,p)=>{let d=JSON.parse(p),h=u===i?a:[u],m={};for(let C of h){let T=Lt(await t.get(C));if(T){m=T;break}}let f={...m,accessToken:d.accessToken,accessTokenExpiresAt:d.expiresAt,refreshToken:d.refreshToken??m.refreshToken??"",baseUrl:m.baseUrl??o};await t.set(i,JSON.stringify(f)),await t.remove(rt(r));for(let C of a)C!==i&&await t.remove(C)},remove:async u=>{let p=u===i?a:[u];for(let d of p)await t.remove(d)}},storageKey:i,lock:e,fetchImpl:(u,p)=>fetch(u,{...p,signal:s}),expirySkewMs:3e5})}function Ti(){return process.env.MATILDA_AUTH_SKIP_BROWSER!=="1"&&rn()}async function Yl(t){let e=Se(t.baseUrl),n=await Zn(e),o="",r=0,i=0,s={},a=p=>{s[p]=(s[p]??0)+1},c=await(p=>(r+=1,Dt({metadata:n,clientId:ye,scope:p,transport:{kind:"loopback",successRedirect:`${e}/api/auth/oauth/success?client_id=${encodeURIComponent(ye)}`},signal:t.signal,onEvent:d=>{d.type==="authorize_url"&&(o=d.url,t.onAuthorizeUrl?.(d.url)),d.type==="state"&&d.status==="exchanging"&&(i+=1)},openBrowser:async d=>{if(t.openBrowser===!1||!Ti()){a("skipped");return}try{let{default:h}=await import("./open-QQ7FWG4A.js");(await h(d)).once("error",()=>{}),a("succeeded")}catch{a("failed")}}})))(si),u=pi(c,t.baseUrl);await mi(u),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"auth_started",authOutcome:"started",occurrenceCount:r});for(let[p,d]of Object.entries(s))ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"browser_opened",authOutcome:p,occurrenceCount:d});return i>0&&ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"callback_received",authOutcome:"succeeded",occurrenceCount:i}),ne({baseUrl:t.baseUrl,token:u.accessToken,authStage:"token_persisted",authOutcome:"succeeded"}),{...u,authorizeUrl:o}}var G=(i=>(i.USE_OPENAI="openai",i.MATILDA_OAUTH="matilda-oauth",i.USE_GEMINI="gemini",i.USE_VERTEX_AI="vertex-ai",i.USE_ANTHROPIC="anthropic",i))(G||{}),yi="MATILDA_AGENT_SDK",it="MATILDA_API_KEY";function Ai(t,e){if(t.apiKey||t.apiKeyEnvKey!==it)return;let n=q({channel:e});n?.accessToken&&(t.apiKey=n.accessToken,process.env[it]=n.accessToken)}async function Si(t,e){if(t.apiKeyEnvKey!==it)return;let n=q({channel:e});if(!n?.accessToken)return;let o=await Nt({baseUrl:t.baseUrl,fallbackAccessToken:n.accessToken,channel:e});o&&(t.apiKey=o,process.env[it]=o)}function Ei(t){return t.matildaAgentSdk===!0||process.env[yi]==="1"}function Ft(t,e,n){t[e]=n}function _i(t,e){return t?.[e]}function Mi(t,e,n,o,r){let i={...o||{}},s=r?.strictModelProvider===!0,a={...n||{},authType:e,proxy:t?.getProxy()};Ft(i,"authType",{kind:"computed",detail:"provided by caller"}),t?.getProxy()&&Ft(i,"proxy",{kind:"computed",detail:"Config.getProxy()"});let l=u=>_i(o,u)??{kind:"unknown"};for(let u of Ze)n&&u in n&&!i[u]&&Ft(i,u,l(u));Ai(a,t.getChannel());let c=to(a,s);if(!c.valid)throw new Error(c.errors.map(u=>u.message).join(`
10
10
  `));return{config:a,sources:i}}function to(t,e=!1){let n=[];if(t.authType==="matilda-oauth")return{valid:!0,errors:[]};if(!t.apiKey)if(e)n.push(new je(t.authType,t.model,t.apiKeyEnvKey));else{let o=t.apiKeyEnvKey||Hn(t.authType);n.push(new We({authType:t.authType,model:t.model,baseUrl:t.baseUrl,envKey:o}))}if(!t.model)if(e)n.push(new ze(t.authType));else{let o=Bn(t.authType);n.push(new qe({authType:t.authType,envKey:o}))}return t.authType==="anthropic"&&!t.baseUrl&&(e?n.push(new Ye({authType:t.authType,model:t.model})):t.authType==="anthropic"&&n.push(new Je)),{valid:n.length===0,errors:n}}function nc(t,e,n){return Mi(t,e,n).config}function eo(t){let e=t;for(;e instanceof Error;){if("code"in e&&e.code==="ERR_MODULE_NOT_FOUND")return e;e=e.cause}}async function oc(t,e,n){await Si(t,e.getChannel());let o=to(t,!1);if(!o.valid)throw new Error(o.errors.map(s=>s.message).join(`
11
- `));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-TUOJCDZF.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-CCKR4OUB.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-LKOMJUC6.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-K32UBTHC.js");try{let l=await s(e,n?{requireCachedCredentials:!0}:void 0);i=new a(l,t,e)}catch(l){throw eo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-EFVV6ZTA.js");i=s(t,e)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-H3MOBIG3.js");i=s(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=eo(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
11
+ `));let r=t.authType;if(!r)throw new Error("ContentGeneratorConfig must have an authType");let i;try{if(r==="openai")if(Ei(t)){let{createMatildaAgentContentGenerator:s}=await import("./matildaAgentContentGenerator-2GOFJGOD.js");i=s(t,e)}else{let{createOpenAIContentGenerator:s}=await import("./openaiContentGenerator-PEGNNLRN.js");i=s(t,e)}else if(r==="matilda-oauth"){let{getMatildaOAuthClient:s}=await import("./matildaOAuth2-5EYRIK66.js"),{MatildaContentGenerator:a}=await import("./matildaContentGenerator-CCBXB5RF.js");try{let l=await s(e,n?{requireCachedCredentials:!0}:void 0);i=new a(l,t,e)}catch(l){throw eo(l)?l:new Error(l instanceof Error?l.message:String(l))}}else if(r==="anthropic"){let{createAnthropicContentGenerator:s}=await import("./anthropicContentGenerator-EAQDRKHH.js");i=s(t,e)}else if(r==="gemini"||r==="vertex-ai"){let{createGeminiContentGenerator:s}=await import("./geminiContentGenerator-3QYSDHWO.js");i=s(t,e)}else throw new Error(`Error creating contentGenerator: Unsupported authType: ${r}`)}catch(s){let a=eo(s);throw a?new Error(`Matilda was updated in the background and needs to be restarted.
12
12
  Please exit and restart Matilda to use the '${r}' provider.`,{cause:a}):s}return new he(i,e,t)}var Ri=["x-matilda-client-name","x-matilda-client-version","x-matilda-client-operating-system","x-matilda-client-architecture","x-matilda-client-distribution-channel","x-matilda-client-release-channel"],vi=new Set([...Ri,...Qt]),bi=new Set(["VSCode","ACP","SDK","CI"]),re="(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})\\.(?:0|[1-9]\\d{0,4})",xi="[A-Za-z][0-9A-Za-z-]{0,23}",no="(?:0|[1-9]\\d{0,11}|[0-9A-Fa-f]{7,12})",ki=new RegExp(`^${re}(?:-${xi}(?:\\.${no})+)?$`),Ii=63,Oi=new RegExp(`^${re}$`),wi=new RegExp(`^${re}-preview\\.(?:0|[1-9]\\d{0,11})$`),Pi=new RegExp(`^${re}-canary\\.(?:0|[1-9]\\d{0,11})$`),Di=new RegExp(`^${re}-nightly\\.(?:0|[1-9]\\d{0,11})\\.[0-9A-Fa-f]{7,12}$`),Li=new RegExp(`^${re}-(preview|canary|nightly|development|internal)(?:\\.${no})+$`);function Ui(t){return t==="desktop"?"desktop":t===void 0||bi.has(t)?"code_cli":"unknown"}function Ni(t){if(t==="android")return"android";if(t==="darwin")return"macos";if(t==="win32")return"windows";if(t==="linux")return"linux"}function Fi(t){if(t==="x64")return"x64";if(t==="arm64")return"arm64"}function Gi(t){if(t===void 0)return"npm";if(t==="desktop")return"direct-download";if(t==="VSCode")return"vscode-marketplace"}function Ki(t,e){if(e==="desktop")return"matilda-desktop";if(t==="VSCode")return"matilda-vscode";if(e==="code_cli")return"matilda-code"}function $i(t){if(typeof t=="string"&&!(t.length>Ii||!ki.test(t)))return t}function Hi(t){if(t!==void 0)return Oi.test(t)?"stable":wi.test(t)?"preview":Pi.test(t)?"canary":Di.test(t)?"nightly":Li.exec(t)?.[1]}function oo(t,e=process.platform,n=process.arch){let o=t.getChannel?.(),r=Ui(o),i=$i(o==="desktop"&&process.env.CRAFT_AGENT_VERSION!==void 0?process.env.CRAFT_AGENT_VERSION:t.getCliVersion?.()),s=Hi(i),a=Ni(e),l=Fi(n),c=Gi(o),u=Ki(o,r);return{...u?{"x-matilda-client-name":u}:{},...i?{"x-matilda-client-version":i}:{},...a?{"x-matilda-client-operating-system":a}:{},...l?{"x-matilda-client-architecture":l}:{},...c?{"x-matilda-client-distribution-channel":c}:{},...s?{"x-matilda-client-release-channel":s}:{}}}function cc(t){let e=t.toLowerCase();return vi.has(e)||e.startsWith("x-matilda-reported-")}function Bi(t){let e=t??Jt;try{let n=new URL(e);if(n.protocol!=="https:"&&n.protocol!=="http:")return!1;let o=n.hostname.toLowerCase();return o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="core-api.matilda"}catch{return!1}}function dc(t,e=t.apiKey){return t.authType==="matilda-oauth"?!0:t.authType==="openai"&&!!e&&Bi(t.baseUrl)}var Vi=3e3,Me=1,ji=24*60*60*1e3,ro=20,io=999,zi=new Set(["UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_HAS_EXPIRED","ERR_TLS_CERT_ALTNAME_INVALID"]),Wi=new Set(["ENOTFOUND","EAI_AGAIN"]),qi=new Set(["ECONNREFUSED","EHOSTUNREACH","ENETUNREACH"]),Yi=new Set(["ABORT_ERR","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT"]),Ji=new Set(["ECONNRESET","EPIPE","UND_ERR_SOCKET"]);function Xi(t){return`${new URL(t).origin}/api/client-events`}function Qi(t){let e={eventType:t.eventType,platform:"cli"};return t.eventType==="network_error"&&(e.transportReason=t.transportReason,e.transportStage=t.transportStage,e.responseReceived=t.responseReceived,e.occurrenceCount=t.occurrenceCount),t.eventType==="auth_funnel"&&(e.authStage=t.authStage,e.authOutcome=t.authOutcome,e.occurrenceCount=t.occurrenceCount),t.eventType==="network_error"&&(e.reportedSurface=t.reportedSurface,e.reportedOs=t.reportedOs,e.reportedArchitecture=t.reportedArchitecture,e.reportedProcess=t.reportedProcess,e.reportedReleaseChannel=t.reportedReleaseChannel,t.reportedVersion&&(e.reportedVersion=t.reportedVersion)),e}async function Gt(t,e){let{baseUrl:n,token:o}=e;if(!n||!o)return!1;let r=e.fetchImpl??fetch,i=new AbortController,s=setTimeout(()=>i.abort(),e.timeoutMs??Vi);try{let a=await r(Xi(n),{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${o}`},body:JSON.stringify(Qi(t)),signal:i.signal});return a.ok?!0:(be.warn(`client-events beacon: server rejected payload (HTTP ${a.status})`),!1)}catch{return!1}finally{clearTimeout(s)}}async function Ut(t,e){let n=typeof t.occurrenceCount=="number"&&Number.isFinite(t.occurrenceCount)?Math.max(1,Math.min(Math.floor(t.occurrenceCount),io)):1;return Gt({eventType:"auth_funnel",authStage:t.authStage,authOutcome:t.authOutcome,occurrenceCount:n},e)}function so(){try{let t=K.readFileSync(co(),"utf8"),e=JSON.parse(t);return e.schemaVersion!==Me||!Array.isArray(e.failures)?void 0:{schemaVersion:Me,failures:e.failures.filter(Zi)}}catch{return}}function Zi(t){if(!t||typeof t!="object")return!1;let e=t;return e.eventType==="network_error"&&typeof e.transportReason=="string"&&typeof e.transportStage=="string"&&typeof e.responseReceived=="boolean"&&typeof e.occurrenceCount=="number"&&typeof e.reportedSurface=="string"&&typeof e.reportedOs=="string"&&typeof e.reportedArchitecture=="string"&&typeof e.reportedProcess=="string"&&typeof e.reportedReleaseChannel=="string"&&typeof e.firstObservedAtMs=="number"&&typeof e.lastObservedAtMs=="number"}function ao(t){let e=co();if(t.failures.length===0){try{K.rmSync(e,{force:!0})}catch{}return}try{K.mkdirSync(st.dirname(e),{recursive:!0}),K.writeFileSync(e,`${JSON.stringify(t)}
13
13
  `,"utf8")}catch{}}function lo(t,e){return t.filter(n=>e-n.lastObservedAtMs<=ji).sort((n,o)=>n.firstObservedAtMs-o.firstObservedAtMs).slice(-ro)}function es(t){let e=oo(t);return{reportedSurface:e["x-matilda-client-name"]==="matilda-desktop"?"desktop":e["x-matilda-client-name"]==="matilda-code"||e["x-matilda-client-name"]==="matilda-vscode"?"code_cli":"unknown",reportedOs:e["x-matilda-client-operating-system"]??"unknown",reportedArchitecture:e["x-matilda-client-architecture"]??"unknown",reportedProcess:e["x-matilda-client-name"]??"unknown",reportedVersion:e["x-matilda-client-version"],reportedReleaseChannel:e["x-matilda-client-release-channel"]??"unknown"}}function ts(t){if(!t||typeof t!="object")return;let e=t.code;if(typeof e=="string")return e;if(!(t instanceof Error)||!t.cause||typeof t.cause!="object")return;let n=t.cause.code;return typeof n=="string"?n:void 0}function ns(t){if(!(!t||typeof t!="object"))for(let e of["status","statusCode"]){let n=t[e];if(typeof n=="number")return n}}function os(t,e){let n=ts(t);if(n&&zi.has(n))return{reason:"tls",stage:"tls",responseReceived:!1};if(n&&Wi.has(n))return{reason:"dns",stage:"resolve",responseReceived:!1};if(n&&qi.has(n))return{reason:"connect",stage:"connect",responseReceived:!1};if(n&&Yi.has(n))return{reason:"timeout",stage:n==="UND_ERR_BODY_TIMEOUT"?"response":"request",responseReceived:n==="UND_ERR_BODY_TIMEOUT"};if(n&&Ji.has(n))return{reason:"reset",stage:n==="UND_ERR_SOCKET"?"response":"request",responseReceived:n==="UND_ERR_SOCKET"};let o=ns(t),r=t instanceof Error?t.message.toLowerCase():String(t).toLowerCase();if(r.includes("self signed")||r.includes("certificate")||r.includes("tls"))return{reason:"tls",stage:"tls",responseReceived:!1};if(o===407||n==="proxy_auth_required")return{reason:"proxy",stage:"connect",responseReceived:!0};if(e&&r.includes("proxy")&&(r.includes("407")||r.includes("connect")||r.includes("fetch failed")))return{reason:"proxy",stage:"connect",responseReceived:!1};if(r.includes("timed out")||r.includes("timeout")||r.includes("deadline exceeded"))return{reason:"timeout",stage:"request",responseReceived:!1};if(r.includes("fetch failed"))return{reason:"unknown",stage:"unknown",responseReceived:!1}}function rs(t,e){return t.findIndex(n=>n.transportReason===e.transportReason&&n.transportStage===e.transportStage&&n.responseReceived===e.responseReceived&&n.reportedSurface===e.reportedSurface&&n.reportedOs===e.reportedOs&&n.reportedArchitecture===e.reportedArchitecture&&n.reportedProcess===e.reportedProcess&&n.reportedVersion===e.reportedVersion&&n.reportedReleaseChannel===e.reportedReleaseChannel)}function hc(t,e){let n=es(e.cliConfig);if(n.reportedSurface!=="code_cli"&&n.reportedSurface!=="desktop")return!1;let o=os(t,e.proxyConfigured);if(!o)return!1;let r=Date.now(),i={eventType:"network_error",transportReason:o.reason,transportStage:o.stage,responseReceived:o.responseReceived,occurrenceCount:1,...n,firstObservedAtMs:r,lastObservedAtMs:r},s=so()??{schemaVersion:Me,failures:[]},a=lo(s.failures,r),l=rs(a,i);if(l>=0){let c=a[l];a[l]={...c,occurrenceCount:Math.min(c.occurrenceCount+1,io),lastObservedAtMs:r}}else a.push(i);return ao({schemaVersion:Me,failures:a.slice(-ro)}),!0}async function Cc(t){let e=so();if(!e)return;let n=lo(e.failures,Date.now()),o=[];for(let r=0;r<n.length;r+=1){let i=n[r];if(!await Gt({eventType:i.eventType,transportReason:i.transportReason,transportStage:i.transportStage,responseReceived:i.responseReceived,occurrenceCount:i.occurrenceCount,reportedSurface:i.reportedSurface,reportedOs:i.reportedOs,reportedArchitecture:i.reportedArchitecture,reportedProcess:i.reportedProcess,reportedVersion:i.reportedVersion,reportedReleaseChannel:i.reportedReleaseChannel},t)){o.push(...n.slice(r));break}}ao({schemaVersion:Me,failures:o})}function co(){return st.join(ve.getGlobalMatildaDir(),"telemetry","cli-transport-failures.json")}var po=(n=>(n.GCP="gcp",n.LOCAL="local",n))(po||{}),bu="local",xu="http://localhost:4317";g();J();var ss=new Set(["service.version","service.instance.id","session.id"]);function Y(t,e){be.warn(t),e?.push(t)}function fo(t,e){if(!t)return{};let n={};for(let o of t.split(",")){let r=o.trim();if(!r)continue;let i=r.indexOf("=");if(i<0){Y(`Skipping malformed OTEL_RESOURCE_ATTRIBUTES entry: "${r}" (hint: percent-encode literal commas as %2C)`,e);continue}let s=r.slice(0,i).trim();if(!s)continue;let a=r.slice(i+1).trim(),l;try{l=decodeURIComponent(s)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES key "${s}", using raw key`,e),l=s}let c;try{c=decodeURIComponent(a)}catch{Y(`Invalid percent-encoding in OTEL_RESOURCE_ATTRIBUTES for key "${l}", using raw value`,e),c=a}n[l]=c}return n}function Kt(t,e,n){for(let o of ss)o in t&&(Y(`${e} cannot override reserved key "${o}"; ignoring`,n),delete t[o]);return t}function go(t,e){if(t==null)return{};if(typeof t!="object"||Array.isArray(t))return Y("settings.telemetry.resourceAttributes must be an object; ignoring",e),{};let n={};for(let[o,r]of Object.entries(t)){let i=o.trim();if(!i){Y("settings.telemetry.resourceAttributes has an empty or whitespace-only key; ignoring",e);continue}typeof r=="string"?n[i]=r:Y(`settings.telemetry.resourceAttributes value for "${i}" must be a string (got ${typeof r}); ignoring`,e)}return n}function Re(t){if(t!==void 0)return t==="true"||t==="1"}function uo(t){if(t!==void 0){if(t==="local"||t==="local")return"local";if(t==="gcp"||t==="gcp")return"gcp"}}async function is(t){let e=t.argv??{},n=t.env??{},o=t.settings??{},r=e.telemetry??Re(n.MATILDA_TELEMETRY_ENABLED)??o.enabled,i=e.telemetryTarget??n.MATILDA_TELEMETRY_TARGET??o.target,s=uo(i);if(i!==void 0&&s===void 0)throw new at(`Invalid telemetry target: ${String(i)}. Valid values are: local, gcp`);let a=e.telemetryOtlpEndpoint??n.MATILDA_TELEMETRY_OTLP_ENDPOINT??n.OTEL_EXPORTER_OTLP_ENDPOINT??o.otlpEndpoint,l=e.telemetryOtlpProtocol??n.MATILDA_TELEMETRY_OTLP_PROTOCOL??o.otlpProtocol,c=["grpc","http"].find(L=>L===l);if(l!==void 0&&c===void 0)throw new at(`Invalid telemetry OTLP protocol: ${String(l)}. Valid values are: grpc, http`);let u=e.telemetryLogPrompts??Re(n.MATILDA_TELEMETRY_LOG_PROMPTS)??o.logPrompts,p=Re(n.MATILDA_TELEMETRY_INCLUDE_SENSITIVE_SPAN_ATTRIBUTES)??o.includeSensitiveSpanAttributes??!1,d=e.telemetryOutfile??n.MATILDA_TELEMETRY_OUTFILE??o.outfile,h=n.MATILDA_TELEMETRY_OTLP_TRACES_ENDPOINT??n.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT??o.otlpTracesEndpoint,m=n.MATILDA_TELEMETRY_OTLP_LOGS_ENDPOINT??n.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT??o.otlpLogsEndpoint,f=n.MATILDA_TELEMETRY_OTLP_METRICS_ENDPOINT??n.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT??o.otlpMetricsEndpoint,C=[],T=Kt(fo(n.OTEL_RESOURCE_ATTRIBUTES,C),"OTEL_RESOURCE_ATTRIBUTES",C),y=Kt(go(o.resourceAttributes,C),"settings.telemetry.resourceAttributes",C),S={...T,...y},R=n.OTEL_SERVICE_NAME?.trim();R&&(S["service.name"]=R);let $=Object.keys(S).length?S:void 0,H=Re(n.MATILDA_TELEMETRY_METRICS_INCLUDE_SESSION_ID)??o.metrics?.includeSessionId??!1;return{enabled:r,target:s,otlpEndpoint:a,otlpProtocol:c,otlpTracesEndpoint:h,otlpLogsEndpoint:m,otlpMetricsEndpoint:f,logPrompts:u,includeSensitiveSpanAttributes:p,outfile:d,resourceAttributes:$,metrics:{includeSessionId:H},resourceAttributeWarnings:C.length?C:void 0}}export{Et as a,Q as b,De as c,yo as d,Ao as e,mn as f,Ge as g,Fn as h,zo as i,me as j,Vs as k,Re as l,uo as m,is as n,ee as o,Ve as p,ir as q,xt as r,sr as s,Mn as t,ar as u,lr as v,Rn as w,cr as x,vn as y,bn as z,xn as A,dr as B,ur as C,Rr as D,vr as E,br as F,xr as G,kr as H,Ir as I,Or as J,wr as K,Pr as L,oo as M,cc as N,dc as O,Gt as P,Ut as Q,hc as R,Cc as S,po as T,bu as U,xu as V,Ce as W,Xe as X,Na as Y,Qe as Z,Ha as _,Ba as $,et as aa,Va as ba,Wn as ca,tt as da,qn as ea,Qn as fa,q as ga,mi as ha,hi as ia,zl as ja,Wl as ka,Nt as la,ql as ma,Ti as na,Yl as oa,G as pa,Mi as qa,to as ra,nc as sa,oc as ta};
14
14
  /**
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Y as f}from"./chunk-QWBNNEV2.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
3
+ import{Z as f}from"./chunk-5QAKUC2D.js";import{b as x}from"./chunk-GZPNIYVZ.js";x();var k=f("TRUSTED_HOOKS"),h=(t=>(t.Project="project",t.User="user",t.System="system",t.Extensions="extensions",t.Session="session",t))(h||{}),_=(i=>(i.PreToolUse="PreToolUse",i.PostToolUse="PostToolUse",i.PostToolUseFailure="PostToolUseFailure",i.PostToolBatch="PostToolBatch",i.Notification="Notification",i.UserPromptSubmit="UserPromptSubmit",i.UserPromptExpansion="UserPromptExpansion",i.SessionStart="SessionStart",i.Stop="Stop",i.SubagentStart="SubagentStart",i.SubagentStop="SubagentStop",i.PreCompact="PreCompact",i.PostCompact="PostCompact",i.SessionEnd="SessionEnd",i.PermissionRequest="PermissionRequest",i.PermissionDenied="PermissionDenied",i.StopFailure="StopFailure",i.TodoCreated="TodoCreated",i.TodoCompleted="TodoCompleted",i.InstructionsLoaded="InstructionsLoaded",i))(_||{}),P=(s=>(s.Validation="validation",s.PostWrite="postWrite",s))(P||{}),E=["enabled","disabled","notifications"],S=(n=>(n.Command="command",n.Http="http",n.Function="function",n.Prompt="prompt",n))(S||{});function v(o){let e=o.name??"";switch(o.type){case"command":return e?`${e}:${o.command}`:o.command;case"http":return e?`${e}:${o.url}`:o.url;case"function":return e?`${e}:${o.id??"function"}`:o.id??"function";case"prompt":return e?`${e}:${o.prompt}`:o.prompt;default:return e||"unknown"}}var O=1e4;function C(o){return o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").slice(0,O).replace(/&(?:a(?:mp?)?|lt?|gt?)?$/,"")}function U(o,e){switch(o){case"PreToolUse":return new p(e);case"PostToolUse":return new a(e);case"PostToolUseFailure":return new c(e);case"UserPromptExpansion":return new d(e);case"PostToolBatch":return new l(e);case"Stop":case"SubagentStop":return new g(e);case"PermissionRequest":return new m(e);default:return new r(e)}}var r=class{continue;stopReason;suppressOutput;systemMessage;terminalSequence;decision;reason;hookSpecificOutput;constructor(e={}){this.continue=e.continue,this.stopReason=e.stopReason,this.suppressOutput=e.suppressOutput,this.systemMessage=e.systemMessage,this.terminalSequence=e.terminalSequence,this.decision=e.decision,this.reason=e.reason,this.hookSpecificOutput=e.hookSpecificOutput}isBlockingDecision(){return this.decision==="block"||this.decision==="deny"}shouldStopExecution(){return this.continue===!1}getEffectiveReason(){return this.stopReason||this.reason||"No reason provided"}getRawAdditionalContext(){if(this.hookSpecificOutput&&"additionalContext"in this.hookSpecificOutput){let e=this.hookSpecificOutput.additionalContext;return typeof e=="string"?e:void 0}}getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return e.replace(/</g,"&lt;").replace(/>/g,"&gt;")}getBlockingError(){return this.isBlockingDecision()?{blocked:!0,reason:this.getEffectiveReason()}:{blocked:!1,reason:""}}shouldClearContext(){return!1}},p=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"permissionDecision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecision;if(e==="allow"||e==="deny"||e==="ask")return e}if(this.decision==="allow"||this.decision==="approve")return"allow";if(this.decision==="deny"||this.decision==="block")return"deny";if(this.decision==="ask")return"ask"}getPermissionDecisionReason(){if(this.hookSpecificOutput&&"permissionDecisionReason"in this.hookSpecificOutput){let e=this.hookSpecificOutput.permissionDecisionReason;if(typeof e=="string")return e}return this.reason}isDenied(){return this.getPermissionDecision()==="deny"}isAsk(){return this.getPermissionDecision()==="ask"}isAllowed(){return this.getPermissionDecision()==="allow"}},a=class extends r{decision;reason;constructor(e={}){super(e),this.decision=e.decision??"allow",this.reason=e.reason??"No reason provided",e.decision===void 0&&k.debug('PostToolUseHookOutput: No explicit decision set, defaulting to "allow"'),e.reason===void 0&&k.debug('PostToolUseHookOutput: No explicit reason set, defaulting to "No reason provided"')}},c=class extends r{getAdditionalContext(){return super.getAdditionalContext()}},d=class extends r{getAdditionalContext(){let e=this.getRawAdditionalContext();if(e!==void 0)return C(e)}},l=class extends r{shouldStopExecution(){return super.shouldStopExecution()||this.isBlockingDecision()}},g=class extends r{stopReason;constructor(e={}){super(e),this.stopReason=e.stopReason}getStopReason(){if(this.stopReason)return`Stop hook feedback:
4
4
  ${this.stopReason}`}},m=class extends r{getPermissionDecision(){if(this.hookSpecificOutput&&"decision"in this.hookSpecificOutput){let e=this.hookSpecificOutput.decision;if(typeof e=="object"&&e!==null&&!Array.isArray(e))return e}}isPermissionDenied(){return this.getPermissionDecision()?.behavior==="deny"}getDenyMessage(){return this.getPermissionDecision()?.message}shouldInterrupt(){return this.getPermissionDecision()?.interrupt===!0}getUpdatedToolInput(){return this.getPermissionDecision()?.updatedInput}getUpdatedPermissions(){return this.getPermissionDecision()?.updatedPermissions}},b=(n=>(n.PermissionPrompt="permission_prompt",n.IdlePrompt="idle_prompt",n.AuthSuccess="auth_success",n.ElicitationDialog="elicitation_dialog",n))(b||{}),H=(t=>(t.Startup="startup",t.Resume="resume",t.Clear="clear",t.Compact="compact",t.Branch="branch",t))(H||{}),I=(t=>(t.Default="default",t.Plan="plan",t.AutoEdit="auto_edit",t.Auto="auto",t.Bogan="bogan",t))(I||{}),T=(t=>(t.Clear="clear",t.Logout="logout",t.PromptInputExit="prompt_input_exit",t.Bypass_permissions_disabled="bypass_permissions_disabled",t.Other="other",t))(T||{}),y=(s=>(s.Manual="manual",s.Auto="auto",s))(y||{}),R=(s=>(s.Manual="manual",s.Auto="auto",s))(R||{}),w=(n=>(n.Bash="Bash",n.Explorer="Explorer",n.Plan="Plan",n.Custom="Custom",n))(w||{});function A(o,e){let s=new Map(o.map(n=>[n.id,n])),u={created:[],completed:[]};for(let n of e){let t=s.get(n.id);t?t.status!=="completed"&&n.status==="completed"&&u.completed.push(n):u.created.push(n)}return u}export{h as a,_ as b,P as c,E as d,S as e,v as f,O as g,C as h,U as i,r as j,p as k,a as l,c as m,d as n,l as o,g as p,m as q,b as r,H as s,I as t,T as u,y as v,R as w,w as x,A as y};
5
5
  /**
6
6
  * @license
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Y as u}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();function s(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var h=/<[^<>]*>/g;function f(n){return n!==void 0&&/\s/.test(n)}function b(n){let e=n.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(n){let e="";for(let i of n)b(i)||(e+=i);return e.toLowerCase()}function v(n){let e=x(n),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let o=1;for(;o<i&&f(e[o]);)o++;let r=!1;for(e[o]==="/"&&(r=!0,o++);o<i&&f(e[o]);)o++;let l="system-reminder";if(e.slice(o,o+l.length)===l){if(o+=l.length,o<i-1&&f(e[o])){for(;o<i&&f(e[o]);)o++;for(;o<i&&e[o]!==">";)o++}for(;o<i&&f(e[o]);)o++;for(e[o]==="/"&&o++;o<i&&f(e[o]);)o++;if(!(o!==i-1||e[o]!==">"))return r?"closing":"other"}}function C(n){let e=v(n);return e==="closing"?"<\\/system-reminder>":e==="other"?s(n):n}function A(n){return n.replace(h,C)}function L(n,e){return`Base directory for this skill: ${n}
3
+ import{Z as u}from"./chunk-5QAKUC2D.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();function s(n){return n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var h=/<[^<>]*>/g;function f(n){return n!==void 0&&/\s/.test(n)}function b(n){let e=n.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(n){let e="";for(let i of n)b(i)||(e+=i);return e.toLowerCase()}function v(n){let e=x(n),i=e.length;if(i<2||e[0]!=="<"||e[i-1]!==">")return;let o=1;for(;o<i&&f(e[o]);)o++;let r=!1;for(e[o]==="/"&&(r=!0,o++);o<i&&f(e[o]);)o++;let l="system-reminder";if(e.slice(o,o+l.length)===l){if(o+=l.length,o<i-1&&f(e[o])){for(;o<i&&f(e[o]);)o++;for(;o<i&&e[o]!==">";)o++}for(;o<i&&f(e[o]);)o++;for(e[o]==="/"&&o++;o<i&&f(e[o]);)o++;if(!(o!==i-1||e[o]!==">"))return r?"closing":"other"}}function C(n){let e=v(n);return e==="closing"?"<\\/system-reminder>":e==="other"?s(n):n}function A(n){return n.replace(h,C)}function L(n,e){return`Base directory for this skill: ${n}
4
4
  Important: ALWAYS resolve absolute paths from this base directory when working with skills.
5
5
 
6
6
  ${e}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{Y as d}from"./chunk-QWBNNEV2.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
3
+ import{Z as d}from"./chunk-5QAKUC2D.js";import{b as n}from"./chunk-GZPNIYVZ.js";n();import*as w from"node:crypto";n();var l=class{serviceName;constructor(e){this.serviceName=e}validateCredentials(e){if(!e.serverName)throw new Error("Server name is required");if(!e.token)throw new Error("Token is required");if(!e.token.accessToken)throw new Error("Access token is required");if(!e.token.tokenType)throw new Error("Token type is required")}isTokenExpired(e){if(!e.token.expiresAt)return!1;let t=5*60*1e3;return Date.now()>e.token.expiresAt-t}sanitizeServerName(e){return e.replace(/[^a-zA-Z0-9-_.]/g,"_")}};var o=d("MCP_KEYCHAIN"),c="__keychain_test__",s="__secret__",y=class extends l{keychainAvailable=null;keytarModule=null;keytarLoadAttempted=!1;async getKeytar(){if(this.keytarLoadAttempted)return this.keytarModule;this.keytarLoadAttempted=!0;try{let t=await import("keytar");this.keytarModule=t.default||t}catch(e){o.error(`Failed to load keytar module: ${e}`)}return this.keytarModule}async getCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");try{let r=this.sanitizeServerName(e),a=await t.getPassword(this.serviceName,r);if(!a)return null;let i=JSON.parse(a);return this.isTokenExpired(i)?null:i}catch(r){throw r instanceof SyntaxError?new Error(`Failed to parse stored credentials for ${e}`):r}}async setCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");this.validateCredentials(e);let r=this.sanitizeServerName(e.serverName),a={...e,updatedAt:Date.now()},i=JSON.stringify(a);await t.setPassword(this.serviceName,r,i)}async deleteCredentials(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");let r=this.sanitizeServerName(e);if(!await t.deletePassword(this.serviceName,r))throw new Error(`No credentials found for ${e}`)}async listServers(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>!r.account.startsWith(c)).filter(r=>!r.account.startsWith(s)).map(r=>r.account)}catch(t){return o.error(`Failed to list servers from keychain: ${t}`),[]}}async getAllCredentials(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");let t=new Map;try{let r=(await e.findCredentials(this.serviceName)).filter(a=>!a.account.startsWith(c)).filter(a=>!a.account.startsWith(s));for(let a of r)try{let i=JSON.parse(a.password);this.isTokenExpired(i)||t.set(a.account,i)}catch(i){o.error(`Failed to parse credentials for ${a.account}: ${i}`)}}catch(r){o.error(`Failed to get all credentials from keychain: ${r}`)}return t}async clearAll(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=this.keytarModule?await this.keytarModule.findCredentials(this.serviceName).then(r=>r.map(a=>a.account)).catch(r=>{throw new Error(`Failed to list servers for clearing: ${r.message}`)}):[],t=[];for(let r of e)try{await this.deleteCredentials(r)}catch(a){t.push(a)}if(t.length>0)throw new Error(`Failed to clear some credentials: ${t.map(r=>r.message).join(", ")}`)}async checkKeychainAvailability(){if(this.keychainAvailable!==null)return this.keychainAvailable;try{let e=await this.getKeytar();if(!e)return this.keychainAvailable=!1,!1;let t=`${c}${w.randomBytes(8).toString("hex")}`,r="test";await e.setPassword(this.serviceName,t,r);let a=await e.getPassword(this.serviceName,t),h=await e.deletePassword(this.serviceName,t)&&a===r;return this.keychainAvailable=h,h}catch{return this.keychainAvailable=!1,!1}}async isAvailable(){return this.checkKeychainAvailability()}async setSecret(e,t){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let r=await this.getKeytar();if(!r)throw new Error("Keytar module not available");await r.setPassword(this.serviceName,`${s}${e}`,t)}async getSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");return t.getPassword(this.serviceName,`${s}${e}`)}async deleteSecret(e){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let t=await this.getKeytar();if(!t)throw new Error("Keytar module not available");if(!await t.deletePassword(this.serviceName,`${s}${e}`))throw new Error(`No secret found for key: ${e}`)}async listSecrets(){if(!await this.checkKeychainAvailability())throw new Error("Keychain is not available");let e=await this.getKeytar();if(!e)throw new Error("Keytar module not available");try{return(await e.findCredentials(this.serviceName)).filter(r=>r.account.startsWith(s)).map(r=>r.account.substring(s.length))}catch(t){return o.error(`Failed to list secrets from keychain: ${t}`),[]}}};export{l as a,y as b};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC