@qitqode/qitqode-android-arm64 0.1.20 → 0.1.21
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.
- package/bundle/{chunk-xb031er5.js → chunk-0942095s.js} +1 -1
- package/bundle/{chunk-0x0a51w3.js → chunk-0czxqcg7.js} +1 -1
- package/bundle/{chunk-9a5nck3f.js → chunk-1b9ey3yh.js} +1 -1
- package/bundle/{chunk-gspdrdyq.js → chunk-21q96fet.js} +1 -1
- package/bundle/{chunk-wnjg8mmh.js → chunk-21t254fq.js} +1 -1
- package/bundle/{chunk-zfvk6zjj.js → chunk-2db8pn5k.js} +1 -1
- package/bundle/{chunk-r2waj5n2.js → chunk-3gxhdy0c.js} +1 -1
- package/bundle/{chunk-471yj527.js → chunk-3m0t96kb.js} +1 -1
- package/bundle/{chunk-dp3hqm2m.js → chunk-4tk4wppp.js} +1 -1
- package/bundle/{chunk-p77m937s.js → chunk-5k1eyz7y.js} +1 -1
- package/bundle/{chunk-c4mxtqyq.js → chunk-5rcnwm9j.js} +1 -1
- package/bundle/{chunk-k728fzrr.js → chunk-5yghd32r.js} +1 -1
- package/bundle/{chunk-q39h31te.js → chunk-651fyxmn.js} +3 -3
- package/bundle/{chunk-7myavy3p.js → chunk-6ba9fc92.js} +1 -1
- package/bundle/{chunk-w0fg8n1f.js → chunk-6dznrhs4.js} +1 -1
- package/bundle/{chunk-knwayz0m.js → chunk-6t70j1wg.js} +1 -1
- package/bundle/{chunk-3makpbng.js → chunk-767vf2ha.js} +1 -1
- package/bundle/{chunk-k6z419yx.js → chunk-76p9v2jf.js} +1 -1
- package/bundle/{chunk-1brsnwhv.js → chunk-7hxksr4h.js} +1 -1
- package/bundle/{chunk-2w154wad.js → chunk-7jefvta3.js} +1 -1
- package/bundle/{chunk-fegrrsfj.js → chunk-7skp0dmg.js} +1 -1
- package/bundle/{chunk-1qw3yh13.js → chunk-88ckmmdr.js} +3 -3
- package/bundle/{chunk-0pbpzty2.js → chunk-8fn883z8.js} +1 -1
- package/bundle/{chunk-c422awkv.js → chunk-9gfe4wtk.js} +1 -1
- package/bundle/{chunk-rdsae6k4.js → chunk-9hwsz356.js} +1 -1
- package/bundle/{chunk-3fzgbam3.js → chunk-9vvvyk10.js} +1 -1
- package/bundle/{chunk-n0y1ea17.js → chunk-atg7cn5r.js} +1 -1
- package/bundle/{chunk-qq48ffjc.js → chunk-b3721b7c.js} +1 -1
- package/bundle/{chunk-nt07vncv.js → chunk-b4r19v4g.js} +1 -1
- package/bundle/{chunk-b2ky15zx.js → chunk-bsg92mw7.js} +1 -1
- package/bundle/{chunk-skjge2wh.js → chunk-bzj7yxw6.js} +1 -1
- package/bundle/{chunk-1gj0m10e.js → chunk-c1dwcsax.js} +1 -1
- package/bundle/{chunk-ysxmk1z1.js → chunk-c4vfxy1e.js} +1 -1
- package/bundle/{chunk-v7yvnnmr.js → chunk-esjs9s9g.js} +1 -1
- package/bundle/chunk-f2q7cbah.js +2 -0
- package/bundle/{chunk-mpn5qm9j.js → chunk-fssswy6j.js} +1 -1
- package/bundle/{chunk-4pedvzse.js → chunk-ghtm9598.js} +1 -1
- package/bundle/{chunk-p41h8naw.js → chunk-gkz68a5s.js} +1 -1
- package/bundle/{chunk-gfm4vad7.js → chunk-gp6nvjb8.js} +153 -153
- package/bundle/{chunk-6tjghyx6.js → chunk-hkydp4m3.js} +1 -1
- package/bundle/{chunk-hjvje9xj.js → chunk-htdpkk8v.js} +1 -1
- package/bundle/{chunk-ghmctw8s.js → chunk-hvnhkrd3.js} +1 -1
- package/bundle/{chunk-fgqrcjsm.js → chunk-hvqgvsa5.js} +1 -1
- package/bundle/{chunk-dgbvsnqb.js → chunk-js7becx7.js} +1 -1
- package/bundle/{chunk-5549c7mb.js → chunk-jwgqpntf.js} +1 -1
- package/bundle/{chunk-7nas10jx.js → chunk-k44dj66f.js} +1 -1
- package/bundle/{chunk-9g4hz1st.js → chunk-kvs7qbga.js} +1 -1
- package/bundle/{chunk-1q2vhe78.js → chunk-m7q12naw.js} +1 -1
- package/bundle/{chunk-pskkmca2.js → chunk-mc1m6dxk.js} +1 -1
- package/bundle/{chunk-anse7bd0.js → chunk-myjbd0vk.js} +1 -1
- package/bundle/{chunk-b49rxw15.js → chunk-n499tbz0.js} +1 -1
- package/bundle/{chunk-y36ggefa.js → chunk-n5k2c708.js} +1 -1
- package/bundle/{chunk-zafrxr1q.js → chunk-n6fh34xx.js} +1 -1
- package/bundle/{chunk-6bq7rx7m.js → chunk-n7a4wpjj.js} +1 -1
- package/bundle/{chunk-vh8w0ea8.js → chunk-ns0hezdf.js} +1 -1
- package/bundle/{chunk-pn77fh9b.js → chunk-q2zk0z41.js} +1 -1
- package/bundle/{chunk-s2g5989e.js → chunk-qh76pgsk.js} +1 -1
- package/bundle/{chunk-tp7sfreh.js → chunk-qxtz0tfd.js} +1 -1
- package/bundle/{chunk-3gdqmave.js → chunk-qy1s81tv.js} +2 -2
- package/bundle/{chunk-28knamc9.js → chunk-r03jc8xm.js} +1 -1
- package/bundle/{chunk-wmqcz5rb.js → chunk-rkb592nb.js} +1 -1
- package/bundle/{chunk-w8rvjbgr.js → chunk-s811ht10.js} +1 -1
- package/bundle/{chunk-8k1q3g8s.js → chunk-sj8py6vk.js} +1 -1
- package/bundle/{chunk-dvn528qs.js → chunk-t6dymkmx.js} +1 -1
- package/bundle/{chunk-jc0wbpjq.js → chunk-th5z0zx7.js} +1 -1
- package/bundle/chunk-tnn7hm4v.js +2 -0
- package/bundle/{chunk-aej69zjj.js → chunk-v0jnnpsz.js} +1 -1
- package/bundle/{chunk-f57rqsby.js → chunk-vdt8dvqs.js} +1 -1
- package/bundle/{chunk-0fwz5r1k.js → chunk-w2f8sjc4.js} +1 -1
- package/bundle/{chunk-rmmrnx95.js → chunk-w5nwkb0s.js} +1 -1
- package/bundle/{chunk-ckhhm2m8.js → chunk-w9mdrb90.js} +1 -1
- package/bundle/{chunk-xbxgrwvy.js → chunk-y7hkykkj.js} +1 -1
- package/bundle/{chunk-ej3gmaba.js → chunk-yja3y138.js} +1 -1
- package/bundle/{chunk-k5vwx1nv.js → chunk-yt6cfsdh.js} +1 -1
- package/bundle/index.js +3 -3
- package/bundle/worker.js +1 -1
- package/package.json +1 -1
- package/bundle/chunk-7pqevqry.js +0 -2
- package/bundle/chunk-p4pc1zdd.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gl as Hj,nl as ql}from"./chunk-0x0a51w3.js";import{Bl as mA,Fl as W1,Hl as UX,Il as aA,Jl as U9,Pl as S8,Ql as B0,Sl as w7,sl as D7,ul as l$,vl as hY,wl as FY,xl as I1,yl as w$,zl as P8}from"./chunk-7myavy3p.js";import{$l as L1,Vl as xV,Wl as hV,Xl as mw,Zl as lw}from"./chunk-fegrrsfj.js";import{Hn as n6,Im as ml,cn as q8,dn as w1,en as Q9,fn as y6,gn as v9,in as m0,kn as q$,ln as LL,on as oA,pn as KX,qn as ll,rn as f5,tn as nK,zn as sA}from"./chunk-c4x99ayd.js";import{Fo as r8,Go as $V,Ho as s8}from"./chunk-w0fg8n1f.js";import{$o as LA,Io as ww,Lo as Nj,Mo as jj,Oo as $w,Qo as O6,Ro as Um,So as jm,To as Vm,Wo as Hm,Xo as Bm,Zo as zm,ap as Mm,bp as Dm,gp as YX}from"./chunk-0pbpzty2.js";import{ip as u0,jp as Gd,kp as F$,lp as Zw,mp as w0}from"./chunk-tq258v8s.js";import{np as mR,op as Ql,pp as Gl}from"./chunk-jc0wbpjq.js";import{rp as Fm}from"./chunk-jfy6bfvv.js";import{sp as d0}from"./chunk-aej69zjj.js";import{Bp as iL,up as cL}from"./chunk-98nh88th.js";import{Cq as pL,Ep as hL,Fp as Q8,Hp as zJ,Ip as BX,Mp as F4,Np as gL,Op as uL,Pp as aV,Rp as r6,Tp as OX,Up as M4,Vp as mL,Xp as qX,Zp as lL,_p as dL,dq as D4,fq as v8,gq as NX,hq as O4,iq as y8,kq as G8,uq as QH}from"./chunk-t7v8wzr9.js";import{Dq as p0,Eq as AX,Gq as s6,Iq as yZ,Kq as JH,Lq as YH,Nq as XH,Pq as I8,Qq as h5,Rq as rV,Sq as HX}from"./chunk-er5q8nhp.js";import{$q as lu}from"./chunk-t2n6fmpy.js";import{cr as BA,dr as Su}from"./chunk-ng85b73s.js";import{qr as Vw,sr as AO,wr as UO}from"./chunk-k5vwx1nv.js";import{yr as WR}from"./chunk-ej3gmaba.js";import{Hr as Uj,Or as U$,Pr as PZ,Vr as g9,Wr as Vj}from"./chunk-3nc9wy1m.js";import{ys as Q30}from"./chunk-r8ddb02d.js";import{Ds as N1}from"./chunk-56cty7nr.js";import{Fs as WY}from"./chunk-thbjhgw0.js";import{$s as xY,Gs as O$,Is as Uw,Os as M8,Zs as qA,_s as V4,ct as F0,dt as b0,mt as C0}from"./chunk-v7yvnnmr.js";import{Bt as Z4,Ct as C$,Gt as o0,nt as J8,pt as FZ,rt as n8,vt as f1}from"./chunk-b5x3zghc.js";import{Ht as U00}from"./chunk-t1f7jeat.js";import{It as I}from"./chunk-tk6gjy9d.js";import{Jt as Tj,Kt as Rm,Nt as rm,Ot as EK,Pt as j1,Qt as CK,Rt as _6,_t as K9}from"./chunk-pkdk0ppc.js";import{Cu as D}from"./chunk-hrnx60em.js";import{uz as oU}from"./chunk-01gtn79f.js";import{$H as L,AO as I$,BN as O,FC as v7,FF as i7,GE as gw,KJ as uw,NE as z9,TF as K4,UE as k6,VC as Rl,eC as O1,iF as RY,jD as S1,oC as k7,oJ as Dw,pI as nU,vD as Z8,xJ as v6,yF as T0}from"./chunk-meaa7wrs.js";import{kP as xL}from"./chunk-gvj8qg7x.js";import{lP as h6,mP as S,nP as B1,pP as X0,qP as PK,rP as IK}from"./chunk-fa03gsff.js";var L7=S((MO)=>{Object.defineProperty(MO,"__esModule",{value:!0});MO.stringArray=MO.array=MO.func=MO.error=MO.number=MO.string=MO.boolean=void 0;function nd($){return $===!0||$===!1}MO.boolean=nd;function NO($){return typeof $==="string"||$ instanceof String}MO.string=NO;function od($){return typeof $==="number"||$ instanceof Number}MO.number=od;function sd($){return $ instanceof Error}MO.error=sd;function rd($){return typeof $==="function"}MO.func=rd;function jO($){return Array.isArray($)}MO.array=jO;function ad($){return jO($)&&$.every((Z)=>NO(Z))}MO.stringArray=ad});var BU=S((cO)=>{Object.defineProperty(cO,"__esModule",{value:!0});cO.Message=cO.NotificationType9=cO.NotificationType8=cO.NotificationType7=cO.NotificationType6=cO.NotificationType5=cO.NotificationType4=cO.NotificationType3=cO.NotificationType2=cO.NotificationType1=cO.NotificationType0=cO.NotificationType=cO.RequestType9=cO.RequestType8=cO.RequestType7=cO.RequestType6=cO.RequestType5=cO.RequestType4=cO.RequestType3=cO.RequestType2=cO.RequestType1=cO.RequestType=cO.RequestType0=cO.AbstractMessageSignature=cO.ParameterStructures=cO.ResponseError=cO.ErrorCodes=void 0;var B5=L7(),VU;(function($){$.ParseError=-32700,$.InvalidRequest=-32600,$.MethodNotFound=-32601,$.InvalidParams=-32602,$.InternalError=-32603,$.jsonrpcReservedErrorRangeStart=-32099,$.serverErrorStart=-32099,$.MessageWriteError=-32099,$.MessageReadError=-32098,$.PendingResponseRejected=-32097,$.ConnectionInactive=-32096,$.ServerNotInitialized=-32002,$.UnknownErrorCode=-32001,$.jsonrpcReservedErrorRangeEnd=-32000,$.serverErrorEnd=-32000})(VU||(cO.ErrorCodes=VU={}));class HU extends Error{constructor($,Z,J){super(Z);this.code=B5.number($)?$:VU.UnknownErrorCode,this.data=J,Object.setPrototypeOf(this,HU.prototype)}toJson(){let $={code:this.code,message:this.message};if(this.data!==void 0)$.data=this.data;return $}}cO.ResponseError=HU;class h${constructor($){this.kind=$}static is($){return $===h$.auto||$===h$.byName||$===h$.byPosition}toString(){return this.kind}}cO.ParameterStructures=h$;h$.auto=new h$("auto");h$.byPosition=new h$("byPosition");h$.byName=new h$("byName");class n1{constructor($,Z){this.method=$,this.numberOfParams=Z}get parameterStructures(){return h$.auto}}cO.AbstractMessageSignature=n1;class LO extends n1{constructor($){super($,0)}}cO.RequestType0=LO;class TO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType=TO;class RO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType1=RO;class PO extends n1{constructor($){super($,2)}}cO.RequestType2=PO;class IO extends n1{constructor($){super($,3)}}cO.RequestType3=IO;class EO extends n1{constructor($){super($,4)}}cO.RequestType4=EO;class CO extends n1{constructor($){super($,5)}}cO.RequestType5=CO;class bO extends n1{constructor($){super($,6)}}cO.RequestType6=bO;class _O extends n1{constructor($){super($,7)}}cO.RequestType7=_O;class SO extends n1{constructor($){super($,8)}}cO.RequestType8=SO;class fO extends n1{constructor($){super($,9)}}cO.RequestType9=fO;class kO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType=kO;class vO extends n1{constructor($){super($,0)}}cO.NotificationType0=vO;class yO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType1=yO;class xO extends n1{constructor($){super($,2)}}cO.NotificationType2=xO;class hO extends n1{constructor($){super($,3)}}cO.NotificationType3=hO;class gO extends n1{constructor($){super($,4)}}cO.NotificationType4=gO;class uO extends n1{constructor($){super($,5)}}cO.NotificationType5=uO;class mO extends n1{constructor($){super($,6)}}cO.NotificationType6=mO;class lO extends n1{constructor($){super($,7)}}cO.NotificationType7=lO;class dO extends n1{constructor($){super($,8)}}cO.NotificationType8=dO;class pO extends n1{constructor($){super($,9)}}cO.NotificationType9=pO;var wO;(function($){function Z(X){let Q=X;return Q&&B5.string(Q.method)&&(B5.string(Q.id)||B5.number(Q.id))}$.isRequest=Z;function J(X){let Q=X;return Q&&B5.string(Q.method)&&X.id===void 0}$.isNotification=J;function Y(X){let Q=X;return Q&&(Q.result!==void 0||!!Q.error)&&(B5.string(Q.id)||B5.number(Q.id)||Q.id===null)}$.isResponse=Y})(wO||(cO.Message=wO={}))});var FU=S((sO)=>{var nO;Object.defineProperty(sO,"__esModule",{value:!0});sO.LRUCache=sO.LinkedMap=sO.Touch=void 0;var g$;(function($){$.None=0,$.First=1,$.AsOld=$.First,$.Last=2,$.AsNew=$.Last})(g$||(sO.Touch=g$={}));class zU{constructor(){this[nO]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has($){return this._map.has($)}get($,Z=g$.None){let J=this._map.get($);if(!J)return;if(Z!==g$.None)this.touch(J,Z);return J.value}set($,Z,J=g$.None){let Y=this._map.get($);if(Y){if(Y.value=Z,J!==g$.None)this.touch(Y,J)}else{switch(Y={key:$,value:Z,next:void 0,previous:void 0},J){case g$.None:this.addItemLast(Y);break;case g$.First:this.addItemFirst(Y);break;case g$.Last:this.addItemLast(Y);break;default:this.addItemLast(Y);break}this._map.set($,Y),this._size++}return this}delete($){return!!this.remove($)}remove($){let Z=this._map.get($);if(!Z)return;return this._map.delete($),this.removeItem(Z),this._size--,Z.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error("Invalid list");let $=this._head;return this._map.delete($.key),this.removeItem($),this._size--,$.value}forEach($,Z){let J=this._state,Y=this._head;while(Y){if(Z)$.bind(Z)(Y.value,Y.key,this);else $(Y.value,Y.key,this);if(this._state!==J)throw Error("LinkedMap got modified during iteration.");Y=Y.next}}keys(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.key,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}values(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.value,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}entries(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:[Z.key,Z.value],done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}[(nO=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld($){if($>=this.size)return;if($===0){this.clear();return}let Z=this._head,J=this.size;while(Z&&J>$)this._map.delete(Z.key),Z=Z.next,J--;if(this._head=Z,this._size=J,Z)Z.previous=void 0;this._state++}addItemFirst($){if(!this._head&&!this._tail)this._tail=$;else if(!this._head)throw Error("Invalid list");else $.next=this._head,this._head.previous=$;this._head=$,this._state++}addItemLast($){if(!this._head&&!this._tail)this._head=$;else if(!this._tail)throw Error("Invalid list");else $.previous=this._tail,this._tail.next=$;this._tail=$,this._state++}removeItem($){if($===this._head&&$===this._tail)this._head=void 0,this._tail=void 0;else if($===this._head){if(!$.next)throw Error("Invalid list");$.next.previous=void 0,this._head=$.next}else if($===this._tail){if(!$.previous)throw Error("Invalid list");$.previous.next=void 0,this._tail=$.previous}else{let{next:Z,previous:J}=$;if(!Z||!J)throw Error("Invalid list");Z.previous=J,J.next=Z}$.next=void 0,$.previous=void 0,this._state++}touch($,Z){if(!this._head||!this._tail)throw Error("Invalid list");if(Z!==g$.First&&Z!==g$.Last)return;if(Z===g$.First){if($===this._head)return;let{next:J,previous:Y}=$;if($===this._tail)Y.next=void 0,this._tail=Y;else J.previous=Y,Y.next=J;$.previous=void 0,$.next=this._head,this._head.previous=$,this._head=$,this._state++}else if(Z===g$.Last){if($===this._tail)return;let{next:J,previous:Y}=$;if($===this._head)J.previous=void 0,this._head=J;else J.previous=Y,Y.next=J;$.next=void 0,$.previous=this._tail,this._tail.next=$,this._tail=$,this._state++}}toJSON(){let $=[];return this.forEach((Z,J)=>{$.push([J,Z])}),$}fromJSON($){this.clear();for(let[Z,J]of $)this.set(Z,J)}}sO.LinkedMap=zU;class oO extends zU{constructor($,Z=1){super();this._limit=$,this._ratio=Math.min(Math.max(0,Z),1)}get limit(){return this._limit}set limit($){this._limit=$,this.checkTrim()}get ratio(){return this._ratio}set ratio($){this._ratio=Math.min(Math.max(0,$),1),this.checkTrim()}get($,Z=g$.AsNew){return super.get($,Z)}peek($){return super.get($,g$.None)}set($,Z){return super.set($,Z,g$.Last),this.checkTrim(),this}checkTrim(){if(this.size>this._limit)this.trimOld(Math.round(this._limit*this._ratio))}}sO.LRUCache=oO});var $q=S((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});tO.Disposable=void 0;var aO;(function($){function Z(J){return{dispose:J}}$.create=Z})(aO||(tO.Disposable=aO={}))});var DZ=S((Zq)=>{Object.defineProperty(Zq,"__esModule",{value:!0});var AU;function OU(){if(AU===void 0)throw Error("No runtime abstraction layer installed");return AU}(function($){function Z(J){if(J===void 0)throw Error("No runtime abstraction layer provided");AU=J}$.install=Z})(OU||(OU={}));Zq.default=OU});var T7=S((Xq)=>{Object.defineProperty(Xq,"__esModule",{value:!0});Xq.Emitter=Xq.Event=void 0;var fp=DZ(),Jq;(function($){let Z={dispose(){}};$.None=function(){return Z}})(Jq||(Xq.Event=Jq={}));class Yq{add($,Z=null,J){if(!this._callbacks)this._callbacks=[],this._contexts=[];if(this._callbacks.push($),this._contexts.push(Z),Array.isArray(J))J.push({dispose:()=>this.remove($,Z)})}remove($,Z=null){if(!this._callbacks)return;let J=!1;for(let Y=0,X=this._callbacks.length;Y<X;Y++)if(this._callbacks[Y]===$)if(this._contexts[Y]===Z){this._callbacks.splice(Y,1),this._contexts.splice(Y,1);return}else J=!0;if(J)throw Error("When adding a listener with a context, you should remove it with the same context")}invoke(...$){if(!this._callbacks)return[];let Z=[],J=this._callbacks.slice(0),Y=this._contexts.slice(0);for(let X=0,Q=J.length;X<Q;X++)try{Z.push(J[X].apply(Y[X],$))}catch(G){(0,fp.default)().console.error(G)}return Z}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}}class N9{constructor($){this._options=$}get event(){if(!this._event)this._event=($,Z,J)=>{if(!this._callbacks)this._callbacks=new Yq;if(this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty())this._options.onFirstListenerAdd(this);this._callbacks.add($,Z);let Y={dispose:()=>{if(!this._callbacks)return;if(this._callbacks.remove($,Z),Y.dispose=N9._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty())this._options.onLastListenerRemove(this)}};if(Array.isArray(J))J.push(Y);return Y};return this._event}fire($){if(this._callbacks)this._callbacks.invoke.call(this._callbacks,$)}dispose(){if(this._callbacks)this._callbacks.dispose(),this._callbacks=void 0}}Xq.Emitter=N9;N9._noop=function(){}});var M9=S((Wq)=>{Object.defineProperty(Wq,"__esModule",{value:!0});Wq.CancellationTokenSource=Wq.CancellationToken=void 0;var vp=DZ(),yp=L7(),qU=T7(),j9;(function($){$.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:qU.Event.None}),$.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:qU.Event.None});function Z(J){let Y=J;return Y&&(Y===$.None||Y===$.Cancelled||yp.boolean(Y.isCancellationRequested)&&!!Y.onCancellationRequested)}$.is=Z})(j9||(Wq.CancellationToken=j9={}));var xp=Object.freeze(function($,Z){let J=(0,vp.default)().timer.setTimeout($.bind(Z),0);return{dispose(){J.dispose()}}});class NU{constructor(){this._isCancelled=!1}cancel(){if(!this._isCancelled){if(this._isCancelled=!0,this._emitter)this._emitter.fire(void 0),this.dispose()}}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){if(this._isCancelled)return xp;if(!this._emitter)this._emitter=new qU.Emitter;return this._emitter.event}dispose(){if(this._emitter)this._emitter.dispose(),this._emitter=void 0}}class Gq{get token(){if(!this._token)this._token=new NU;return this._token}cancel(){if(!this._token)this._token=j9.Cancelled;else this._token.cancel()}dispose(){if(!this._token)this._token=j9.None;else if(this._token instanceof NU)this._token.dispose()}}Wq.CancellationTokenSource=Gq});var Aq=S((zq)=>{Object.defineProperty(zq,"__esModule",{value:!0});zq.SharedArrayReceiverStrategy=zq.SharedArraySenderStrategy=void 0;var gp=M9(),CY;(function($){$.Continue=0,$.Cancelled=1})(CY||(CY={}));class Uq{constructor(){this.buffers=new Map}enableCancellation($){if($.id===null)return;let Z=new SharedArrayBuffer(4),J=new Int32Array(Z,0,1);J[0]=CY.Continue,this.buffers.set($.id,Z),$.$cancellationData=Z}async sendCancellation($,Z){let J=this.buffers.get(Z);if(J===void 0)return;let Y=new Int32Array(J,0,1);Atomics.store(Y,0,CY.Cancelled)}cleanup($){this.buffers.delete($)}dispose(){this.buffers.clear()}}zq.SharedArraySenderStrategy=Uq;class Vq{constructor($){this.data=new Int32Array($,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===CY.Cancelled}get onCancellationRequested(){throw Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class Hq{constructor($){this.token=new Vq($)}cancel(){}dispose(){}}class Bq{constructor(){this.kind="request"}createCancellationTokenSource($){let Z=$.$cancellationData;if(Z===void 0)return new gp.CancellationTokenSource;return new Hq(Z)}}zq.SharedArrayReceiverStrategy=Bq});var jU=S((qq)=>{Object.defineProperty(qq,"__esModule",{value:!0});qq.Semaphore=void 0;var mp=DZ();class Oq{constructor($=1){if($<=0)throw Error("Capacity must be greater than 0");this._capacity=$,this._active=0,this._waiting=[]}lock($){return new Promise((Z,J)=>{this._waiting.push({thunk:$,resolve:Z,reject:J}),this.runNext()})}get active(){return this._active}runNext(){if(this._waiting.length===0||this._active===this._capacity)return;(0,mp.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let $=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error("To many thunks active");try{let Z=$.thunk();if(Z instanceof Promise)Z.then((J)=>{this._active--,$.resolve(J),this.runNext()},(J)=>{this._active--,$.reject(J),this.runNext()});else this._active--,$.resolve(Z),this.runNext()}catch(Z){this._active--,$.reject(Z),this.runNext()}}}qq.Semaphore=Oq});var Lq=S((Dq)=>{Object.defineProperty(Dq,"__esModule",{value:!0});Dq.ReadableStreamMessageReader=Dq.AbstractMessageReader=Dq.MessageReader=void 0;var DU=DZ(),R7=L7(),MU=T7(),lp=jU(),jq;(function($){function Z(J){let Y=J;return Y&&R7.func(Y.listen)&&R7.func(Y.dispose)&&R7.func(Y.onError)&&R7.func(Y.onClose)&&R7.func(Y.onPartialMessage)}$.is=Z})(jq||(Dq.MessageReader=jq={}));class LU{constructor(){this.errorEmitter=new MU.Emitter,this.closeEmitter=new MU.Emitter,this.partialMessageEmitter=new MU.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($){this.errorEmitter.fire(this.asError($))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage($){this.partialMessageEmitter.fire($)}asError($){if($ instanceof Error)return $;else return Error(`Reader received error. Reason: ${R7.string($.message)?$.message:"unknown"}`)}}Dq.AbstractMessageReader=LU;var wU;(function($){function Z(J){let Y,X,Q,G=new Map,W,K=new Map;if(J===void 0||typeof J==="string")Y=J??"utf-8";else{if(Y=J.charset??"utf-8",J.contentDecoder!==void 0)Q=J.contentDecoder,G.set(Q.name,Q);if(J.contentDecoders!==void 0)for(let U of J.contentDecoders)G.set(U.name,U);if(J.contentTypeDecoder!==void 0)W=J.contentTypeDecoder,K.set(W.name,W);if(J.contentTypeDecoders!==void 0)for(let U of J.contentTypeDecoders)K.set(U.name,U)}if(W===void 0)W=(0,DU.default)().applicationJson.decoder,K.set(W.name,W);return{charset:Y,contentDecoder:Q,contentDecoders:G,contentTypeDecoder:W,contentTypeDecoders:K}}$.fromOptions=Z})(wU||(wU={}));class Mq extends LU{constructor($,Z){super();this.readable=$,this.options=wU.fromOptions(Z),this.buffer=(0,DU.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new lp.Semaphore(1)}set partialMessageTimeout($){this._partialMessageTimeout=$}get partialMessageTimeout(){return this._partialMessageTimeout}listen($){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=$;let Z=this.readable.onData((J)=>{this.onData(J)});return this.readable.onError((J)=>this.fireError(J)),this.readable.onClose(()=>this.fireClose()),Z}onData($){try{this.buffer.append($);while(!0){if(this.nextMessageLength===-1){let J=this.buffer.tryReadHeaders(!0);if(!J)return;let Y=J.get("content-length");if(!Y){this.fireError(Error(`Header must provide a Content-Length property.
|
|
2
|
+
import{gl as Hj,nl as ql}from"./chunk-0czxqcg7.js";import{Bl as mA,Fl as W1,Hl as UX,Il as aA,Jl as U9,Pl as S8,Ql as B0,Sl as w7,sl as D7,ul as l$,vl as hY,wl as FY,xl as I1,yl as w$,zl as P8}from"./chunk-6ba9fc92.js";import{$l as L1,Vl as xV,Wl as hV,Xl as mw,Zl as lw}from"./chunk-7skp0dmg.js";import{Hn as n6,Im as ml,cn as q8,dn as w1,en as Q9,fn as y6,gn as v9,in as m0,kn as q$,ln as LL,on as oA,pn as KX,qn as ll,rn as f5,tn as nK,zn as sA}from"./chunk-c4x99ayd.js";import{Fo as r8,Go as $V,Ho as s8}from"./chunk-6dznrhs4.js";import{$o as LA,Io as ww,Lo as Nj,Mo as jj,Oo as $w,Qo as O6,Ro as Um,So as jm,To as Vm,Wo as Hm,Xo as Bm,Zo as zm,ap as Mm,bp as Dm,gp as YX}from"./chunk-8fn883z8.js";import{ip as u0,jp as Gd,kp as F$,lp as Zw,mp as w0}from"./chunk-tq258v8s.js";import{np as mR,op as Ql,pp as Gl}from"./chunk-th5z0zx7.js";import{rp as Fm}from"./chunk-jfy6bfvv.js";import{sp as d0}from"./chunk-v0jnnpsz.js";import{Bp as iL,up as cL}from"./chunk-98nh88th.js";import{Cq as pL,Ep as hL,Fp as Q8,Hp as zJ,Ip as BX,Mp as F4,Np as gL,Op as uL,Pp as aV,Rp as r6,Tp as OX,Up as M4,Vp as mL,Xp as qX,Zp as lL,_p as dL,dq as D4,fq as v8,gq as NX,hq as O4,iq as y8,kq as G8,uq as QH}from"./chunk-t7v8wzr9.js";import{Dq as p0,Eq as AX,Gq as s6,Iq as yZ,Kq as JH,Lq as YH,Nq as XH,Pq as I8,Qq as h5,Rq as rV,Sq as HX}from"./chunk-er5q8nhp.js";import{$q as lu}from"./chunk-t2n6fmpy.js";import{cr as BA,dr as Su}from"./chunk-ng85b73s.js";import{qr as Vw,sr as AO,wr as UO}from"./chunk-yt6cfsdh.js";import{yr as WR}from"./chunk-yja3y138.js";import{Hr as Uj,Or as U$,Pr as PZ,Vr as g9,Wr as Vj}from"./chunk-3nc9wy1m.js";import{ys as Q30}from"./chunk-r8ddb02d.js";import{Ds as N1}from"./chunk-56cty7nr.js";import{Fs as WY}from"./chunk-thbjhgw0.js";import{$s as xY,Gs as O$,Is as Uw,Os as M8,Zs as qA,_s as V4,ct as F0,dt as b0,mt as C0}from"./chunk-esjs9s9g.js";import{Bt as Z4,Ct as C$,Gt as o0,nt as J8,pt as FZ,rt as n8,vt as f1}from"./chunk-b5x3zghc.js";import{Ht as U00}from"./chunk-t1f7jeat.js";import{It as I}from"./chunk-tk6gjy9d.js";import{Jt as Tj,Kt as Rm,Nt as rm,Ot as EK,Pt as j1,Qt as CK,Rt as _6,_t as K9}from"./chunk-pkdk0ppc.js";import{Cu as D}from"./chunk-hrnx60em.js";import{uz as oU}from"./chunk-01gtn79f.js";import{$H as L,AO as I$,BN as O,FC as v7,FF as i7,GE as gw,KJ as uw,NE as z9,TF as K4,UE as k6,VC as Rl,eC as O1,iF as RY,jD as S1,oC as k7,oJ as Dw,pI as nU,vD as Z8,xJ as v6,yF as T0}from"./chunk-meaa7wrs.js";import{kP as xL}from"./chunk-gvj8qg7x.js";import{lP as h6,mP as S,nP as B1,pP as X0,qP as PK,rP as IK}from"./chunk-fa03gsff.js";var L7=S((MO)=>{Object.defineProperty(MO,"__esModule",{value:!0});MO.stringArray=MO.array=MO.func=MO.error=MO.number=MO.string=MO.boolean=void 0;function nd($){return $===!0||$===!1}MO.boolean=nd;function NO($){return typeof $==="string"||$ instanceof String}MO.string=NO;function od($){return typeof $==="number"||$ instanceof Number}MO.number=od;function sd($){return $ instanceof Error}MO.error=sd;function rd($){return typeof $==="function"}MO.func=rd;function jO($){return Array.isArray($)}MO.array=jO;function ad($){return jO($)&&$.every((Z)=>NO(Z))}MO.stringArray=ad});var BU=S((cO)=>{Object.defineProperty(cO,"__esModule",{value:!0});cO.Message=cO.NotificationType9=cO.NotificationType8=cO.NotificationType7=cO.NotificationType6=cO.NotificationType5=cO.NotificationType4=cO.NotificationType3=cO.NotificationType2=cO.NotificationType1=cO.NotificationType0=cO.NotificationType=cO.RequestType9=cO.RequestType8=cO.RequestType7=cO.RequestType6=cO.RequestType5=cO.RequestType4=cO.RequestType3=cO.RequestType2=cO.RequestType1=cO.RequestType=cO.RequestType0=cO.AbstractMessageSignature=cO.ParameterStructures=cO.ResponseError=cO.ErrorCodes=void 0;var B5=L7(),VU;(function($){$.ParseError=-32700,$.InvalidRequest=-32600,$.MethodNotFound=-32601,$.InvalidParams=-32602,$.InternalError=-32603,$.jsonrpcReservedErrorRangeStart=-32099,$.serverErrorStart=-32099,$.MessageWriteError=-32099,$.MessageReadError=-32098,$.PendingResponseRejected=-32097,$.ConnectionInactive=-32096,$.ServerNotInitialized=-32002,$.UnknownErrorCode=-32001,$.jsonrpcReservedErrorRangeEnd=-32000,$.serverErrorEnd=-32000})(VU||(cO.ErrorCodes=VU={}));class HU extends Error{constructor($,Z,J){super(Z);this.code=B5.number($)?$:VU.UnknownErrorCode,this.data=J,Object.setPrototypeOf(this,HU.prototype)}toJson(){let $={code:this.code,message:this.message};if(this.data!==void 0)$.data=this.data;return $}}cO.ResponseError=HU;class h${constructor($){this.kind=$}static is($){return $===h$.auto||$===h$.byName||$===h$.byPosition}toString(){return this.kind}}cO.ParameterStructures=h$;h$.auto=new h$("auto");h$.byPosition=new h$("byPosition");h$.byName=new h$("byName");class n1{constructor($,Z){this.method=$,this.numberOfParams=Z}get parameterStructures(){return h$.auto}}cO.AbstractMessageSignature=n1;class LO extends n1{constructor($){super($,0)}}cO.RequestType0=LO;class TO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType=TO;class RO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.RequestType1=RO;class PO extends n1{constructor($){super($,2)}}cO.RequestType2=PO;class IO extends n1{constructor($){super($,3)}}cO.RequestType3=IO;class EO extends n1{constructor($){super($,4)}}cO.RequestType4=EO;class CO extends n1{constructor($){super($,5)}}cO.RequestType5=CO;class bO extends n1{constructor($){super($,6)}}cO.RequestType6=bO;class _O extends n1{constructor($){super($,7)}}cO.RequestType7=_O;class SO extends n1{constructor($){super($,8)}}cO.RequestType8=SO;class fO extends n1{constructor($){super($,9)}}cO.RequestType9=fO;class kO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType=kO;class vO extends n1{constructor($){super($,0)}}cO.NotificationType0=vO;class yO extends n1{constructor($,Z=h$.auto){super($,1);this._parameterStructures=Z}get parameterStructures(){return this._parameterStructures}}cO.NotificationType1=yO;class xO extends n1{constructor($){super($,2)}}cO.NotificationType2=xO;class hO extends n1{constructor($){super($,3)}}cO.NotificationType3=hO;class gO extends n1{constructor($){super($,4)}}cO.NotificationType4=gO;class uO extends n1{constructor($){super($,5)}}cO.NotificationType5=uO;class mO extends n1{constructor($){super($,6)}}cO.NotificationType6=mO;class lO extends n1{constructor($){super($,7)}}cO.NotificationType7=lO;class dO extends n1{constructor($){super($,8)}}cO.NotificationType8=dO;class pO extends n1{constructor($){super($,9)}}cO.NotificationType9=pO;var wO;(function($){function Z(X){let Q=X;return Q&&B5.string(Q.method)&&(B5.string(Q.id)||B5.number(Q.id))}$.isRequest=Z;function J(X){let Q=X;return Q&&B5.string(Q.method)&&X.id===void 0}$.isNotification=J;function Y(X){let Q=X;return Q&&(Q.result!==void 0||!!Q.error)&&(B5.string(Q.id)||B5.number(Q.id)||Q.id===null)}$.isResponse=Y})(wO||(cO.Message=wO={}))});var FU=S((sO)=>{var nO;Object.defineProperty(sO,"__esModule",{value:!0});sO.LRUCache=sO.LinkedMap=sO.Touch=void 0;var g$;(function($){$.None=0,$.First=1,$.AsOld=$.First,$.Last=2,$.AsNew=$.Last})(g$||(sO.Touch=g$={}));class zU{constructor(){this[nO]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has($){return this._map.has($)}get($,Z=g$.None){let J=this._map.get($);if(!J)return;if(Z!==g$.None)this.touch(J,Z);return J.value}set($,Z,J=g$.None){let Y=this._map.get($);if(Y){if(Y.value=Z,J!==g$.None)this.touch(Y,J)}else{switch(Y={key:$,value:Z,next:void 0,previous:void 0},J){case g$.None:this.addItemLast(Y);break;case g$.First:this.addItemFirst(Y);break;case g$.Last:this.addItemLast(Y);break;default:this.addItemLast(Y);break}this._map.set($,Y),this._size++}return this}delete($){return!!this.remove($)}remove($){let Z=this._map.get($);if(!Z)return;return this._map.delete($),this.removeItem(Z),this._size--,Z.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw Error("Invalid list");let $=this._head;return this._map.delete($.key),this.removeItem($),this._size--,$.value}forEach($,Z){let J=this._state,Y=this._head;while(Y){if(Z)$.bind(Z)(Y.value,Y.key,this);else $(Y.value,Y.key,this);if(this._state!==J)throw Error("LinkedMap got modified during iteration.");Y=Y.next}}keys(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.key,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}values(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:Z.value,done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}entries(){let $=this._state,Z=this._head,J={[Symbol.iterator]:()=>{return J},next:()=>{if(this._state!==$)throw Error("LinkedMap got modified during iteration.");if(Z){let Y={value:[Z.key,Z.value],done:!1};return Z=Z.next,Y}else return{value:void 0,done:!0}}};return J}[(nO=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld($){if($>=this.size)return;if($===0){this.clear();return}let Z=this._head,J=this.size;while(Z&&J>$)this._map.delete(Z.key),Z=Z.next,J--;if(this._head=Z,this._size=J,Z)Z.previous=void 0;this._state++}addItemFirst($){if(!this._head&&!this._tail)this._tail=$;else if(!this._head)throw Error("Invalid list");else $.next=this._head,this._head.previous=$;this._head=$,this._state++}addItemLast($){if(!this._head&&!this._tail)this._head=$;else if(!this._tail)throw Error("Invalid list");else $.previous=this._tail,this._tail.next=$;this._tail=$,this._state++}removeItem($){if($===this._head&&$===this._tail)this._head=void 0,this._tail=void 0;else if($===this._head){if(!$.next)throw Error("Invalid list");$.next.previous=void 0,this._head=$.next}else if($===this._tail){if(!$.previous)throw Error("Invalid list");$.previous.next=void 0,this._tail=$.previous}else{let{next:Z,previous:J}=$;if(!Z||!J)throw Error("Invalid list");Z.previous=J,J.next=Z}$.next=void 0,$.previous=void 0,this._state++}touch($,Z){if(!this._head||!this._tail)throw Error("Invalid list");if(Z!==g$.First&&Z!==g$.Last)return;if(Z===g$.First){if($===this._head)return;let{next:J,previous:Y}=$;if($===this._tail)Y.next=void 0,this._tail=Y;else J.previous=Y,Y.next=J;$.previous=void 0,$.next=this._head,this._head.previous=$,this._head=$,this._state++}else if(Z===g$.Last){if($===this._tail)return;let{next:J,previous:Y}=$;if($===this._head)J.previous=void 0,this._head=J;else J.previous=Y,Y.next=J;$.next=void 0,$.previous=this._tail,this._tail.next=$,this._tail=$,this._state++}}toJSON(){let $=[];return this.forEach((Z,J)=>{$.push([J,Z])}),$}fromJSON($){this.clear();for(let[Z,J]of $)this.set(Z,J)}}sO.LinkedMap=zU;class oO extends zU{constructor($,Z=1){super();this._limit=$,this._ratio=Math.min(Math.max(0,Z),1)}get limit(){return this._limit}set limit($){this._limit=$,this.checkTrim()}get ratio(){return this._ratio}set ratio($){this._ratio=Math.min(Math.max(0,$),1),this.checkTrim()}get($,Z=g$.AsNew){return super.get($,Z)}peek($){return super.get($,g$.None)}set($,Z){return super.set($,Z,g$.Last),this.checkTrim(),this}checkTrim(){if(this.size>this._limit)this.trimOld(Math.round(this._limit*this._ratio))}}sO.LRUCache=oO});var $q=S((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});tO.Disposable=void 0;var aO;(function($){function Z(J){return{dispose:J}}$.create=Z})(aO||(tO.Disposable=aO={}))});var DZ=S((Zq)=>{Object.defineProperty(Zq,"__esModule",{value:!0});var AU;function OU(){if(AU===void 0)throw Error("No runtime abstraction layer installed");return AU}(function($){function Z(J){if(J===void 0)throw Error("No runtime abstraction layer provided");AU=J}$.install=Z})(OU||(OU={}));Zq.default=OU});var T7=S((Xq)=>{Object.defineProperty(Xq,"__esModule",{value:!0});Xq.Emitter=Xq.Event=void 0;var fp=DZ(),Jq;(function($){let Z={dispose(){}};$.None=function(){return Z}})(Jq||(Xq.Event=Jq={}));class Yq{add($,Z=null,J){if(!this._callbacks)this._callbacks=[],this._contexts=[];if(this._callbacks.push($),this._contexts.push(Z),Array.isArray(J))J.push({dispose:()=>this.remove($,Z)})}remove($,Z=null){if(!this._callbacks)return;let J=!1;for(let Y=0,X=this._callbacks.length;Y<X;Y++)if(this._callbacks[Y]===$)if(this._contexts[Y]===Z){this._callbacks.splice(Y,1),this._contexts.splice(Y,1);return}else J=!0;if(J)throw Error("When adding a listener with a context, you should remove it with the same context")}invoke(...$){if(!this._callbacks)return[];let Z=[],J=this._callbacks.slice(0),Y=this._contexts.slice(0);for(let X=0,Q=J.length;X<Q;X++)try{Z.push(J[X].apply(Y[X],$))}catch(G){(0,fp.default)().console.error(G)}return Z}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}}class N9{constructor($){this._options=$}get event(){if(!this._event)this._event=($,Z,J)=>{if(!this._callbacks)this._callbacks=new Yq;if(this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty())this._options.onFirstListenerAdd(this);this._callbacks.add($,Z);let Y={dispose:()=>{if(!this._callbacks)return;if(this._callbacks.remove($,Z),Y.dispose=N9._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty())this._options.onLastListenerRemove(this)}};if(Array.isArray(J))J.push(Y);return Y};return this._event}fire($){if(this._callbacks)this._callbacks.invoke.call(this._callbacks,$)}dispose(){if(this._callbacks)this._callbacks.dispose(),this._callbacks=void 0}}Xq.Emitter=N9;N9._noop=function(){}});var M9=S((Wq)=>{Object.defineProperty(Wq,"__esModule",{value:!0});Wq.CancellationTokenSource=Wq.CancellationToken=void 0;var vp=DZ(),yp=L7(),qU=T7(),j9;(function($){$.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:qU.Event.None}),$.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:qU.Event.None});function Z(J){let Y=J;return Y&&(Y===$.None||Y===$.Cancelled||yp.boolean(Y.isCancellationRequested)&&!!Y.onCancellationRequested)}$.is=Z})(j9||(Wq.CancellationToken=j9={}));var xp=Object.freeze(function($,Z){let J=(0,vp.default)().timer.setTimeout($.bind(Z),0);return{dispose(){J.dispose()}}});class NU{constructor(){this._isCancelled=!1}cancel(){if(!this._isCancelled){if(this._isCancelled=!0,this._emitter)this._emitter.fire(void 0),this.dispose()}}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){if(this._isCancelled)return xp;if(!this._emitter)this._emitter=new qU.Emitter;return this._emitter.event}dispose(){if(this._emitter)this._emitter.dispose(),this._emitter=void 0}}class Gq{get token(){if(!this._token)this._token=new NU;return this._token}cancel(){if(!this._token)this._token=j9.Cancelled;else this._token.cancel()}dispose(){if(!this._token)this._token=j9.None;else if(this._token instanceof NU)this._token.dispose()}}Wq.CancellationTokenSource=Gq});var Aq=S((zq)=>{Object.defineProperty(zq,"__esModule",{value:!0});zq.SharedArrayReceiverStrategy=zq.SharedArraySenderStrategy=void 0;var gp=M9(),CY;(function($){$.Continue=0,$.Cancelled=1})(CY||(CY={}));class Uq{constructor(){this.buffers=new Map}enableCancellation($){if($.id===null)return;let Z=new SharedArrayBuffer(4),J=new Int32Array(Z,0,1);J[0]=CY.Continue,this.buffers.set($.id,Z),$.$cancellationData=Z}async sendCancellation($,Z){let J=this.buffers.get(Z);if(J===void 0)return;let Y=new Int32Array(J,0,1);Atomics.store(Y,0,CY.Cancelled)}cleanup($){this.buffers.delete($)}dispose(){this.buffers.clear()}}zq.SharedArraySenderStrategy=Uq;class Vq{constructor($){this.data=new Int32Array($,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===CY.Cancelled}get onCancellationRequested(){throw Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}}class Hq{constructor($){this.token=new Vq($)}cancel(){}dispose(){}}class Bq{constructor(){this.kind="request"}createCancellationTokenSource($){let Z=$.$cancellationData;if(Z===void 0)return new gp.CancellationTokenSource;return new Hq(Z)}}zq.SharedArrayReceiverStrategy=Bq});var jU=S((qq)=>{Object.defineProperty(qq,"__esModule",{value:!0});qq.Semaphore=void 0;var mp=DZ();class Oq{constructor($=1){if($<=0)throw Error("Capacity must be greater than 0");this._capacity=$,this._active=0,this._waiting=[]}lock($){return new Promise((Z,J)=>{this._waiting.push({thunk:$,resolve:Z,reject:J}),this.runNext()})}get active(){return this._active}runNext(){if(this._waiting.length===0||this._active===this._capacity)return;(0,mp.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let $=this._waiting.shift();if(this._active++,this._active>this._capacity)throw Error("To many thunks active");try{let Z=$.thunk();if(Z instanceof Promise)Z.then((J)=>{this._active--,$.resolve(J),this.runNext()},(J)=>{this._active--,$.reject(J),this.runNext()});else this._active--,$.resolve(Z),this.runNext()}catch(Z){this._active--,$.reject(Z),this.runNext()}}}qq.Semaphore=Oq});var Lq=S((Dq)=>{Object.defineProperty(Dq,"__esModule",{value:!0});Dq.ReadableStreamMessageReader=Dq.AbstractMessageReader=Dq.MessageReader=void 0;var DU=DZ(),R7=L7(),MU=T7(),lp=jU(),jq;(function($){function Z(J){let Y=J;return Y&&R7.func(Y.listen)&&R7.func(Y.dispose)&&R7.func(Y.onError)&&R7.func(Y.onClose)&&R7.func(Y.onPartialMessage)}$.is=Z})(jq||(Dq.MessageReader=jq={}));class LU{constructor(){this.errorEmitter=new MU.Emitter,this.closeEmitter=new MU.Emitter,this.partialMessageEmitter=new MU.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($){this.errorEmitter.fire(this.asError($))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage($){this.partialMessageEmitter.fire($)}asError($){if($ instanceof Error)return $;else return Error(`Reader received error. Reason: ${R7.string($.message)?$.message:"unknown"}`)}}Dq.AbstractMessageReader=LU;var wU;(function($){function Z(J){let Y,X,Q,G=new Map,W,K=new Map;if(J===void 0||typeof J==="string")Y=J??"utf-8";else{if(Y=J.charset??"utf-8",J.contentDecoder!==void 0)Q=J.contentDecoder,G.set(Q.name,Q);if(J.contentDecoders!==void 0)for(let U of J.contentDecoders)G.set(U.name,U);if(J.contentTypeDecoder!==void 0)W=J.contentTypeDecoder,K.set(W.name,W);if(J.contentTypeDecoders!==void 0)for(let U of J.contentTypeDecoders)K.set(U.name,U)}if(W===void 0)W=(0,DU.default)().applicationJson.decoder,K.set(W.name,W);return{charset:Y,contentDecoder:Q,contentDecoders:G,contentTypeDecoder:W,contentTypeDecoders:K}}$.fromOptions=Z})(wU||(wU={}));class Mq extends LU{constructor($,Z){super();this.readable=$,this.options=wU.fromOptions(Z),this.buffer=(0,DU.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new lp.Semaphore(1)}set partialMessageTimeout($){this._partialMessageTimeout=$}get partialMessageTimeout(){return this._partialMessageTimeout}listen($){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=$;let Z=this.readable.onData((J)=>{this.onData(J)});return this.readable.onError((J)=>this.fireError(J)),this.readable.onClose(()=>this.fireClose()),Z}onData($){try{this.buffer.append($);while(!0){if(this.nextMessageLength===-1){let J=this.buffer.tryReadHeaders(!0);if(!J)return;let Y=J.get("content-length");if(!Y){this.fireError(Error(`Header must provide a Content-Length property.
|
|
3
3
|
${JSON.stringify(Object.fromEntries(J))}`));return}let X=parseInt(Y);if(isNaN(X)){this.fireError(Error(`Content-Length value must be a number. Got ${Y}`));return}this.nextMessageLength=X}let Z=this.buffer.tryReadBody(this.nextMessageLength);if(Z===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let J=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(Z):Z,Y=await this.options.contentTypeDecoder.decode(J,this.options);this.callback(Y)}).catch((J)=>{this.fireError(J)})}}catch(Z){this.fireError(Z)}}clearPartialMessageTimer(){if(this.partialMessageTimer)this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0}setPartialMessageTimer(){if(this.clearPartialMessageTimer(),this._partialMessageTimeout<=0)return;this.partialMessageTimer=(0,DU.default)().timer.setTimeout(($,Z)=>{if(this.partialMessageTimer=void 0,$===this.messageToken)this.firePartialMessage({messageToken:$,waitingTime:Z}),this.setPartialMessageTimer()},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout)}}Dq.ReadableStreamMessageReader=Mq});var _q=S((Cq)=>{Object.defineProperty(Cq,"__esModule",{value:!0});Cq.WriteableStreamMessageWriter=Cq.AbstractMessageWriter=Cq.MessageWriter=void 0;var Tq=DZ(),bY=L7(),cp=jU(),Rq=T7(),ip="Content-Length: ",Pq=`\r
|
|
4
4
|
`,Iq;(function($){function Z(J){let Y=J;return Y&&bY.func(Y.dispose)&&bY.func(Y.onClose)&&bY.func(Y.onError)&&bY.func(Y.write)}$.is=Z})(Iq||(Cq.MessageWriter=Iq={}));class RU{constructor(){this.errorEmitter=new Rq.Emitter,this.closeEmitter=new Rq.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError($,Z,J){this.errorEmitter.fire([this.asError($),Z,J])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError($){if($ instanceof Error)return $;else return Error(`Writer received error. Reason: ${bY.string($.message)?$.message:"unknown"}`)}}Cq.AbstractMessageWriter=RU;var TU;(function($){function Z(J){if(J===void 0||typeof J==="string")return{charset:J??"utf-8",contentTypeEncoder:(0,Tq.default)().applicationJson.encoder};else return{charset:J.charset??"utf-8",contentEncoder:J.contentEncoder,contentTypeEncoder:J.contentTypeEncoder??(0,Tq.default)().applicationJson.encoder}}$.fromOptions=Z})(TU||(TU={}));class Eq extends RU{constructor($,Z){super();this.writable=$,this.options=TU.fromOptions(Z),this.errorCount=0,this.writeSemaphore=new cp.Semaphore(1),this.writable.onError((J)=>this.fireError(J)),this.writable.onClose(()=>this.fireClose())}async write($){return this.writeSemaphore.lock(async()=>{return this.options.contentTypeEncoder.encode($,this.options).then((J)=>{if(this.options.contentEncoder!==void 0)return this.options.contentEncoder.encode(J);else return J}).then((J)=>{let Y=[];return Y.push(ip,J.byteLength.toString(),Pq),Y.push(Pq),this.doWrite($,Y,J)},(J)=>{throw this.fireError(J),J})})}async doWrite($,Z,J){try{return await this.writable.write(Z.join(""),"ascii"),this.writable.write(J)}catch(Y){return this.handleError(Y,$),Promise.reject(Y)}}handleError($,Z){this.errorCount++,this.fireError($,Z,this.errorCount)}end(){this.writable.end()}}Cq.WriteableStreamMessageWriter=Eq});var vq=S((fq)=>{Object.defineProperty(fq,"__esModule",{value:!0});fq.AbstractMessageBuffer=void 0;var sp=13,rp=10,ap=`\r
|
|
5
5
|
`;class Sq{constructor($="utf-8"){this._encoding=$,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append($){let Z=typeof $==="string"?this.fromString($,this._encoding):$;this._chunks.push(Z),this._totalLength+=Z.byteLength}tryReadHeaders($=!1){if(this._chunks.length===0)return;let Z=0,J=0,Y=0,X=0;$:while(J<this._chunks.length){let K=this._chunks[J];Y=0;Z:while(Y<K.length){switch(K[Y]){case sp:switch(Z){case 0:Z=1;break;case 2:Z=3;break;default:Z=0}break;case rp:switch(Z){case 1:Z=2;break;case 3:Z=4,Y++;break $;default:Z=0}break;default:Z=0}Y++}X+=K.byteLength,J++}if(Z!==4)return;let Q=this._read(X+Y),G=new Map,W=this.toString(Q,"ascii").split(ap);if(W.length<2)return G;for(let K=0;K<W.length-2;K++){let U=W[K],V=U.indexOf(":");if(V===-1)throw Error(`Message header must separate key and value using ':'
|
|
@@ -485,7 +485,7 @@ ${J}`);Z.destroy($)}function Uu($){if(typeof $!=="function")throw new Gu(typeof
|
|
|
485
485
|
`})}UK.prototype.incr=function($,Z,J,Y){this.redis.rateLimit(this.key+$,J,Y,this.continueExceeding,this.exponentialBackoff,(X,Q)=>{X?Z(X,null):Z(null,{current:Q[0],ttl:Q[1]})})};UK.prototype.child=function($){return new UK($.continueExceeding,$.exponentialBackoff,this.redis,`${this.key}${$.routeInfo.method}${$.routeInfo.url}-`)};Du.exports=UK});var Cu=S((Jh0,VK)=>{var Sq0=qu(),{parse:Ru,format:fq0}=Nu(),kq0=Mu(),vq0=wu(),yq0={rateLimit:"x-ratelimit-limit",rateRemaining:"x-ratelimit-remaining",rateReset:"x-ratelimit-reset",retryAfter:"retry-after"},xq0={rateLimit:"ratelimit-limit",rateRemaining:"ratelimit-remaining",rateReset:"ratelimit-reset",retryAfter:"retry-after"},VA=()=>{},hq0=($)=>$.ip,gq0=($,Z)=>{let J=Error(`Rate limit exceeded, retry in ${Z.after}`);return J.statusCode=Z.statusCode,J};async function HA($,Z){let J={global:typeof Z.global==="boolean"?Z.global:!0};if(typeof Z.enableDraftSpec==="boolean"&&Z.enableDraftSpec)J.enableDraftSpec=!0,J.labels=xq0;else J.enableDraftSpec=!1,J.labels=yq0;if(J.addHeaders=Object.assign({[J.labels.rateLimit]:!0,[J.labels.rateRemaining]:!0,[J.labels.rateReset]:!0,[J.labels.retryAfter]:!0},Z.addHeaders),J.addHeadersOnExceeding=Object.assign({[J.labels.rateLimit]:!0,[J.labels.rateRemaining]:!0,[J.labels.rateReset]:!0},Z.addHeadersOnExceeding),Number.isFinite(Z.max)&&Z.max>=0)J.max=Math.trunc(Z.max);else if(typeof Z.max==="function")J.max=Z.max;else J.max=1000;if(Number.isFinite(Z.timeWindow)&&Z.timeWindow>=0)J.timeWindow=Math.trunc(Z.timeWindow);else if(typeof Z.timeWindow==="string")J.timeWindow=Ru(Z.timeWindow);else if(typeof Z.timeWindow==="function")J.timeWindow=Z.timeWindow;else J.timeWindow=60000;if(J.hook=Z.hook||"onRequest",J.allowList=Z.allowList||Z.whitelist||null,J.ban=Number.isFinite(Z.ban)&&Z.ban>=0?Math.trunc(Z.ban):-1,J.onBanReach=typeof Z.onBanReach==="function"?Z.onBanReach:VA,J.onExceeding=typeof Z.onExceeding==="function"?Z.onExceeding:VA,J.onExceeded=typeof Z.onExceeded==="function"?Z.onExceeded:VA,J.continueExceeding=typeof Z.continueExceeding==="boolean"?Z.continueExceeding:!1,J.exponentialBackoff=typeof Z.exponentialBackoff==="boolean"?Z.exponentialBackoff:!1,J.keyGenerator=typeof Z.keyGenerator==="function"?Z.keyGenerator:hq0,typeof Z.errorResponseBuilder==="function")J.errorResponseBuilder=Z.errorResponseBuilder,J.isCustomErrorMessage=!0;else J.errorResponseBuilder=gq0,J.isCustomErrorMessage=!1;J.skipOnError=typeof Z.skipOnError==="boolean"?Z.skipOnError:!1;let Y={rateLimitRan:Symbol("fastify.request.rateLimitRan"),store:null};if(Z.store){let X=Z.store;Y.store=new X(J)}else if(Z.redis)Y.store=new vq0(J.continueExceeding,J.exponentialBackoff,Z.redis,Z.nameSpace);else Y.store=new kq0(J.continueExceeding,J.exponentialBackoff,Z.cache);if($.decorateRequest(Y.rateLimitRan,!1),!$.hasDecorator("createRateLimit"))$.decorate("createRateLimit",(X)=>{let Q=Lu(Y,J,X);return(G)=>Iu.apply(this,Q.concat(G))});if(!$.hasDecorator("rateLimit"))$.decorate("rateLimit",(X)=>{let Q=Lu(Y,J,X);return Eu(...Q)});$.addHook("onRoute",(X)=>{if(X.config?.rateLimit!=null){if(typeof X.config.rateLimit==="object"){let Q=Object.create(Y),G=Pu(J,X.config.rateLimit,{routeInfo:X});Q.store=Y.store.child(G),Tu(Q,G,X)}else if(X.config.rateLimit!==!1)throw Error("Unknown value for route rate-limit configuration")}else if(J.global)Tu(Y,J,X)})}function Pu(...$){let Z=Object.assign({},...$);if(Number.isFinite(Z.timeWindow)&&Z.timeWindow>=0)Z.timeWindow=Math.trunc(Z.timeWindow);else if(typeof Z.timeWindow==="string")Z.timeWindow=Ru(Z.timeWindow);else if(typeof Z.timeWindow!=="function")Z.timeWindow=60000;if(Number.isFinite(Z.max)&&Z.max>=0)Z.max=Math.trunc(Z.max);else if(typeof Z.max!=="function")Z.max=1000;if(Number.isFinite(Z.ban)&&Z.ban>=0)Z.ban=Math.trunc(Z.ban);else Z.ban=-1;if(Z.groupId!==void 0&&typeof Z.groupId!=="string")throw Error("groupId must be a string");return Z}function Lu($,Z,J){if(typeof J==="object"){let Y=Object.create($),X=Pu(Z,J,{routeInfo:{}});return Y.store=Y.store.child(X),[Y,X]}return[$,Z]}function Tu($,Z,J){let Y=Z.hook,X=Eu($,Z);if(Array.isArray(J[Y]))J[Y].push(X);else if(typeof J[Y]==="function")J[Y]=[J[Y],X];else J[Y]=[X]}async function Iu($,Z,J){let{store:Y}=$,X=await Z.keyGenerator(J),Q=J.routeOptions.config?.rateLimit?.groupId;if(Q)X+=Q;if(Z.allowList){if(typeof Z.allowList==="function"){if(await Z.allowList(J,X))return{isAllowed:!0,key:X}}else if(Z.allowList.indexOf(X)!==-1)return{isAllowed:!0,key:X}}let G=typeof Z.max==="number"?Z.max:await Z.max(J,X),W=typeof Z.timeWindow==="number"?Z.timeWindow:await Z.timeWindow(J,X),K=0,U=0,V=0;try{let H=await new Promise((B,z)=>{Y.incr(X,(F,A)=>{F?z(F):B(A)},W,G)});K=H.current,U=H.ttl,V=Math.ceil(H.ttl/1000)}catch(H){if(!Z.skipOnError)throw H}return{isAllowed:!1,key:X,max:G,timeWindow:W,remaining:Math.max(0,G-K),ttl:U,ttlInSeconds:V,isExceeded:K>G,isBanned:Z.ban!==-1&&K-G>Z.ban}}function Eu($,Z){let{rateLimitRan:J}=$;return async(Y,X)=>{if(Y[J])return;Y[J]=!0;let Q=await Iu($,Z,Y);if(Q.isAllowed)return;let{key:G,max:W,remaining:K,ttl:U,ttlInSeconds:V,isExceeded:H,isBanned:B}=Q;if(!H){if(Z.addHeadersOnExceeding[Z.labels.rateLimit])X.header(Z.labels.rateLimit,W);if(Z.addHeadersOnExceeding[Z.labels.rateRemaining])X.header(Z.labels.rateRemaining,K);if(Z.addHeadersOnExceeding[Z.labels.rateReset])X.header(Z.labels.rateReset,V);Z.onExceeding(Y,G);return}if(Z.onExceeded(Y,G),Z.addHeaders[Z.labels.rateLimit])X.header(Z.labels.rateLimit,W);if(Z.addHeaders[Z.labels.rateRemaining])X.header(Z.labels.rateRemaining,0);if(Z.addHeaders[Z.labels.rateReset])X.header(Z.labels.rateReset,V);if(Z.addHeaders[Z.labels.retryAfter])X.header(Z.labels.retryAfter,V);let z={statusCode:429,ban:!1,max:W,ttl:U,after:fq0(V*1000,!0)};if(B)z.statusCode=403,z.ban=!0,Z.onBanReach(Y,G);throw Z.errorResponseBuilder(Y,z)}}VK.exports=Sq0(HA,{fastify:"5.x",name:"@fastify/rate-limit"});VK.exports.default=HA;VK.exports.fastifyRateLimit=HA});var Tm=S((Lm,OK)=>{(($,Z)=>{if(typeof define==="function"&&define.amd)define([],Z);else if(typeof OK==="object"&&OK.exports)OK.exports=Z();else $.fuzzysort=Z()})(Lm,($)=>{var Z=(u,l)=>{if(!u||!l)return r;var $0=z(u);if(!g(l))l=B(l);var v=$0.bitflags;if((v&l._bitflags)!==v)return r;return A($0,l)},J=(u,l,$0)=>{if(!u)return $0?.all?F(l,$0):t;var v=z(u),h=v.bitflags,c=v.containsSpace,m=V($0?.threshold||0),a=$0?.limit||d,e=0,H0=0,A0=l.length;function P0(x){if(e<a)h0.add(x),++e;else if(++H0,x._score>h0.peek()._score)h0.replaceTop(x)}if($0?.key){var s0=$0.key;for(var o=0;o<A0;++o){var K0=l[o],z0=k(K0,s0);if(!z0)continue;if(!g(z0))z0=B(z0);if((h&z0._bitflags)!==h)continue;var N0=A(v,z0);if(N0===r)continue;if(N0._score<m)continue;N0.obj=K0,P0(N0)}}else if($0?.keys){var Q1=$0.keys,_0=Q1.length;$:for(var o=0;o<A0;++o){var K0=l[o];{var e0=0;for(var S0=0;S0<_0;++S0){var s0=Q1[S0],z0=k(K0,s0);if(!z0){b[S0]=G0;continue}if(!g(z0))z0=B(z0);b[S0]=z0,e0|=z0._bitflags}if((h&e0)!==h)continue}if(c)for(let n=0;n<v.spaceSearches.length;n++)C[n]=p;for(var S0=0;S0<_0;++S0){if(z0=b[S0],z0===G0){y[S0]=G0;continue}if(y[S0]=A(v,z0,!1,c),y[S0]===r){y[S0]=G0;continue}if(c)for(let J0=0;J0<v.spaceSearches.length;J0++){if(f[J0]>-1000){if(C[J0]>p){var E1=(C[J0]+f[J0])/4;if(E1>C[J0])C[J0]=E1}}if(f[J0]>C[J0])C[J0]=f[J0]}}if(c){for(let n=0;n<v.spaceSearches.length;n++)if(C[n]===p)continue $}else{var n0=!1;for(let n=0;n<_0;n++)if(y[n]._score!==p){n0=!0;break}if(!n0)continue}var F1=new W(_0);for(let n=0;n<_0;n++)F1[n]=y[n];if(c){var a0=0;for(let n=0;n<v.spaceSearches.length;n++)a0+=C[n]}else{var a0=p;for(let J0=0;J0<_0;J0++){var N0=F1[J0];if(N0._score>-1000){if(a0>p){var E1=(a0+N0._score)/4;if(E1>a0)a0=E1}}if(N0._score>a0)a0=N0._score}}if(F1.obj=K0,F1._score=a0,$0?.scoreFn){if(a0=$0.scoreFn(F1),!a0)continue;a0=V(a0),F1._score=a0}if(a0<m)continue;P0(F1)}}else for(var o=0;o<A0;++o){var z0=l[o];if(!z0)continue;if(!g(z0))z0=B(z0);if((h&z0._bitflags)!==h)continue;var N0=A(v,z0);if(N0===r)continue;if(N0._score<m)continue;P0(N0)}if(e===0)return t;var V1=Array(e);for(var o=e-1;o>=0;--o)V1[o]=h0.poll();return V1.total=e+H0,V1},Y=(u,l="<b>",$0="</b>")=>{var v=typeof l==="function"?l:void 0,h=u.target,c=h.length,m=u.indexes,a="",e=0,H0=0,A0=!1,P0=[];for(var s0=0;s0<c;++s0){var o=h[s0];if(m[H0]===s0){if(++H0,!A0)if(A0=!0,v)P0.push(a),a="";else a+=l;if(H0===m.length){if(v)a+=o,P0.push(v(a,e++)),a="",P0.push(h.substr(s0+1));else a+=o+$0+h.substr(s0+1);break}}else if(A0)if(A0=!1,v)P0.push(v(a,e++)),a="";else a+=$0;a+=o}return v?P0:a},X=(u)=>{if(typeof u==="number")u=""+u;else if(typeof u!=="string")u="";var l=w(u);return K(u,{_targetLower:l._lower,_targetLowerCodes:l.lowerCodes,_bitflags:l.bitflags})},Q=()=>{E.clear(),R.clear()};class G{get["indexes"](){return this._indexes.slice(0,this._indexes.len).sort((u,l)=>u-l)}set["indexes"](u){return this._indexes=u}["highlight"](u,l){return Y(this,u,l)}get["score"](){return U(this._score)}set["score"](u){this._score=V(u)}}class W extends Array{get["score"](){return U(this._score)}set["score"](u){this._score=V(u)}}var K=(u,l)=>{let $0=new G;return $0.target=u,$0.obj=l.obj??r,$0._score=l._score??p,$0._indexes=l._indexes??[],$0._targetLower=l._targetLower??"",$0._targetLowerCodes=l._targetLowerCodes??r,$0._nextBeginningIndexes=l._nextBeginningIndexes??r,$0._bitflags=l._bitflags??0,$0},U=(u)=>{if(u===p)return 0;if(u>1)return u;return Math.E**(((-u+1)**0.04307-1)*-2)},V=(u)=>{if(u===0)return p;if(u>1)return u;return 1-Math.pow(Math.log(u)/-2+1,23.218017181332716)},H=(u)=>{if(typeof u==="number")u=""+u;else if(typeof u!=="string")u="";u=u.trim();var l=w(u),$0=[];if(l.containsSpace){var v=u.split(/\s+/);v=[...new Set(v)];for(var h=0;h<v.length;h++){if(v[h]==="")continue;var c=w(v[h]);$0.push({lowerCodes:c.lowerCodes,_lower:v[h].toLowerCase(),containsSpace:!1})}}return{lowerCodes:l.lowerCodes,_lower:l._lower,containsSpace:l.containsSpace,bitflags:l.bitflags,spaceSearches:$0}},B=(u)=>{if(u.length>999)return X(u);var l=E.get(u);if(l!==void 0)return l;return l=X(u),E.set(u,l),l},z=(u)=>{if(u.length>999)return H(u);var l=R.get(u);if(l!==void 0)return l;return l=H(u),R.set(u,l),l},F=(u,l)=>{var $0=[];$0.total=u.length;var v=l?.limit||d;if(l?.key)for(var h=0;h<u.length;h++){var c=u[h],m=k(c,l.key);if(m==r)continue;if(!g(m))m=B(m);var a=K(m.target,{_score:m._score,obj:c});if($0.push(a),$0.length>=v)return $0}else if(l?.keys)for(var h=0;h<u.length;h++){var c=u[h],e=new W(l.keys.length);for(var H0=l.keys.length-1;H0>=0;--H0){var m=k(c,l.keys[H0]);if(!m){e[H0]=G0;continue}if(!g(m))m=B(m);m._score=p,m._indexes.len=0,e[H0]=m}if(e.obj=c,e._score=p,$0.push(e),$0.length>=v)return $0}else for(var h=0;h<u.length;h++){var m=u[h];if(m==r)continue;if(!g(m))m=B(m);if(m._score=p,m._indexes.len=0,$0.push(m),$0.length>=v)return $0}return $0},A=(u,l,$0=!1,v=!1)=>{if($0===!1&&u.containsSpace)return N(u,l,v);var{_lower:h,lowerCodes:c}=u,m=c[0],a=l._targetLowerCodes,e=c.length,H0=a.length,o=0,A0=0,P0=0;for(;;){var s0=m===a[A0];if(s0){if(T[P0++]=A0,++o,o===e)break;m=c[o]}if(++A0,A0>=H0)return r}var o=0,K0=!1,z0=0,N0=l._nextBeginningIndexes;if(N0===r)N0=l._nextBeginningIndexes=M(l.target);A0=T[0]===0?0:N0[T[0]-1];var Q1=0;if(A0!==H0)for(;;)if(A0>=H0){if(o<=0)break;if(++Q1,Q1>200)break;--o;var _0=P[--z0];A0=N0[_0]}else{var s0=c[o]===a[A0];if(s0){if(P[z0++]=A0,++o,o===e){K0=!0;break}++A0}else A0=N0[A0]}var e0=e<=1?-1:l._targetLower.indexOf(h,T[0]),S0=!!~e0,E1=!S0?!1:e0===0||l._nextBeginningIndexes[e0-1]===e0;if(S0&&!E1)for(var n0=0;n0<N0.length;n0=N0[n0]){if(n0<=e0)continue;for(var F1=0;F1<e;F1++)if(c[F1]!==l._targetLowerCodes[n0+F1])break;if(F1===e){e0=n0,E1=!0;break}}var a0=(n)=>{var J0=0,E0=0;for(var M0=1;M0<e;++M0)if(n[M0]-n[M0-1]!==1)J0-=n[M0],++E0;var D1=n[e-1]-n[0]-(e-1);if(J0-=(12+D1)*E0,n[0]!==0)J0-=n[0]*n[0]*0.2;if(!K0)J0*=1000;else{var g0=1;for(var M0=N0[0];M0<H0;M0=N0[M0])++g0;if(g0>24)J0*=(g0-24)*10}if(J0-=(H0-e)/2,S0)J0/=1+e*e*1;if(E1)J0/=1+e*e*1;return J0-=(H0-e)/2,J0};if(!K0){if(S0)for(var n0=0;n0<e;++n0)T[n0]=e0+n0;var V1=T,x=a0(V1)}else if(E1){for(var n0=0;n0<e;++n0)T[n0]=e0+n0;var V1=T,x=a0(T)}else var V1=P,x=a0(P);l._score=x;for(var n0=0;n0<e;++n0)l._indexes[n0]=V1[n0];l._indexes.len=e;let i=new G;return i.target=l.target,i._score=l._score,i._indexes=l._indexes,i},N=(u,l,$0)=>{var v=new Set,h=0,c=r,m=0,a=u.spaceSearches,e=a.length,H0=0,A0=()=>{for(let E1=H0-1;E1>=0;E1--)l._nextBeginningIndexes[_[E1*2+0]]=_[E1*2+1]},P0=!1;for(var S0=0;S0<e;++S0){f[S0]=p;var s0=a[S0];if(c=A(s0,l),$0){if(c===r)continue;P0=!0}else if(c===r)return A0(),r;var o=S0===e-1;if(!o){var K0=c._indexes,z0=!0;for(let n0=0;n0<K0.len-1;n0++)if(K0[n0+1]-K0[n0]!==1){z0=!1;break}if(z0){var N0=K0[K0.len-1]+1,Q1=l._nextBeginningIndexes[N0-1];for(let n0=N0-1;n0>=0;n0--){if(Q1!==l._nextBeginningIndexes[n0])break;l._nextBeginningIndexes[n0]=N0,_[H0*2+0]=n0,_[H0*2+1]=Q1,H0++}}}if(h+=c._score/e,f[S0]=c._score/e,c._indexes[0]<m)h-=(m-c._indexes[0])*2;m=c._indexes[0];for(var _0=0;_0<c._indexes.len;++_0)v.add(c._indexes[_0])}if($0&&!P0)return r;A0();var e0=A(u,l,!0);if(e0!==r&&e0._score>h){if($0)for(var S0=0;S0<e;++S0)f[S0]=e0._score/e;return e0}if($0)c=l;c._score=h;var S0=0;for(let E1 of v)c._indexes[S0++]=E1;return c._indexes.len=S0,c},j=(u)=>u.replace(/\p{Script=Latin}+/gu,(l)=>l.normalize("NFD")).replace(/[\u0300-\u036f]/g,""),w=(u)=>{u=j(u);var l=u.length,$0=u.toLowerCase(),v=[],h=0,c=!1;for(var m=0;m<l;++m){var a=v[m]=$0.charCodeAt(m);if(a===32){c=!0;continue}var e=a>=97&&a<=122?a-97:a>=48&&a<=57?26:a<=127?30:31;h|=1<<e}return{lowerCodes:v,bitflags:h,containsSpace:c,_lower:$0}},q=(u)=>{var l=u.length,$0=[],v=0,h=!1,c=!1;for(var m=0;m<l;++m){var a=u.charCodeAt(m),e=a>=65&&a<=90,H0=e||a>=97&&a<=122||a>=48&&a<=57,A0=e&&!h||!c||!H0;if(h=e,c=H0,A0)$0[v++]=m}return $0},M=(u)=>{u=j(u);var l=u.length,$0=q(u),v=[],h=$0[0],c=0;for(var m=0;m<l;++m)if(h>m)v[m]=h;else h=$0[++c],v[m]=h===void 0?l:h;return v},E=new Map,R=new Map,T=[],P=[],_=[],C=[],f=[],b=[],y=[],k=(u,l)=>{var $0=u[l];if($0!==void 0)return $0;if(typeof l==="function")return l(u);var v=l;if(!Array.isArray(l))v=l.split(".");var h=v.length,c=-1;while(u&&++c<h)u=u[v[c]];return u},g=(u)=>{return typeof u==="object"&&typeof u._bitflags==="number"},d=1/0,p=-d,t=[];t.total=0;var r=null,G0=X(""),O0=(u)=>{var l=[],$0=0,v={},h=(c)=>{for(var m=0,a=l[m],e=1;e<$0;){var H0=e+1;m=e,H0<$0&&l[H0]._score<l[e]._score&&(m=H0),l[m-1>>1]=l[m],e=1+(m<<1)}for(var A0=m-1>>1;m>0&&a._score<l[A0]._score;A0=(m=A0)-1>>1)l[m]=l[A0];l[m]=a};return v.add=(c)=>{var m=$0;l[$0++]=c;for(var a=m-1>>1;m>0&&c._score<l[a]._score;a=(m=a)-1>>1)l[m]=l[a];l[m]=c},v.poll=(c)=>{if($0!==0){var m=l[0];return l[0]=l[--$0],h(),m}},v.peek=(c)=>{if($0!==0)return l[0]},v.replaceTop=(c)=>{l[0]=c,h()},v},h0=O0();return{single:Z,go:J,prepare:X,cleanup:Q}})});var $9={};B1($9,{toRow:()=>DM0,plan:()=>fM0,listGlobal:()=>yM0,list:()=>vM0,layer:()=>qd,isDefaultTitle:()=>MM0,getUsage:()=>kM0,fromRow:()=>AY,defaultLayer:()=>mM0,SetTitleInput:()=>EM0,SetRevertInput:()=>_M0,SetPermissionInput:()=>bM0,SetArchivedInput:()=>CM0,Service:()=>oK,RemoveInput:()=>IM0,ProjectInfo:()=>Fd,MessagesInput:()=>SM0,Info:()=>B6,GlobalInfo:()=>wM0,GetInput:()=>RM0,ForkInput:()=>TM0,Event:()=>OY,CreateInput:()=>LM0,ChildrenInput:()=>PM0,BusyError:()=>Od});var YU;((dM0)=>{let $=["brave","calm","clever","cosmic","crisp","curious","eager","gentle","glowing","happy","hidden","jolly","kind","lucky","mighty","misty","neon","nimble","playful","proud","quick","quiet","shiny","silent","stellar","sunny","swift","tidy","witty"],Z=["cabin","cactus","canyon","circuit","comet","eagle","engine","falcon","forest","garden","harbor","island","knight","lagoon","meadow","moon","mountain","nebula","orchid","otter","panda","pixel","planet","river","rocket","sailor","squid","star","tiger","wizard","wolf"];function J(){return[$[Math.floor(Math.random()*$.length)],Z[Math.floor(Math.random()*Z.length)]].join("-")}dM0.create=J})(YU||={});var l1={};B1(l1,{subscribeAll:()=>Cd,subscribe:()=>Ed,publish:()=>Id,layer:()=>XU,defaultLayer:()=>Rd,Service:()=>PY,InstanceDisposed:()=>VO,Bus:()=>l1});var jZ=C0.create({service:"bus"}),VO=L1.define("server.instance.disposed",I.object({directory:I.string()}));class PY extends S1.Service()("@qitqode/Bus"){}var XU=T0.effect(PY,L.gen(function*(){let $=yield*B0.make(L.fn("Bus.state")(function*(K){let U=yield*v6.unbounded(),V=new Map;return yield*L.addFinalizer(()=>L.gen(function*(){yield*v6.publish(U,{type:VO.type,properties:{directory:K.directory}}),yield*v6.shutdown(U);for(let H of V.values())yield*v6.shutdown(H)})),{wildcard:U,typed:V}}));function Z(K,U){return L.gen(function*(){let V=K.typed.get(U.type);if(!V)V=yield*v6.unbounded(),K.typed.set(U.type,V);return V})}function J(K,U){return L.gen(function*(){let V=yield*B0.get($),H={type:K.type,properties:U};jZ.debug("publishing",{type:K.type});let B=V.typed.get(K.type);if(B)yield*v6.publish(B,H);yield*v6.publish(V.wildcard,H);let z=yield*B0.directory,F=yield*B0.context,A=yield*B0.workspaceID;D7.emit("event",{directory:z,project:F.project.id,workspace:A,payload:H})})}function Y(K){return jZ.info("subscribing",{type:K.type}),I$.unwrap(L.gen(function*(){let U=yield*B0.get($),V=yield*Z(U,K);return I$.fromPubSub(V)})).pipe(I$.ensuring(L.sync(()=>jZ.info("unsubscribing",{type:K.type}))))}function X(){return jZ.info("subscribing",{type:"*"}),I$.unwrap(L.gen(function*(){let K=yield*B0.get($);return I$.fromPubSub(K.wildcard)})).pipe(I$.ensuring(L.sync(()=>jZ.info("unsubscribing",{type:"*"}))))}function Q(K,U,V){return L.gen(function*(){jZ.info("subscribing",{type:U});let H=yield*w7.make(),B=yield*RY.make(),z=yield*RY.provide(B)(v6.subscribe(K));return yield*RY.provide(B)(I$.fromSubscription(z).pipe(I$.runForEach((F)=>L.tryPromise({try:()=>Promise.resolve().then(()=>V(F)),catch:(A)=>{jZ.error("subscriber failed",{type:U,cause:A})}}).pipe(L.ignore)),L.forkScoped)),()=>{jZ.info("unsubscribing",{type:U}),H.fork(RY.close(B,z9.void))}})}let G=L.fn("Bus.subscribeCallback")(function*(K,U){let V=yield*B0.get($),H=yield*Z(V,K);return yield*Q(H,K.type,U)}),W=L.fn("Bus.subscribeAllCallback")(function*(K){let U=yield*B0.get($);return yield*Q(U.wildcard,"*",K)});return PY.of({publish:J,subscribe:Y,subscribeAll:X,subscribeCallback:G,subscribeAllCallback:W})})),Rd=XU,{runPromise:Pd,runSync:HO}=UO(PY,XU);async function Id($,Z){return Pd((J)=>J.publish($,Z))}function Ed($,Z){return HO((J)=>J.subscribeCallback($,Z))}function Cd($){return HO((Z)=>Z.subscribeAllCallback($))}var X$={};B1(X$,{versionedType:()=>IY,run:()=>pd,reset:()=>gd,replayAll:()=>dd,replay:()=>qO,remove:()=>cd,registry:()=>EY,project:()=>ld,payloads:()=>id,init:()=>ud,define:()=>md,SyncEvent:()=>X$});var _8=y6("event_sequence",{aggregate_id:w1().notNull().primaryKey(),seq:q8().notNull()}),F9=y6("event",{id:w1().primaryKey(),aggregate_id:w1().notNull().references(()=>_8.aggregate_id,{onDelete:"cascade"}),seq:q8().notNull(),type:w1().notNull(),data:w1({mode:"json"}).$type().notNull()});var d1={};B1(d1,{timestamp:()=>hd,schema:()=>fd,descending:()=>xd,create:()=>zO,ascending:()=>yd,Identifier:()=>d1});import{randomBytes as bd}from"crypto";var _d="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function QU($){let Z="",J=bd($);for(let Y=0;Y<$;Y++)Z+=_d[J[Y]%62];return Z}function GU(){let $=0,Z=0;return(J)=>{if(J!==void 0)return BigInt(J)*BigInt(4096);let Y=Date.now();if(Y>$)$=Y,Z=0;if(Z++,Z>4095)$++,Z=1;return BigInt($)*BigInt(4096)+BigInt(Z)}}function WU($){let Z=Buffer.alloc(6);for(let J=0;J<6;J++)Z[J]=Number($>>BigInt(40-8*J)&BigInt(255));return Z.toString("hex")}var Sd;((JD0)=>{let Z=GU();function J(){return X(!1)}JD0.ascending=J;function Y(){return X(!0)}JD0.descending=Y;function X(Q,G){let W=Z(G);return W=Q?~W:W,WU(W)+QU(14)}JD0.create=X})(Sd||={});var A9={event:"evt",session:"ses",message:"msg",permission:"per",question:"que",user:"usr",part:"prt",pty:"pty",tool:"tool",workspace:"wrk",entry:"ent",workflow:"wf"};function fd($){return I.string().startsWith(A9[$])}var kd=26,vd=GU();function yd($,Z){return BO($,"ascending",Z)}function xd($,Z){return BO($,"descending",Z)}function BO($,Z,J){if(!J)return zO(A9[$],Z);if(!J.startsWith(A9[$]))throw Error(`ID ${J} does not start with ${A9[$]}`);return J}function zO($,Z,J){let Y=vd(J);return Y=Z==="descending"?~Y:Y,$+"_"+WU(Y)+QU(kd-12)}function hd($){let Z=$.split("_")[0],J=$.slice(Z.length+1,Z.length+13),Y=BigInt("0x"+J);return Number(Y/BigInt(4096))}var FO=O.String.annotate({[F$]:d1.schema("event")}).pipe(O.brand("EventID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("event",Z)),zod:d1.schema("event").pipe(I.custom())})));var EY=new Map,O9,q9=new Map,KU=!1,UU;function gd(){KU=!1,O9=void 0,UU=($,Z)=>Z}function ud($){O9=new Map($.projectors);for(let[Z,J]of q9.entries()){let Y=EY.get(IY(Z,J));L1.define(Y.type,Y.properties||Y.schema)}KU=!0,UU=$.convertEvent||((Z,J)=>J)}function IY($,Z){return Z?`${$}.${Z}`:$}function md($){if(KU)throw Error("Error defining sync event: sync system has been frozen");let Z={type:$.type,version:$.version,aggregate:$.aggregate,schema:$.schema,properties:$.busSchema?$.busSchema:$.schema};return q9.set(Z.type,Math.max(Z.version,q9.get(Z.type)||0)),EY.set(IY(Z.type,Z.version),Z),Z}function ld($,Z){return[$,Z]}function OO($,Z,J){if(O9==null)throw Error("No projectors available. Call `SyncEvent.init` to install projectors");let Y=O9.get($);if(!Y)throw Error(`Projector not found for event: ${$.type}`);W1.transaction((X)=>{if(Y(X,Z.data),b0.QITQODE_EXPERIMENTAL_WORKSPACES)X.insert(_8).values({aggregate_id:Z.aggregateID,seq:Z.seq}).onConflictDoUpdate({target:_8.aggregate_id,set:{seq:Z.seq}}).run(),X.insert(F9).values({id:Z.id,seq:Z.seq,aggregate_id:Z.aggregateID,type:IY($.type,$.version),data:Z.data}).run();W1.effect(()=>{if(J?.publish){let Q=UU($.type,Z.data);if(Q instanceof Promise)Q.then((G)=>{l1.publish({type:$.type,properties:$.schema},G)});else l1.publish({type:$.type,properties:$.schema},Q);D7.emit("event",{directory:S8.directory,project:S8.project.id,workspace:AO.workspaceID,payload:{type:"sync",syncEvent:{type:IY($.type,$.version),...Z}}})}})})}function qO($,Z){let J=EY.get($.type);if(!J)throw Error(`Unknown event type: ${$.type}`);let X=W1.use((G)=>G.select({seq:_8.seq}).from(_8).where(m0(_8.aggregate_id,$.aggregateID)).get())?.seq??-1;if($.seq<=X)return;let Q=X+1;if($.seq!==Q)throw Error(`Sequence mismatch for aggregate "${$.aggregateID}": expected ${Q}, got ${$.seq}`);OO(J,$,{publish:!!Z?.publish})}function dd($,Z){let J=$[0]?.aggregateID;if(!J)return;if($.some((X)=>X.aggregateID!==J))throw Error("Replay events must belong to the same session");let Y=$[0].seq;for(let[X,Q]of $.entries()){let G=Y+X;if(Q.seq!==G)throw Error(`Replay sequence mismatch at index ${X}: expected ${G}, got ${Q.seq}`)}for(let X of $)qO(X,Z);return J}function pd($,Z,J){let Y=Z[$.aggregate];if(Y==null)throw Error(`SyncEvent.run: "${$.aggregate}" required but not found: ${JSON.stringify(Z)}`);if($.version!==q9.get($.type))throw Error(`SyncEvent.run: running old versions of events is not allowed: ${$.type}`);let{publish:X=!0}=J||{};W1.transaction((Q)=>{let G=FO.ascending(),W=Q.select({seq:_8.seq}).from(_8).where(m0(_8.aggregate_id,Y)).get(),K=W?.seq!=null?W.seq+1:0;OO($,{id:G,seq:K,aggregateID:Y,data:Z},{publish:X})},{behavior:"immediate"})}function cd($){W1.transaction((Z)=>{Z.delete(_8).where(m0(_8.aggregate_id,$)).run(),Z.delete(F9).where(m0(F9.aggregate_id,$)).run()})}function id(){return EY.entries().map(([$,Z])=>{return I.object({type:I.literal("sync"),name:I.literal($),id:I.string(),seq:I.number(),aggregateID:I.literal(Z.aggregate),data:Z.schema}).meta({ref:`SyncEvent.${Z.type}`})}).toArray()}var b$={};B1(b$,{toModelMessagesEffect:()=>UR,toModelMessages:()=>re,stream:()=>pV,parts:()=>IL,page:()=>PL,isMedia:()=>MX,get:()=>Ea,fromError:()=>SA,fingerprint:()=>OH,filterCompactedEffect:()=>Ca,filterCompacted:()=>cV,cursor:()=>dV,WithParts:()=>Ta,User:()=>DL,ToolStateRunning:()=>FL,ToolStatePending:()=>zL,ToolStateError:()=>OL,ToolStateCompleted:()=>AL,ToolState:()=>qL,ToolPart:()=>NL,TextPart:()=>ew,SymbolSource:()=>JL,SubtaskPart:()=>WL,StructuredOutputError:()=>pw,StepStartPart:()=>VL,StepFinishPart:()=>BL,SnapshotPart:()=>aw,SYNTHETIC_ATTACHMENT_PROMPT:()=>KR,RetryPart:()=>UL,ResourceSource:()=>YL,ReasoningPart:()=>$L,Provenance:()=>ML,PatchPart:()=>tw,Part:()=>mV,OutputLengthError:()=>H4,OutputFormatText:()=>ow,OutputFormatJsonSchema:()=>sw,ModelError:()=>nw,MessageV2:()=>b$,InvalidOutputError:()=>cw,Info:()=>lV,Format:()=>rw,FileSource:()=>ZL,FilePartSource:()=>XL,FilePart:()=>uV,Event:()=>La,ContextOverflowError:()=>WX,ContentFilterError:()=>iw,CompactionPart:()=>KL,CheckpointPart:()=>GL,AuthError:()=>B4,Assistant:()=>wL,AgentPart:()=>QL,AbortedError:()=>S5,APIError:()=>i6});var r0=O.String.annotate({[F$]:d1.schema("session")}).pipe(O.brand("SessionID"),u0(($)=>({descending:(Z)=>$.make(d1.descending("session",Z)),zod:d1.schema("session").pipe(I.custom())}))),i1=O.String.annotate({[F$]:d1.schema("message")}).pipe(O.brand("MessageID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("message",Z)),zod:d1.schema("message").pipe(I.custom())}))),MZ=O.String.annotate({[F$]:d1.schema("part")}).pipe(O.brand("PartID"),u0(($)=>({ascending:(Z)=>$.make(d1.ascending("part",Z)),zod:d1.schema("part").pipe(I.custom())})));var Q4={};B1(Q4,{layer:()=>Cw,defaultLayer:()=>Ha,Symbol:()=>Ga,Status:()=>Ka,Service:()=>X4,Range:()=>Y4,Event:()=>Ew,DocumentSymbol:()=>Wa,Diagnostic:()=>QX});var b7=h6(KN(),1);import vY from"path";import{pathToFileURL as z5,fileURLToPath as kc}from"url";var UN={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};function hU($,Z){let J;return Promise.race([$,new Promise((X,Q)=>{J=setTimeout(()=>{Q(Error(`Operation timed out after ${Z}ms`))},Z)})]).finally(()=>clearTimeout(J))}var vc=150,F5=C0.create({service:"lsp.client"}),yc=N1.create("LSPInitializeError",I.object({serverID:I.string()})),VN={Diagnostics:L1.define("lsp.client.diagnostics",I.object({serverID:I.string(),path:I.string()}))};async function HN($){let Z=F5.clone().tag("serverID",$.serverID);Z.info("starting client");let J=b7.createMessageConnection(new b7.StreamMessageReader($.server.process.stdout),new b7.StreamMessageWriter($.server.process.stdin)),Y=new Map;if(J.onNotification("textDocument/publishDiagnostics",(G)=>{let W=o0.normalizePath(kc(G.uri));Z.info("textDocument/publishDiagnostics",{path:W,count:G.diagnostics.length});let K=Y.has(W);if(Y.set(W,G.diagnostics),!K&&$.serverID==="typescript")return;l1.publish(VN.Diagnostics,{path:W,serverID:$.serverID})}),J.onRequest("window/workDoneProgress/create",(G)=>{return Z.info("window/workDoneProgress/create",G),null}),J.onRequest("workspace/configuration",async()=>{return[$.server.initialization??{}]}),J.onRequest("client/registerCapability",async()=>{}),J.onRequest("client/unregisterCapability",async()=>{}),J.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:z5($.root).href}]),J.listen(),Z.info("sending initialize"),await hU(J.sendRequest("initialize",{rootUri:z5($.root).href,processId:$.server.process.pid,workspaceFolders:[{name:"workspace",uri:z5($.root).href}],initializationOptions:{...$.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0}},textDocument:{synchronization:{didOpen:!0,didChange:!0},publishDiagnostics:{versionSupport:!0}}}}),45000).catch((G)=>{throw Z.error("initialize error",{error:G}),new yc({serverID:$.serverID},{cause:G})}),await J.sendNotification("initialized",{}),$.server.initialization)await J.sendNotification("workspace/didChangeConfiguration",{settings:$.server.initialization});let X={},Q={root:$.root,get serverID(){return $.serverID},get connection(){return J},notify:{async open(G){G.path=vY.isAbsolute(G.path)?G.path:vY.resolve($.directory,G.path);let W=await o0.readText(G.path),K=vY.extname(G.path),U=UN[K]??"plaintext",V=X[G.path];if(V!==void 0){F5.info("workspace/didChangeWatchedFiles",G),await J.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:z5(G.path).href,type:2}]});let H=V+1;X[G.path]=H,F5.info("textDocument/didChange",{path:G.path,version:H}),await J.sendNotification("textDocument/didChange",{textDocument:{uri:z5(G.path).href,version:H},contentChanges:[{text:W}]});return}F5.info("workspace/didChangeWatchedFiles",G),await J.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:z5(G.path).href,type:1}]}),F5.info("textDocument/didOpen",G),Y.delete(G.path),await J.sendNotification("textDocument/didOpen",{textDocument:{uri:z5(G.path).href,languageId:U,version:0,text:W}}),X[G.path]=0;return}},get diagnostics(){return Y},async waitForDiagnostics(G){let W=o0.normalizePath(vY.isAbsolute(G.path)?G.path:vY.resolve($.directory,G.path));F5.info("waiting for diagnostics",{path:W});let K,U;return await hU(new Promise((V)=>{K=l1.subscribe(VN.Diagnostics,(H)=>{if(H.properties.path===W&&H.properties.serverID===Q.serverID){if(U)clearTimeout(U);U=setTimeout(()=>{F5.info("got diagnostics",{path:W}),K?.(),V()},vc)}})}),3000).catch(()=>{}).finally(()=>{if(U)clearTimeout(U);K?.()})},async shutdown(){Z.info("shutting down"),J.end(),J.dispose(),await f1.stop($.server.process),Z.info("shutdown")}};return Z.info("initialized"),Q}import Pw from"path";import{pathToFileURL as Iw,fileURLToPath as Qa}from"url";var _7={};B1(_7,{Zls:()=>xN,YamlLS:()=>wN,Vue:()=>ON,Typescript:()=>AN,Ty:()=>gN,Tinymist:()=>iN,TexLab:()=>oN,TerraformLS:()=>nN,Svelte:()=>MN,SourceKit:()=>CN,RustAnalyzer:()=>bN,Rubocop:()=>hN,Pyright:()=>uN,Prisma:()=>TN,PHPIntelephense:()=>lN,Oxlint:()=>NN,Ocaml:()=>vN,Nixd:()=>cN,LuaLS:()=>LN,KotlinLS:()=>fN,JuliaLS:()=>dN,JDTLS:()=>SN,HLS:()=>pN,Gopls:()=>PN,Gleam:()=>yN,FSharp:()=>EN,ElixirLS:()=>mN,ESLint:()=>qN,DockerfileLS:()=>sN,Deno:()=>FN,Dart:()=>kN,Clojure:()=>rN,Clangd:()=>_N,CSharp:()=>IN,Biome:()=>jN,BashLS:()=>RN,Astro:()=>DN});function Z1($,Z,J){let Y=Array.isArray(Z)?[...Z]:[],X=Array.isArray(Z)?J:Z,Q=f1.spawn([$,...Y],{...X,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!Q.stdin||!Q.stdout||!Q.stderr)throw Error("Process output not available");return Q}import xc from"fs/promises";import gU from"path";var Q0=C0.create({service:"lsp.server"}),uU=async($)=>xc.stat($).then(()=>!0).catch(()=>!1),q6=($,Z={})=>f1.run($,{...Z,nothrow:!0}),zN=($,Z={})=>f1.text($,{...Z,nothrow:!0});async function N6($,Z){if($)return $;if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;return O6.which(Z)}var j6=($,Z,J)=>Z1($,Z,{cwd:J,env:{...n8()}}),t0=($,Z)=>{return async(J,Y)=>{if(Z){let G=o0.up({targets:Z,start:gU.dirname(J),stop:Y.directory}),W=await G.next();if(await G.return(),W.value)return}let X=o0.up({targets:$,start:gU.dirname(J),stop:Y.directory}),Q=await X.next();if(await X.return(),!Q.value)return Y.directory;return gU.dirname(Q.value)}};import{createRequire as hc}from"module";import gc from"path";var wZ;((jL0)=>{function $(Z,J){try{return hc(gc.join(J,"package.json")).resolve(Z)}catch{}}jL0.resolve=$})(wZ||={});import uc from"path";async function LZ($,Z,J){let Y=await fetch($);if(!Y.ok){Q0.error(`Failed to download ${J}`);return}let X=uc.join(F0.Path.bin,Z);if(Y.body)await o0.writeStream(X,Y.body);return X}async function TZ($,Z){return M8.extractZip($,F0.Path.bin).then(()=>!0).catch((J)=>{return Q0.error(`Failed to extract ${Z} archive`,{error:J}),!1})}import M6 from"fs/promises";import{text as mc}from"stream/consumers";import D8 from"path";var FN={id:"deno",root:async($,Z)=>{let J=o0.up({targets:["deno.json","deno.jsonc"],start:D8.dirname($),stop:Z.directory}),Y=await J.next();if(await J.return(),!Y.value)return;return D8.dirname(Y.value)},extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn($){let Z=d0("deno");if(!Z){Q0.info("deno not found, please install deno first");return}return{process:Z1(Z,["lsp"],{cwd:$})}}},AN={id:"typescript",root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn($,Z){let J=wZ.resolve("typescript/lib/tsserver.js",Z.directory);if(Q0.info("typescript server",{tsserver:J}),!J)return;let Y=await O6.which("typescript-language-server");if(!Y)return;return{process:Z1(Y,["--stdio"],{cwd:$,env:{...n8()}}),initialization:{tsserver:{path:J}}}}},ON={id:"vue",extensions:[".vue"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("vue-language-server"),"@vue/language-server");if(!Z)return;return{process:j6(Z,["--stdio"],$),initialization:{}}}},qN={id:"eslint",root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn($,Z){if(!wZ.resolve("eslint",Z.directory))return;Q0.info("spawning eslint server");let Y=D8.join(F0.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await o0.exists(Y)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading and building VS Code ESLint server");let Q=await LZ("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip","vscode-eslint.zip","vscode-eslint");if(!Q)return;if(!await TZ(Q,"vscode-eslint"))return;await M6.rm(Q,{force:!0});let W=D8.join(F0.Path.bin,"vscode-eslint-main"),K=D8.join(F0.Path.bin,"vscode-eslint");if(await M6.stat(K).catch(()=>{return}))Q0.info("removing old eslint installation",{path:K}),await M6.rm(K,{force:!0,recursive:!0});await M6.rename(W,K);let V=process.platform==="win32"?"npm.cmd":"npm";await f1.run([V,"install"],{cwd:K}),await f1.run([V,"run","compile"],{cwd:K}),Q0.info("installed VS Code ESLint server",{serverPath:Y})}return{process:Z1("node",[Y,"--stdio"],{cwd:$,env:{...n8()}})}}},NN={id:"oxlint",root:t0([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn($,Z){let J=process.platform==="win32"?".cmd":"",Y=D8.join("node_modules",".bin","oxc_language_server"+J),X=D8.join("node_modules",".bin","oxlint"+J),Q=async(K)=>{let U=D8.join($,K);if(await o0.exists(U))return U;let V=o0.up({targets:[K],start:$,stop:Z.worktree}),H=await V.next();if(await V.return(),H.value)return H.value;return},G=await Q(X);if(!G){let K=d0("oxlint");if(K)G=K}if(G){let K=Z1(G,["--help"]);if(await K.exited,K.stdout){if((await mc(K.stdout)).includes("--lsp"))return{process:Z1(G,["--lsp"],{cwd:$})}}}let W=await Q(Y);if(!W){let K=d0("oxc_language_server");if(K)W=K}if(W)return{process:Z1(W,[],{cwd:$})};Q0.info("oxlint not found, please install oxlint");return}},jN={id:"biome",root:t0(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn($){let Z=D8.join($,"node_modules",".bin","biome"),J;if(await o0.exists(Z))J=Z;if(!J){let Q=d0("biome");if(Q)J=Q}let Y=["lsp-proxy","--stdio"];if(!J){if(!wZ.resolve("biome",$))return;if(J=await O6.which("biome"),!J)return;Y=["lsp-proxy","--stdio"]}return{process:Z1(J,Y,{cwd:$,env:{...n8()}})}}},MN={id:"svelte",extensions:[".svelte"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("svelteserver"),"svelte-language-server");if(!Z)return;return{process:j6(Z,["--stdio"],$),initialization:{}}}},DN={id:"astro",extensions:[".astro"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($,Z){let J=wZ.resolve("typescript/lib/tsserver.js",Z.directory);if(!J){Q0.info("typescript not found, required for Astro language server");return}let Y=D8.dirname(J),X=await N6(d0("astro-ls"),"@astrojs/language-server");if(!X)return;return{process:j6(X,["--stdio"],$),initialization:{typescript:{tsdk:Y}}}}},wN={id:"yaml-ls",extensions:[".yaml",".yml"],root:t0(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn($){let Z=await N6(d0("yaml-language-server"),"yaml-language-server");if(!Z)return;return{process:j6(Z,["--stdio"],$)}}},LN={id:"lua-ls",root:t0([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn($){let Z=d0("lua-language-server");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading lua-language-server from GitHub releases");let J=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!J.ok){Q0.error("Failed to fetch lua-language-server release info");return}let Y=await J.json(),X=process.platform,Q=process.arch,G="",W=Q;if(Q==="arm64")W="arm64";else if(Q==="x64")W="x64";else if(Q==="ia32")W="ia32";let K=X;if(X==="darwin")K="darwin";else if(X==="linux")K="linux";else if(X==="win32")K="win32";let U=X==="win32"?"zip":"tar.gz";G=`lua-language-server-${Y.tag_name}-${K}-${W}.${U}`;let V=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],H=`${K}-${W}.${U}`;if(!V.includes(H)){Q0.error(`Platform ${X} and architecture ${Q} is not supported by lua-language-server`);return}let B=Y.assets.find((w)=>w.name===G);if(!B){Q0.error(`Could not find asset ${G} in latest lua-language-server release`);return}let z=B.browser_download_url,F=await fetch(z);if(!F.ok){Q0.error("Failed to download lua-language-server");return}let A=D8.join(F0.Path.bin,G);if(F.body)await o0.writeStream(A,F.body);let N=D8.join(F0.Path.bin,`lua-language-server-${W}-${K}`);if(await M6.stat(N).catch(()=>{return}))await M6.rm(N,{force:!0,recursive:!0});if(await M6.mkdir(N,{recursive:!0}),U==="zip"){if(!await M8.extractZip(A,N).then(()=>!0).catch((q)=>{return Q0.error("Failed to extract lua-language-server archive",{error:q}),!1}))return}else if(!await q6(["tar","-xzf",A,"-C",N]).then((q)=>q.code===0).catch((q)=>{return Q0.error("Failed to extract lua-language-server archive",{error:q}),!1}))return;if(await M6.rm(A,{force:!0}),Z=D8.join(N,"bin","lua-language-server"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract lua-language-server binary");return}if(X!=="win32"){if(!await M6.chmod(Z,493).then(()=>!0).catch((q)=>{return Q0.error("Failed to set executable permission for lua-language-server binary",{error:q}),!1}))return}Q0.info("installed lua-language-server",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},TN={id:"prisma",extensions:[".prisma"],root:t0(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn($){let Z=d0("prisma");if(!Z){Q0.info("prisma not found, please install prisma");return}return{process:Z1(Z,["language-server"],{cwd:$})}}},RN={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:async($,Z)=>Z.directory,async spawn($){let Z=await N6(d0("bash-language-server"),"bash-language-server");if(!Z)return;return{process:j6(Z,["start"],$)}}};import $8 from"fs/promises";import o1 from"path";import lc from"os";var PN={id:"gopls",root:async($,Z)=>{let J=await t0(["go.work"])($,Z);if(J)return J;return t0(["go.mod","go.sum"])($,Z)},extensions:[".go"],async spawn($){let Z=d0("gopls");if(!Z){if(!d0("go"))return;if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing gopls"),await f1.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{GOBIN:F0.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install gopls");return}Z=o1.join(F0.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),Q0.info("installed gopls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},IN={id:"csharp",root:t0([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn($){let Z=d0("csharp-ls");if(!Z){if(!d0("dotnet")){Q0.error(".NET SDK is required to install csharp-ls");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing csharp-ls via dotnet tool"),await f1.spawn(["dotnet","tool","install","csharp-ls","--tool-path",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install csharp-ls");return}Z=o1.join(F0.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),Q0.info("installed csharp-ls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},EN={id:"fsharp",root:t0([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn($){let Z=d0("fsautocomplete");if(!Z){if(!d0("dotnet")){Q0.error(".NET SDK is required to install fsautocomplete");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing fsautocomplete via dotnet tool"),await f1.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install fsautocomplete");return}Z=o1.join(F0.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),Q0.info("installed fsautocomplete",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},CN={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:t0(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn($){let Z=d0("sourcekit-lsp");if(Z)return{process:Z1(Z,{cwd:$})};if(!d0("xcrun"))return;let J=await zN(["xcrun","--find","sourcekit-lsp"]);if(J.code!==0)return;let Y=J.text.trim();return{process:Z1(Y,{cwd:$})}}},bN={id:"rust",root:async($,Z)=>{let J=await t0(["Cargo.toml","Cargo.lock"])($,Z);if(J===void 0)return;let Y=J;while(Y!==o1.dirname(Y)){let X=o1.join(Y,"Cargo.toml");try{if((await o0.readText(X)).includes("[workspace]"))return Y}catch{}let Q=o1.dirname(Y);if(Q===Y||!o0.contains(Z.worktree,Q))break;Y=Q}return J},extensions:[".rs"],async spawn($){let Z=d0("rust-analyzer");if(!Z){Q0.info("rust-analyzer not found in path, please install it");return}return{process:Z1(Z,{cwd:$})}}},_N={id:"clangd",root:t0(["compile_commands.json","compile_flags.txt",".clangd"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn($){let Z=["--background-index","--clang-tidy"],J=d0("clangd");if(J)return{process:Z1(J,Z,{cwd:$})};let Y=process.platform==="win32"?".exe":"",X=o1.join(F0.Path.bin,"clangd"+Y);if(await o0.exists(X))return{process:Z1(X,Z,{cwd:$})};let Q=await $8.readdir(F0.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let R of Q){if(!R.isDirectory())continue;if(!R.name.startsWith("clangd_"))continue;let T=o1.join(F0.Path.bin,R.name,"bin","clangd"+Y);if(await o0.exists(T))return{process:Z1(T,Z,{cwd:$})}}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading clangd from GitHub releases");let G=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!G.ok){Q0.error("Failed to fetch clangd release info");return}let W=await G.json(),K=W.tag_name;if(!K){Q0.error("clangd release did not include a tag name");return}let U=process.platform,H={darwin:"mac",linux:"linux",win32:"windows"}[U];if(!H){Q0.error(`Platform ${U} is not supported by clangd auto-download`);return}let B=W.assets??[],z=(R)=>{if(!R.name)return!1;if(!R.browser_download_url)return!1;if(!R.name.includes(H))return!1;return R.name.includes(K)},F=B.find((R)=>z(R)&&R.name?.endsWith(".zip"))??B.find((R)=>z(R)&&R.name?.endsWith(".tar.xz"))??B.find((R)=>z(R));if(!F?.name||!F.browser_download_url){Q0.error("clangd could not match release asset",{tag:K,platform:U});return}let A=F.name,N=await fetch(F.browser_download_url);if(!N.ok){Q0.error("Failed to download clangd");return}let j=o1.join(F0.Path.bin,A),w=await N.arrayBuffer();if(w.byteLength===0){Q0.error("Failed to write clangd archive");return}await o0.write(j,Buffer.from(w));let q=A.endsWith(".zip"),M=A.endsWith(".tar.xz");if(!q&&!M){Q0.error("clangd encountered unsupported asset",{asset:A});return}if(q){if(!await M8.extractZip(j,F0.Path.bin).then(()=>!0).catch((T)=>{return Q0.error("Failed to extract clangd archive",{error:T}),!1}))return}if(M)await q6(["tar","-xf",j],{cwd:F0.Path.bin});await $8.rm(j,{force:!0});let E=o1.join(F0.Path.bin,"clangd_"+K,"bin","clangd"+Y);if(!await o0.exists(E)){Q0.error("Failed to extract clangd binary");return}if(U!=="win32")await $8.chmod(E,493).catch(()=>{});return await $8.unlink(o1.join(F0.Path.bin,"clangd")).catch(()=>{}),await $8.symlink(E,o1.join(F0.Path.bin,"clangd")).catch(()=>{}),Q0.info("installed clangd",{bin:E}),{process:Z1(E,Z,{cwd:$})}}},SN={id:"jdtls",root:async($,Z)=>{let J=["settings.gradle","settings.gradle.kts"],Y=["gradlew","gradlew.bat"],X=Y.concat(J),[Q,G,W]=await Promise.all([t0(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"],X)($,Z),t0(Y,J)($,Z),t0(J)($,Z)]);if(Q)return Q;if(G)return G;if(W)return W},extensions:[".java"],async spawn($){let Z=d0("java");if(!Z){Q0.error("Java 21 or newer is required to run the JDTLS. Please install it first.");return}let J=await q6(["java","-version"]).then((V)=>{let H=/"(\d+)\.\d+\.\d+"/.exec(V.stderr.toString());return!H?void 0:parseInt(H[1])});if(J==null||J<21){Q0.error("JDTLS requires at least Java 21.");return}let Y=o1.join(F0.Path.bin,"jdtls"),X=o1.join(Y,"plugins");if(!await uU(X)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("Downloading JDTLS LSP server."),await $8.mkdir(Y,{recursive:!0});let V="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",H="release.tar.gz";Q0.info("Downloading JDTLS archive",{url:V,dest:Y});let B=await fetch(V);if(!B.ok||!B.body){Q0.error("Failed to download JDTLS",{status:B.status,statusText:B.statusText});return}await o0.writeStream(o1.join(Y,H),B.body),Q0.info("Extracting JDTLS archive");let z=await q6(["tar","-xzf",H],{cwd:Y});if(z.code!==0){Q0.error("Failed to extract JDTLS",{exitCode:z.code,stderr:z.stderr.toString()});return}await $8.rm(o1.join(Y,H),{force:!0}),Q0.info("JDTLS download and extraction completed")}let G=(await $8.readdir(X).catch(()=>[])).find((V)=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(V))?.trim()??"",W=o1.join(X,G);if(!await uU(W)){Q0.error(`Failed to locate the JDTLS launcher module in the installed directory: ${Y}.`);return}let K=o1.join(Y,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),U=await $8.mkdtemp(o1.join(lc.tmpdir(),"qitqode-jdtls-data"));return{process:Z1(Z,["-jar",W,"-configuration",K,"-data",U,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:$})}}},fN={id:"kotlin-ls",extensions:[".kt",".kts"],root:async($,Z)=>{let J=await t0(["settings.gradle.kts","settings.gradle"])($,Z);if(J)return J;let Y=await t0(["gradlew","gradlew.bat"])($,Z);if(Y)return Y;let X=await t0(["build.gradle.kts","build.gradle"])($,Z);if(X)return X;return t0(["pom.xml"])($,Z)},async spawn($){let Z=o1.join(F0.Path.bin,"kotlin-ls"),J=process.platform==="win32"?o1.join(Z,"kotlin-lsp.cmd"):o1.join(Z,"kotlin-lsp.sh");if(!await o0.exists(J)){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("Downloading Kotlin Language Server from GitHub.");let X=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!X.ok){Q0.error("Failed to fetch kotlin-lsp release info");return}let G=(await X.json()).name?.replace(/^v/,"");if(!G){Q0.error("Could not determine Kotlin LSP version from release");return}let{platform:W,arch:K}=process,U=K;if(K==="arm64")U="aarch64";else if(K==="x64")U="x64";let V=W;if(W==="darwin")V="mac";else if(W==="linux")V="linux";else if(W==="win32")V="win";let H=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],B=`${V}-${U}`;if(!H.includes(B)){Q0.error(`Platform ${W}/${K} is not supported by Kotlin LSP`);return}let z=`kotlin-lsp-${G}-${V}-${U}.zip`,F=`https://download-cdn.jetbrains.com/kotlin-lsp/${G}/${z}`;await $8.mkdir(Z,{recursive:!0});let A=o1.join(Z,"kotlin-ls.zip"),N=await fetch(F);if(!N.ok||!N.body){Q0.error("Failed to download Kotlin Language Server",{status:N.status,statusText:N.statusText});return}if(await o0.writeStream(A,N.body),!await M8.extractZip(A,Z).then(()=>!0).catch((w)=>{return Q0.error("Failed to extract Kotlin LS archive",{error:w}),!1}))return;if(await $8.rm(A,{force:!0}),process.platform!=="win32")await $8.chmod(J,493).catch(()=>{});Q0.info("Installed Kotlin Language Server",{path:J})}if(!await o0.exists(J)){Q0.error(`Failed to locate the Kotlin LS launcher script in the installed directory: ${Z}.`);return}return{process:Z1(J,["--stdio"],{cwd:$})}}},kN={id:"dart",extensions:[".dart"],root:t0(["pubspec.yaml","analysis_options.yaml"]),async spawn($){let Z=d0("dart");if(!Z){Q0.info("dart not found, please install dart first");return}return{process:Z1(Z,["language-server","--lsp"],{cwd:$})}}},vN={id:"ocaml-lsp",extensions:[".ml",".mli"],root:t0(["dune-project","dune-workspace",".merlin","opam"]),async spawn($){let Z=d0("ocamllsp");if(!Z){Q0.info("ocamllsp not found, please install ocaml-lsp-server");return}return{process:Z1(Z,{cwd:$})}}},yN={id:"gleam",extensions:[".gleam"],root:t0(["gleam.toml"]),async spawn($){let Z=d0("gleam");if(!Z){Q0.info("gleam not found, please install gleam first");return}return{process:Z1(Z,["lsp"],{cwd:$})}}},xN={id:"zls",extensions:[".zig",".zon"],root:t0(["build.zig"]),async spawn($){let Z=d0("zls");if(!Z){if(!d0("zig")){Q0.error("Zig is required to use zls. Please install Zig first.");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading zls from GitHub releases");let Y=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!Y.ok){Q0.error("Failed to fetch zls release info");return}let X=await Y.json(),Q=process.platform,G=process.arch,W="",K=G;if(G==="arm64")K="aarch64";else if(G==="x64")K="x86_64";else if(G==="ia32")K="x86";let U=Q;if(Q==="darwin")U="macos";else if(Q==="win32")U="windows";let V=Q==="win32"?"zip":"tar.xz";if(W=`zls-${K}-${U}.${V}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(W)){Q0.error(`Platform ${Q} and architecture ${G} is not supported by zls`);return}let B=X.assets?.find((F)=>F.name===W);if(!B?.browser_download_url){Q0.error(`Could not find asset ${W} in latest zls release`);return}let z=await LZ(B.browser_download_url,W,"zls");if(!z)return;if(V==="zip"){if(!await TZ(z,"zls"))return}else await q6(["tar","-xf",z],{cwd:F0.Path.bin});if(await $8.rm(z,{force:!0}),Z=o1.join(F0.Path.bin,"zls"+(Q==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract zls binary");return}if(Q!=="win32")await $8.chmod(Z,493).catch(()=>{});Q0.info("installed zls",{bin:Z})}return{process:Z1(Z,{cwd:$})}}};import A5 from"fs/promises";import f8 from"path";function dc($){return[process.env.VIRTUAL_ENV,f8.join($,".venv"),f8.join($,"venv")].filter((Z)=>Z!==void 0)}async function mU($,Z){let J=process.platform==="win32";for(let Y of dc($)){let X=J?f8.join(Y,"Scripts",`${Z}.exe`):f8.join(Y,"bin",Z);if(await o0.exists(X))return X}return}var hN={id:"ruby-lsp",root:t0(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn($){let Z=d0("rubocop");if(!Z){let J=d0("ruby"),Y=d0("gem");if(!J||!Y){Q0.info("Ruby not found, please install Ruby first");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;if(Q0.info("installing rubocop"),await f1.spawn(["gem","install","rubocop","--bindir",F0.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0){Q0.error("Failed to install rubocop");return}Z=f8.join(F0.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),Q0.info("installed rubocop",{bin:Z})}return{process:Z1(Z,["--lsp"],{cwd:$})}}},gN={id:"ty",extensions:[".py",".pyi"],root:t0(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn($){if(!b0.QITQODE_EXPERIMENTAL_LSP_TY)return;let Z=d0("ty"),J={},Y=await mU($,"python");if(Y)J.pythonPath=Y;if(!Z)Z=await mU($,"ty")??null;if(!Z){Q0.error("ty not found, please install ty first");return}return{process:Z1(Z,["server"],{cwd:$}),initialization:J}}},uN={id:"pyright",extensions:[".py",".pyi"],root:t0(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn($){let Z=await N6(d0("pyright-langserver"),"pyright");if(!Z)return;let J=["--stdio"],Y={},X=await mU($,"python");if(X)Y.pythonPath=X;return{process:j6(Z,J,$),initialization:Y}}},mN={id:"elixir-ls",extensions:[".ex",".exs"],root:t0(["mix.exs","mix.lock"]),async spawn($){let Z=d0("elixir-ls");if(!Z){let J=f8.join(F0.Path.bin,"elixir-ls");if(Z=f8.join(F0.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await o0.exists(Z)){if(!d0("elixir")){Q0.error("elixir is required to run elixir-ls");return}if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading elixir-ls from GitHub releases");let X=await LZ("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip","elixir-ls.zip","elixir-ls");if(!X)return;if(!await TZ(X,"elixir-ls"))return;await A5.rm(X,{force:!0,recursive:!0});let G=f8.join(F0.Path.bin,"elixir-ls-master"),W={MIX_ENV:"prod",...n8()};await f1.run(["mix","deps.get"],{cwd:G,env:W}),await f1.run(["mix","compile"],{cwd:G,env:W}),await f1.run(["mix","elixir_ls.release2","-o","release"],{cwd:G,env:W}),Q0.info("installed elixir-ls",{path:J})}}return{process:Z1(Z,{cwd:$})}}},lN={id:"php intelephense",extensions:[".php"],root:t0(["composer.json","composer.lock",".php-version"]),async spawn($){let Z=await N6(d0("intelephense"),"intelephense");if(!Z)return;return{process:j6(Z,["--stdio"],$),initialization:{telemetry:{enabled:!1}}}}},dN={id:"julials",extensions:[".jl"],root:t0(["Project.toml","Manifest.toml","*.jl"]),async spawn($){let Z=d0("julia");if(!Z){Q0.info("julia not found, please install julia first (https://julialang.org/downloads/)");return}return{process:Z1(Z,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:$})}}},pN={id:"haskell-language-server",extensions:[".hs",".lhs"],root:t0(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn($){let Z=d0("haskell-language-server-wrapper");if(!Z){Q0.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return{process:Z1(Z,["--lsp"],{cwd:$})}}},cN={id:"nixd",extensions:[".nix"],root:async($,Z)=>{let J=await t0(["flake.nix"])($,Z);if(J&&J!==Z.directory)return J;if(Z.worktree&&Z.worktree!==Z.directory)return Z.worktree;return Z.directory},async spawn($){let Z=d0("nixd");if(!Z){Q0.info("nixd not found, please install nixd first");return}return{process:Z1(Z,[],{cwd:$,env:{...n8()}})}}},iN={id:"tinymist",extensions:[".typ",".typc"],root:t0(["typst.toml"]),async spawn($){let Z=d0("tinymist");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading tinymist from GitHub releases");let J=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!J.ok){Q0.error("Failed to fetch tinymist release info");return}let Y=await J.json(),X=process.platform,G=process.arch==="arm64"?"aarch64":"x86_64",W,K;if(X==="darwin")W="apple-darwin",K="tar.gz";else if(X==="win32")W="pc-windows-msvc",K="zip";else W="unknown-linux-gnu",K="tar.gz";let U=`tinymist-${G}-${W}.${K}`,H=(Y.assets??[]).find((z)=>z.name===U);if(!H?.browser_download_url){Q0.error(`Could not find asset ${U} in tinymist release`);return}let B=await LZ(H.browser_download_url,U,"tinymist");if(!B)return;if(K==="zip"){if(!await TZ(B,"tinymist"))return}else await q6(["tar","-xzf",B,"--strip-components=1"],{cwd:F0.Path.bin});if(await A5.rm(B,{force:!0}),Z=f8.join(F0.Path.bin,"tinymist"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract tinymist binary");return}if(X!=="win32")await A5.chmod(Z,493).catch(()=>{});Q0.info("installed tinymist",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},nN={id:"terraform",extensions:[".tf",".tfvars"],root:t0([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn($){let Z=d0("terraform-ls");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading terraform-ls from HashiCorp releases");let J=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!J.ok){Q0.error("Failed to fetch terraform-ls release info");return}let Y=await J.json(),X=process.platform,G=process.arch==="arm64"?"arm64":"amd64",W=X==="win32"?"windows":X,U=(Y.builds??[]).find((z)=>z.arch===G&&z.os===W);if(!U?.url){Q0.error(`Could not find build for ${W}/${G} terraform-ls release version ${Y.version}`);return}let V=await fetch(U.url);if(!V.ok){Q0.error("Failed to download terraform-ls");return}let H=f8.join(F0.Path.bin,"terraform-ls.zip");if(V.body)await o0.writeStream(H,V.body);if(!await M8.extractZip(H,F0.Path.bin).then(()=>!0).catch((z)=>{return Q0.error("Failed to extract terraform-ls archive",{error:z}),!1}))return;if(await A5.rm(H,{force:!0}),Z=f8.join(F0.Path.bin,"terraform-ls"+(X==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract terraform-ls binary");return}if(X!=="win32")await A5.chmod(Z,493).catch(()=>{});Q0.info("installed terraform-ls",{bin:Z})}return{process:Z1(Z,["serve"],{cwd:$}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},oN={id:"texlab",extensions:[".tex",".bib"],root:t0([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn($){let Z=d0("texlab");if(!Z){if(b0.QITQODE_DISABLE_LSP_DOWNLOAD)return;Q0.info("downloading texlab from GitHub releases");let J=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!J.ok){Q0.error("Failed to fetch texlab release info");return}let Y=await J.json();if(!Y.tag_name?.replace("v","")){Q0.error("texlab release did not include a version tag");return}let Q=process.platform,W=process.arch==="arm64"?"aarch64":"x86_64",K=Q==="darwin"?"macos":Q==="win32"?"windows":"linux",U=Q==="win32"?"zip":"tar.gz",V=`texlab-${W}-${K}.${U}`,B=(Y.assets??[]).find((F)=>F.name===V);if(!B?.browser_download_url){Q0.error(`Could not find asset ${V} in texlab release`);return}let z=await LZ(B.browser_download_url,V,"texlab");if(!z)return;if(U==="zip"){if(!await TZ(z,"texlab"))return}if(U==="tar.gz")await q6(["tar","-xzf",z],{cwd:F0.Path.bin});if(await A5.rm(z,{force:!0}),Z=f8.join(F0.Path.bin,"texlab"+(Q==="win32"?".exe":"")),!await o0.exists(Z)){Q0.error("Failed to extract texlab binary");return}if(Q!=="win32")await A5.chmod(Z,493).catch(()=>{});Q0.info("installed texlab",{bin:Z})}return{process:Z1(Z,{cwd:$})}}},sN={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:async($,Z)=>Z.directory,async spawn($){let Z=await N6(d0("docker-langserver"),"dockerfile-language-server-nodejs");if(!Z)return;return{process:j6(Z,["--stdio"],$)}}},rN={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:t0(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn($){let Z=d0("clojure-lsp");if(!Z&&process.platform==="win32")Z=d0("clojure-lsp.exe");if(!Z){Q0.info("clojure-lsp not found, please install clojure-lsp first");return}return{process:Z1(Z,["listen"],{cwd:$})}}};var X8={};B1(X8,{layer:()=>Lw,defaultLayer:()=>Ya,Service:()=>J4,Server:()=>$a,Layout:()=>Za,Info:()=>E5,ConfigDirectoryTypoError:()=>Ja});import tr from"path";var k8={};B1(k8,{layer:()=>Yj,defaultLayer:()=>ec,WellKnown:()=>cU,Service:()=>S9,Oauth:()=>dU,OAUTH_DUMMY_KEY:()=>lU,Info:()=>Jj,AuthError:()=>f9,Auth:()=>k8,Api:()=>pU});import tc from"path";var g6={};B1(g6,{setKeyForTest:()=>sc,resetForTest:()=>oc,isEnvelope:()=>cc,encryptionKey:()=>nc,encrypt:()=>rc,decrypt:()=>ac,AuthKeyring:()=>g6});import b9 from"crypto";import{execFile as pc}from"child_process";var S7="qitqode",yY="auth-encryption-key",tN="__qitqode_encrypted__";function cc($){return typeof $==="object"&&$!==null&&$[tN]===1&&$.alg==="aes-256-gcm"}function f7($,Z,J){return new Promise((Y)=>{let X=pc($,Z,{timeout:5000},(Q,G)=>{let W=Q?Q.code??1:0;Y({code:typeof W==="number"?W:1,stdout:G??""})});if(J!==void 0)X.stdin?.write(J),X.stdin?.end()})}async function aN($,Z){return(await f7($,Z)).code===0}async function ic(){if(process.env.QITQODE_DISABLE_KEYRING)return;if(process.platform==="darwin"){if(!await aN("security",["help"]))return;return{async get(){let $=await f7("security",["find-generic-password","-s",S7,"-a",yY,"-w"]);return $.code===0?$.stdout.trim():void 0},async set($){return(await f7("security",["add-generic-password","-U","-s",S7,"-a",yY,"-w",$])).code===0}}}if(process.platform==="linux"){if(!await aN("secret-tool",["search","service",S7])){let $=await f7("secret-tool",["lookup","service",S7,"account",yY]);if($.code!==0&&$.code!==1)return}return{async get(){let $=await f7("secret-tool",["lookup","service",S7,"account",yY]);return $.code===0&&$.stdout.trim()?$.stdout.trim():void 0},async set($){return(await f7("secret-tool",["store","--label","QitQode auth encryption key","service",S7,"account",yY],$)).code===0}}}return}var _9;function nc(){return _9??=(async()=>{let $=await ic();if(!$)return;let Z=await $.get();if(Z){let J=Buffer.from(Z,"base64");if(J.length===32)return J;return}return xY.withLock("auth-keyring-init",async()=>{let J=await $.get();if(J){let G=Buffer.from(J,"base64");return G.length===32?G:void 0}let Y=b9.randomBytes(32);if(!await $.set(Y.toString("base64")))return;let X=await $.get();if(!X)return;let Q=Buffer.from(X,"base64");return Q.length===32?Q:void 0})})(),_9}function oc(){_9=void 0}function sc($){_9=Promise.resolve($)}function rc($,Z){let J=b9.randomBytes(12),Y=b9.createCipheriv("aes-256-gcm",Z,J),X=Buffer.concat([Y.update($,"utf8"),Y.final()]);return{[tN]:1,alg:"aes-256-gcm",iv:J.toString("base64"),tag:Y.getAuthTag().toString("base64"),data:X.toString("base64")}}function ac($,Z){let J=b9.createDecipheriv("aes-256-gcm",Z,Buffer.from($.iv,"base64"));return J.setAuthTag(Buffer.from($.tag,"base64")),Buffer.concat([J.update(Buffer.from($.data,"base64")),J.final()]).toString("utf8")}var lU="qitqode-oauth-dummy-key",eN=tc.join(F0.Path.data,"auth.json"),$j=($)=>(Z)=>new f9({message:$,cause:Z});class dU extends O.Class("OAuth")({type:O.Literal("oauth"),refresh:O.String,access:O.String,expires:O.Number,accountId:O.optional(O.String),enterpriseUrl:O.optional(O.String)}){}class pU extends O.Class("ApiAuth")({type:O.Literal("api"),key:O.String,metadata:O.optional(O.Record(O.String,O.String))}){}class cU extends O.Class("WellKnownAuth")({type:O.Literal("wellknown"),key:O.String,token:O.String}){}var Zj=O.Union([dU,pU,cU]).annotate({discriminator:"type",identifier:"Auth"}),Jj=Object.assign(Zj,{zod:w0(Zj)});class f9 extends O.TaggedErrorClass()("AuthError",{message:O.String,cause:O.optional(O.Defect)}){}class S9 extends S1.Service()("@qitqode/Auth"){}var Yj=T0.effect(S9,L.gen(function*(){let $=yield*C$.Service,Z=O.decodeUnknownOption(Jj),J=L.fn("Auth.readFile")(function*(){let U=yield*$.readJson(eN).pipe(L.orElseSucceed(()=>({})));if(!g6.isEnvelope(U))return U;let V=yield*L.promise(()=>g6.encryptionKey());if(!V)return yield*L.fail(new f9({message:"auth.json is encrypted but the OS keyring is unavailable. Restore keyring access or delete auth.json and log in again."}));return yield*L.try({try:()=>JSON.parse(g6.decrypt(U,V)),catch:$j("Failed to decrypt auth data (keyring key mismatch?)")})}),Y=L.fn("Auth.writeFile")(function*(U){let V=yield*L.promise(()=>g6.encryptionKey()),H=V?g6.encrypt(JSON.stringify(U),V):U;yield*$.writeJson(eN,H,384).pipe(L.mapError($j("Failed to write auth data")))}),X=L.fn("Auth.all")(function*(){let U=yield*J(),V=v7.filterMap(U,(H)=>k7.fromOption(Z(H),()=>{return}));if(process.env.QITQODE_AUTH_CONTENT)try{let H=JSON.parse(process.env.QITQODE_AUTH_CONTENT);return{...v7.filterMap(H,(z)=>k7.fromOption(Z(z),()=>{return})),...V}}catch(H){console.error("[Auth] Failed to parse QITQODE_AUTH_CONTENT env var:",H)}return V}),Q=L.fn("Auth.get")(function*(U){return(yield*X())[U]}),G="auth-file",W=L.fn("Auth.set")(function*(U,V){yield*L.scoped(L.gen(function*(){yield*xY.effect("auth-file");let H=U.replace(/\/+$/,""),B=yield*X();if(H!==U)delete B[U];delete B[H+"/"],yield*Y({...B,[H]:V})}))}),K=L.fn("Auth.remove")(function*(U){yield*L.scoped(L.gen(function*(){yield*xY.effect("auth-file");let V=U.replace(/\/+$/,""),H=yield*X();delete H[U],delete H[V],yield*Y(H)}))});return S9.of({get:Q,all:X,set:W,remove:K})})),ec=Yj.pipe(T0.provide(C$.defaultLayer));var u6={};B1(u6,{layer:()=>Xj,defaultLayer:()=>$i,Service:()=>k9,Env:()=>u6});class k9 extends S1.Service()("@qitqode/Env"){}var Xj=T0.effect(k9,L.gen(function*(){let $=yield*B0.make(L.fn("Env.state")(()=>L.succeed({...process.env}))),Z=L.fn("Env.get")((Q)=>B0.use($,(G)=>G[Q])),J=L.fn("Env.all")(()=>B0.get($)),Y=L.fn("Env.set")(function*(Q,G){let W=yield*B0.get($);W[Q]=G}),X=L.fn("Env.remove")(function*(Q){let G=yield*B0.get($);delete G[Q]});return k9.of({get:Z,all:J,set:Y,remove:X})})),$i=Xj;var Qj={Connected:L1.define("server.connected",I.object({})),Heartbeat:L1.define("server.heartbeat",I.object({})),Disposed:L1.define("global.disposed",I.object({}))};var n7={};B1(n7,{layer:()=>qj,defaultLayer:()=>Gi,UserCode:()=>mY,Service:()=>m9,RefreshToken:()=>y7,PollSuccess:()=>g7,PollSlow:()=>m7,PollResult:()=>Gj,PollPending:()=>u7,PollExpired:()=>l7,PollError:()=>p7,PollDenied:()=>d7,OrgID:()=>y9,Org:()=>dY,Login:()=>pY,Info:()=>lY,DeviceCode:()=>x7,AccountTransportError:()=>q5,AccountServiceError:()=>RZ,AccountRepoError:()=>h7,AccountID:()=>gY,Account:()=>n7,AccessToken:()=>uY});var c7={};B1(c7,{layer:()=>Zi,Service:()=>h9,AccountRepo:()=>c7});var w8=y6("account",{id:w1().$type().primaryKey(),email:w1().notNull(),url:w1().notNull(),access_token:w1().$type().notNull(),refresh_token:w1().$type().notNull(),token_expiry:q8(),...hY}),O5=y6("account_state",{id:q8().primaryKey(),active_account_id:w1().$type().references(()=>w8.id,{onDelete:"set null"}),active_org_id:w1().$type()}),ET0=y6("control_account",{email:w1().notNull(),url:w1().notNull(),access_token:w1().$type().notNull(),refresh_token:w1().$type().notNull(),token_expiry:q8(),active:q8({mode:"boolean"}).notNull().$default(()=>!1),...hY},($)=>[v9({columns:[$.email,$.url]})]);var gY=O.String.pipe(O.brand("AccountID")),y9=O.String.pipe(O.brand("OrgID")),uY=O.String.pipe(O.brand("AccessToken")),y7=O.String.pipe(O.brand("RefreshToken")),x7=O.String.pipe(O.brand("DeviceCode")),mY=O.String.pipe(O.brand("UserCode"));class lY extends O.Class("Account")({id:gY,email:O.String,url:O.String,active_org_id:O.NullOr(y9)}){}class dY extends O.Class("Org")({id:y9,name:O.String}){}class h7 extends O.TaggedErrorClass()("AccountRepoError",{message:O.String,cause:O.optional(O.Defect)}){}class RZ extends O.TaggedErrorClass()("AccountServiceError",{message:O.String,cause:O.optional(O.Defect)}){}class q5 extends O.TaggedErrorClass()("AccountTransportError",{method:O.String,url:O.String,description:O.optional(O.String),cause:O.optional(O.Defect)}){static fromHttpClientError($){return new q5({method:$.request.method,url:$.request.url,description:$.description,cause:$.cause})}get message(){return[`Could not reach ${this.method} ${this.url}.`,"This failed before the server returned an HTTP response.",this.description,"Check your network, proxy, or VPN configuration and try again."].filter(Boolean).join(`
|
|
486
486
|
`)}}class pY extends O.Class("Login")({code:x7,user:mY,url:O.String,server:O.String,expiry:O.Duration,interval:O.Duration}){}class g7 extends O.TaggedClass()("PollSuccess",{email:O.String}){}class u7 extends O.TaggedClass()("PollPending",{}){}class m7 extends O.TaggedClass()("PollSlow",{}){}class l7 extends O.TaggedClass()("PollExpired",{}){}class d7 extends O.TaggedClass()("PollDenied",{}){}class p7 extends O.TaggedClass()("PollError",{cause:O.Defect}){}var Gj=O.Union([g7,u7,m7,l7,d7,p7]);var x9=($)=>{let Z=new URL($);Z.search="",Z.hash="";let J=Z.pathname.replace(/\/+$/,"");return J.length===0?Z.origin:`${Z.origin}${J}`};var Wj=1;class h9 extends S1.Service()("@qitqode/AccountRepo"){}var Zi=T0.effect(h9,L.gen(function*(){let $=O.decodeUnknownSync(lY),Z=(B)=>L.try({try:()=>W1.use(B),catch:(z)=>new h7({message:"Database operation failed",cause:z})}),J=(B)=>L.try({try:()=>W1.transaction(B),catch:(z)=>new h7({message:"Database operation failed",cause:z})}),Y=(B)=>{let z=B.select().from(O5).where(m0(O5.id,Wj)).get();if(!z?.active_account_id)return;let F=B.select().from(w8).where(m0(w8.id,z.active_account_id)).get();if(!F)return;return{...F,active_org_id:z.active_org_id??null}},X=(B,z,F)=>{let A=O1.getOrNull(F);return B.insert(O5).values({id:Wj,active_account_id:z,active_org_id:A}).onConflictDoUpdate({target:O5.id,set:{active_account_id:z,active_org_id:A}}).run()},Q=L.fn("AccountRepo.active")(()=>Z((B)=>Y(B)).pipe(L.map((B)=>B?O1.some($(B)):O1.none()))),G=L.fn("AccountRepo.list")(()=>Z((B)=>B.select().from(w8).all().map((z)=>$({...z,active_org_id:null})))),W=L.fn("AccountRepo.remove")((B)=>J((z)=>{z.update(O5).set({active_account_id:null,active_org_id:null}).where(m0(O5.active_account_id,B)).run(),z.delete(w8).where(m0(w8.id,B)).run()}).pipe(L.asVoid)),K=L.fn("AccountRepo.use")((B,z)=>Z((F)=>X(F,B,z)).pipe(L.asVoid)),U=L.fn("AccountRepo.getRow")((B)=>Z((z)=>z.select().from(w8).where(m0(w8.id,B)).get()).pipe(L.map(O1.fromNullishOr))),V=L.fn("AccountRepo.persistToken")((B)=>Z((z)=>z.update(w8).set({access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:O1.getOrNull(B.expiry)}).where(m0(w8.id,B.accountID)).run()).pipe(L.asVoid)),H=L.fn("AccountRepo.persistAccount")((B)=>J((z)=>{let F=x9(B.url);z.insert(w8).values({id:B.id,email:B.email,url:F,access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:B.expiry}).onConflictDoUpdate({target:w8.id,set:{email:B.email,url:F,access_token:B.accessToken,refresh_token:B.refreshToken,token_expiry:B.expiry}}).run(),X(z,B.id,B.orgID)}).pipe(L.asVoid));return h9.of({active:Q,list:G,remove:W,use:K,getRow:U,persistToken:V,persistAccount:H})}));class Bj extends O.Class("RemoteConfig")({config:O.Record(O.String,O.Json)}){}var u9=O.Number.pipe(O.decodeTo(O.Duration,{decode:nU.transform(($)=>Z8.seconds($)),encode:nU.transform(($)=>Z8.toSeconds($))}));class zj extends O.Class("TokenRefresh")({access_token:uY,refresh_token:y7,expires_in:u9}){}class Fj extends O.Class("DeviceAuth")({device_code:x7,user_code:mY,verification_uri_complete:O.String,expires_in:u9,interval:u9}){}class Aj extends O.Class("DeviceTokenSuccess")({access_token:uY,refresh_token:y7,token_type:O.Literal("Bearer"),expires_in:u9}){}class tU extends O.Class("DeviceTokenError")({error:O.String,error_description:O.String}){toPollResult(){if(this.error==="authorization_pending")return new u7;if(this.error==="slow_down")return new m7;if(this.error==="expired_token")return new l7;if(this.error==="access_denied")return new d7;return new p7({cause:this.error})}}var Ji=O.Union([Aj,tU]);class Oj extends O.Class("User")({id:gY,email:O.String}){}class sU extends O.Class("ClientId")({client_id:O.String}){}class rU extends O.Class("DeviceTokenRequest")({grant_type:O.String,device_code:x7,client_id:O.String}){}class aU extends O.Class("TokenRefreshRequest")({grant_type:O.String,refresh_token:y7,client_id:O.String}){}var iU="opencode-cli",Yi=Z8.minutes(5),Xi=Z8.toMillis(Yi),Kj=($,Z)=>$!=null&&$>Z+Xi,o8=($="Account service operation failed")=>(Z)=>Z.pipe(L.mapError((J)=>Qi(J,$))),Qi=($,Z)=>{if($ instanceof RZ||$ instanceof q5)return $;if(Uj.isHttpClientError($))switch($.reason._tag){case"TransportError":return q5.fromHttpClientError($.reason);default:return new RZ({message:Z,cause:$})}return new RZ({message:Z,cause:$})};class m9 extends S1.Service()("@qitqode/Account"){}var qj=T0.effect(m9,L.gen(function*(){let $=yield*c7.Service,Z=yield*g9.HttpClient,J=Hj(Z),Y=g9.filterStatusOk(Z),X=g9.filterStatusOk(J),Q=(R)=>J.execute(R).pipe(o8("HTTP request failed")),G=(R)=>X.execute(R).pipe(o8("HTTP request failed")),W=(R)=>R.pipe(L.flatMap((T)=>Y.execute(T)),o8("HTTP request failed")),K=(R)=>R.pipe(L.flatMap((T)=>Z.execute(T)),o8("HTTP request failed")),U=L.fnUntraced(function*(R){let T=yield*i7.currentTimeMillis,P=yield*W(U$.post(`${R.url}/auth/device/token`).pipe(U$.acceptJson,U$.schemaBodyJson(aU)(new aU({grant_type:"refresh_token",refresh_token:R.refresh_token,client_id:iU})))),_=yield*PZ.schemaBodyJson(zj)(P).pipe(o8("Failed to decode response")),C=O1.some(T+Z8.toMillis(_.expires_in));return yield*$.persistToken({accountID:R.id,accessToken:_.access_token,refreshToken:_.refresh_token,expiry:C}),_.access_token}),V=yield*oU.make({capacity:Number.POSITIVE_INFINITY,timeToLive:Z8.zero,lookup:L.fnUntraced(function*(R){let T=yield*$.getRow(R);if(O1.isNone(T))return yield*L.fail(new RZ({message:"Account not found during token refresh"}));let P=T.value,_=yield*i7.currentTimeMillis;if(Kj(P.token_expiry,_))return P.access_token;return yield*U(P)})}),H=L.fnUntraced(function*(R){let T=yield*i7.currentTimeMillis;if(Kj(R.token_expiry,T))return R.access_token;return yield*oU.get(V,R.id)}),B=L.fnUntraced(function*(R){let T=yield*$.getRow(R);if(O1.isNone(T))return O1.none();let P=T.value,_=yield*H(P);return O1.some({account:P,accessToken:_})}),z=L.fnUntraced(function*(R,T){let P=yield*G(U$.get(`${R}/api/orgs`).pipe(U$.acceptJson,U$.bearerToken(T)));return yield*PZ.schemaBodyJson(O.Array(dY))(P).pipe(o8("Failed to decode response"))}),F=L.fnUntraced(function*(R,T){let P=yield*G(U$.get(`${R}/api/user`).pipe(U$.acceptJson,U$.bearerToken(T)));return yield*PZ.schemaBodyJson(Oj)(P).pipe(o8("Failed to decode response"))}),A=L.fn("Account.token")((R)=>B(R).pipe(L.map(O1.map((T)=>T.accessToken)))),N=L.fn("Account.activeOrg")(function*(){let R=yield*$.active();if(O1.isNone(R))return O1.none();let T=R.value;if(!T.active_org_id)return O1.none();let _=(yield*w(T.id)).find((C)=>C.id===T.active_org_id);if(!_)return O1.none();return O1.some({account:T,org:_})}),j=L.fn("Account.orgsByAccount")(function*(){let R=yield*$.list();return yield*L.forEach(R,(T)=>w(T.id).pipe(L.catch(()=>L.succeed([])),L.map((P)=>({account:T,orgs:P}))),{concurrency:3})}),w=L.fn("Account.orgs")(function*(R){let T=yield*B(R);if(O1.isNone(T))return[];let{account:P,accessToken:_}=T.value;return yield*z(P.url,_)}),q=L.fn("Account.config")(function*(R,T){let P=yield*B(R);if(O1.isNone(P))return O1.none();let{account:_,accessToken:C}=P.value,f=yield*Q(U$.get(`${_.url}/api/config`).pipe(U$.acceptJson,U$.bearerToken(C),U$.setHeaders({"x-org-id":T})));if(f.status===404)return O1.none();let b=yield*PZ.filterStatusOk(f).pipe(o8()),y=yield*PZ.schemaBodyJson(Bj)(b).pipe(o8("Failed to decode response"));return O1.some(y.config)}),M=L.fn("Account.login")(function*(R){let T=x9(R),P=yield*W(U$.post(`${T}/auth/device/code`).pipe(U$.acceptJson,U$.schemaBodyJson(sU)(new sU({client_id:iU})))),_=yield*PZ.schemaBodyJson(Fj)(P).pipe(o8("Failed to decode response"));return new pY({code:_.device_code,user:_.user_code,url:`${T}${_.verification_uri_complete}`,server:T,expiry:_.expires_in,interval:_.interval})}),E=L.fn("Account.poll")(function*(R){let T=yield*K(U$.post(`${R.server}/auth/device/token`).pipe(U$.acceptJson,U$.schemaBodyJson(rU)(new rU({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:R.code,client_id:iU})))),P=yield*PZ.schemaBodyJson(Ji)(T).pipe(o8("Failed to decode response"));if(P instanceof tU)return P.toPollResult();let _=P.access_token,C=F(R.server,_),f=z(R.server,_),[b,y]=yield*L.all([C,f],{concurrency:2}),k=y.length>0?O1.some(y[0].id):O1.none(),d=(yield*i7.currentTimeMillis)+Z8.toMillis(P.expires_in),p=P.refresh_token;return yield*$.persistAccount({id:b.id,email:b.email,url:R.server,accessToken:_,refreshToken:p,expiry:d,orgID:k}),new g7({email:b.email})});return m9.of({active:$.active,activeOrg:N,list:$.list,orgsByAccount:j,remove:$.remove,use:$.use,orgs:w,config:q,token:A,login:M,poll:E})})),Gi=qj.pipe(T0.provide(c7.layer),T0.provide(Vj.layer));import Wi from"path";async function Mj(){let $=["qitqode.jsonc","qitqode.json","config.json"].map((Z)=>Wi.join(F0.Path.config,Z));for(let Z of $)if(await o0.exists(Z))return Z;return $[0]}function eU($,Z,J=[]){if(!J8(Z)){let Y=Nj($,J,Z,{formattingOptions:{insertSpaces:!0,tabSize:2}});return jj($,Y)}return Object.entries(Z).reduce((Y,[X,Q])=>{if(Q===void 0)return Y;return eU(Y,Q,[...J,X])},$)}function o7($){let{plugin_origins:Z,mcp_origins:J,...Y}=$;return Y}var Ki=C0.create({service:"config.sources"});function Dj($,Z){if(!J8($))return $;let J={...$};if(!(("theme"in J)||("keybinds"in J)||("tui"in J)))return J;return delete J.theme,delete J.keybinds,delete J.tui,Ki.warn("tui keys in qitqode config are deprecated; move them to tui.json",{path:Z}),J}async function wj($,Z){if(!$.plugin)return $;for(let J=0;J<$.plugin.length;J++)$.plugin[J]=await s8.resolvePluginSpec($.plugin[J],Z);return $}var Ui=C0.create({service:"config.loader"});function Lj($){let Z=L.fnUntraced(function*(X){return yield*$.fs.readFileString(X).pipe(L.catchIf((Q)=>Q.reason._tag==="NotFound",()=>L.succeed(void 0)),L.orDie)}),J=L.fnUntraced(function*(X,Q){let G="path"in Q?Q.path:Q.source,W=yield*L.promise(()=>$V.substitute("path"in Q?{text:X,type:"path",path:Q.path}:{text:X,type:"virtual",...Q})),K=r8.jsonc(W,G),U=r8.schema($.info,Dj(K,G),G);if(!("path"in Q))return U;if(yield*L.promise(()=>wj(U,Q.path)),!U.$schema){U.$schema="https://opencode.ai/config.json";let V=X.replace(/^\s*\{/,`{
|
|
487
487
|
"$schema": "https://opencode.ai/config.json",`);yield*$.fs.writeFileString(Q.path,V).pipe(L.catch(()=>L.void))}return U}),Y=L.fnUntraced(function*(X){Ui.info("loading",{path:X});let Q=yield*Z(X);if(!Q)return{};return yield*J(Q,{path:X})});return{readConfigFile:Z,loadConfig:J,loadFile:Y}}import cY from"path";import{pathToFileURL as Vi}from"url";import ZV from"fs/promises";function Rj($){return L.fnUntraced(function*(){let Z=Tj({},j1(yield*$(cY.join(F0.Path.config,"config.json"))),j1(yield*$(cY.join(F0.Path.config,"qitqode.json"))),j1(yield*$(cY.join(F0.Path.config,"qitqode.jsonc")))),J=cY.join(F0.Path.config,"config");if(!(yield*L.promise(()=>ZV.access(J).then(()=>!0,()=>!1))))return Z;return yield*L.promise(()=>import(Vi(J).href,{with:{type:"toml"}}).then(async(X)=>{let{provider:Q,model:G,...W}=X.default;if(Q&&G)Z.model=`${Q}/${G}`;Z.$schema="https://opencode.ai/config.json",Z=j1(Z,W),await ZV.writeFile(cY.join(F0.Path.config,"config.json"),JSON.stringify(Z,null,2)),await ZV.unlink(J)}).catch(()=>{})),Z})}import SZ from"path";import dr from"os";function l9($,Z){let J=j1($,Z);if($.instructions&&Z.instructions)J.instructions=Array.from(new Set([...$.instructions,...Z.instructions]));return J}var IZ={};B1(IZ,{redactString:()=>Ej,redactCommand:()=>Oi,fromClaude:()=>Ai,Remote:()=>QV,OAuth:()=>XV,Local:()=>YV,Info:()=>Hi,ConfigMCP:()=>IZ});class YV extends O.Class("McpLocalConfig")({type:O.Literal("local").annotate({description:"Type of MCP server connection"}),command:O.mutable(O.Array(O.String)).annotate({description:"Command and arguments to run the MCP server"}),environment:O.optional(O.Record(O.String,O.String)).annotate({description:"Environment variables to set when running the MCP server"}),enabled:O.optional(O.Boolean).annotate({description:"Enable or disable the MCP server on startup"}),timeout:O.optional(O.Number).annotate({description:"Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."})}){static zod=w0(this)}class XV extends O.Class("McpOAuthConfig")({clientId:O.optional(O.String).annotate({description:"OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."}),clientSecret:O.optional(O.String).annotate({description:"OAuth client secret (if required by the authorization server)"}),scope:O.optional(O.String).annotate({description:"OAuth scopes to request during authorization"}),redirectUri:O.optional(O.String).annotate({description:"OAuth redirect URI (default: http://127.0.0.1:19876/mcp/oauth/callback)."})}){static zod=w0(this)}class QV extends O.Class("McpRemoteConfig")({type:O.Literal("remote").annotate({description:"Type of MCP server connection"}),url:O.String.annotate({description:"URL of the remote MCP server"}),enabled:O.optional(O.Boolean).annotate({description:"Enable or disable the MCP server on startup"}),headers:O.optional(O.Record(O.String,O.String)).annotate({description:"Headers to send with the request"}),oauth:O.optional(O.Union([XV,O.Literal(!1)])).annotate({description:"OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."}),timeout:O.optional(O.Number).annotate({description:"Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."})}){static zod=w0(this)}var Hi=O.Union([YV,QV]).annotate({discriminator:"type"}).pipe(u0(($)=>({zod:w0($)}))),Pj=new Set(["http","streamable-http","remote"]),Ij=new Set(["stdio","local"]),Bi=["authorization","token","api_key","apikey","key","secret","password","credential"];function JV($){if(!J8($))return;return Object.fromEntries(Object.entries($).filter((Z)=>typeof Z[1]==="string"))}function zi($){return Bi.some((Z)=>$.toLowerCase().includes(Z))}function Fi($){if($===!1)return!1;if(!J8($))return;let Z={...typeof $.clientId==="string"&&{clientId:$.clientId},...typeof $.clientSecret==="string"&&{clientSecret:$.clientSecret},...typeof $.scope==="string"&&{scope:$.scope},...typeof $.redirectUri==="string"&&{redirectUri:$.redirectUri}};return Object.keys(Z).length>0?Z:void 0}function Ai($,Z){if(!J8(Z))return{warning:`skipped Claude Code MCP server "${$}"; server config is not an object.`};if(Z.type==="sse")return{warning:`skipped Claude Code MCP server "${$}"; unsupported transport "sse".`};if(Z.args!==void 0&&!Array.isArray(Z.args))return{warning:`skipped Claude Code MCP server "${$}"; args is not an array.`};let J=Array.isArray(Z.args)?Z.args:[];if(!J.every((W)=>typeof W==="string"))return{warning:`skipped Claude Code MCP server "${$}"; args must contain only strings.`};let Y=Z.disabled===!0?!1:Z.enabled===!1?!1:!0,X=JV(Z.environment)??JV(Z.env),Q=typeof Z.timeout==="number"?Z.timeout:void 0,G=typeof Z.type==="string"?Z.type:void 0;if(typeof Z.command==="string"&&(!G||Ij.has(G)))return{config:{type:"local",command:[Z.command,...J],...X&&{environment:X},enabled:Y,...Q!==void 0&&{timeout:Q}}};if(Z.command!==void 0)return{warning:`skipped Claude Code MCP server "${$}"; command is not a string.`};if(typeof Z.url==="string"&&(!G||Pj.has(G))){let W=JV(Z.headers),K=Fi(Z.oauth);return{config:{type:"remote",url:Z.url,enabled:Y,...W&&{headers:W},...K!==void 0&&{oauth:K},...Q!==void 0&&{timeout:Q}}}}if(Z.url!==void 0)return{warning:`skipped Claude Code MCP server "${$}"; url is not a string.`};if(G&&!Ij.has(G)&&!Pj.has(G))return{warning:`skipped Claude Code MCP server "${$}"; unsupported transport "${G}".`};return{warning:`skipped Claude Code MCP server "${$}"; missing command or url.`}}function Ej($){return $.replace(/(Bearer\s+)[^\s]+/gi,"$1****").replace(/([?&][^=\s&]*(?:authorization|token|api[_-]?key|apikey|key|secret|password|credential)[^=\s&]*=)[^&\s]+/gi,"$1****").replace(/((?:authorization|token|api[_-]?key|apikey|key|secret|password|credential)=)[^\s]+/gi,"$1****")}function Oi($){return $.map((Z,J)=>{if(J>0&&zi($[J-1]))return"****";return Ej(Z)})}var GV=C0.create({service:"config.sources"});function Cj($){let Z=(G,W,K,U)=>{if(!K.mcp)return G;return{...G,mcp_origins:{...G.mcp_origins??{},...Object.fromEntries(Object.keys(K.mcp).map((V)=>[V,{type:U,source:W}]))}}},J=L.fnUntraced(function*(G,W,K,U){if(!K?.length)return G;let V=U??(yield*$.resolvePluginScope(W)),H=s8.deduplicatePluginOrigins([...G.plugin_origins??[],...K.map((B)=>({spec:B,source:W,scope:V}))]);return{...G,plugin:H.map((B)=>B.spec),plugin_origins:H}}),Y=L.fnUntraced(function*(G,W,K,U){let V=l9(G,K),H=Z(V,W,K,"qitqode");return yield*J(H,W,K.plugin,U)}),X=L.fnUntraced(function*(G){let W=yield*$.readConfigFile(G);if(!W)return;return yield*L.try({try:()=>JSON.parse(W),catch:()=>Error(`failed to parse ${G}; Claude Code MCP compatibility skipped.`)}).pipe(L.tapError((K)=>L.sync(()=>GV.warn(K.message))),L.option,L.map(O1.getOrUndefined))}),Q=L.fnUntraced(function*(G,W){let K=yield*X(W);if(!J8(K)||!J8(K.mcpServers))return G;let U=G;for(let[V,H]of Object.entries(K.mcpServers)){if(U.mcp?.[V]&&U.mcp_origins?.[V]?.type!=="claude"){GV.info(`skipped Claude Code MCP server "${V}"; native qitqode MCP with same name already exists.`);continue}let z=IZ.fromClaude(V,H);if("warning"in z){GV.warn(z.warning);continue}let F=r8.schema($.info,{mcp:{[V]:z.config}},W);U={...U,mcp:{...U.mcp??{},[V]:F.mcp[V]},mcp_origins:{...U.mcp_origins??{},[V]:{type:"claude",source:W}}}}return U});return{merge:Y,mergeMcpOrigins:Z,mergePluginOrigins:J,mergeClaudeMcp:Q}}function bj($,Z){let J=$;for(let[Y,X]of Object.entries(J.mode??{}))J.agent=j1(J.agent??{},{[Y]:{...X,mode:"primary"}});if(Z.permissionOverride)J.permission=j1(J.permission??{},JSON.parse(Z.permissionOverride));if(J.tools){let Y={};for(let[X,Q]of Object.entries(J.tools)){let G=Q?"allow":"deny";if(X==="write"||X==="edit"||X==="patch"||X==="multiedit"){Y.edit=G;continue}Y[X]=G}J.permission=j1(Y,J.permission??{})}if(!J.username)J.username=Z.username;if(J.autoshare===!0&&!J.share)J.share="auto";if(Z.disableAutoCompact)J.compaction={...J.compaction,auto:!1};if(Z.disablePrune)J.compaction={...J.compaction,prune:!1};return J}var d6={};B1(d6,{loadMode:()=>vr,load:()=>kr,Info:()=>_V,ConfigAgent:()=>d6});import _j from"path";function qi($,Z){let J=$.replaceAll("\\","/");for(let Y of Z){let X=J.indexOf(Y);if(X===-1)continue;return J.slice(X+Y.length)}}function Sj($,Z){let J=qi($,Z)??_j.basename($),Y=_j.extname(J);return Y.length?J.slice(0,-Y.length):J}var bV={};B1(bV,{shell:()=>wr,parse:()=>CV,files:()=>Dr,fallbackSanitization:()=>eD,SHELL_REGEX:()=>tD,FrontmatterError:()=>$X,FILE_REGEX:()=>aD});var EV=h6(rD(),1);var aD=/(?<![\w`])@(\.?[^\s`,.]*(?:\.[^\s`,.]+)*)/g,tD=/!`([^`]+)`/g;function Dr($){return Array.from($.matchAll(aD))}function wr($){return Array.from($.matchAll(tD))}function eD($){let Z=$.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!Z)return $;let J=Z[1],Y=J.split(/\r?\n/),X=[];for(let G of Y){if(G.trim().startsWith("#")||G.trim()===""){X.push(G);continue}if(G.match(/^\s+/)){X.push(G);continue}let W=G.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\s*:\s*(.*)$/);if(!W){X.push(G);continue}let K=W[1],U=W[2].trim();if(U===""||U===">"||U==="|"||U.startsWith('"')||U.startsWith("'")){X.push(G);continue}if(U.includes(":")){X.push(`${K}: |-`),X.push(` ${U}`);continue}X.push(G)}let Q=X.join(`
|
|
488
|
-
`);return $.replace(J,()=>Q)}async function CV($){let Z=await o0.readText($);try{return EV.default(Z,{})}catch(J){let Y=eD(Z);if(Y===Z)throw new $X({path:$,message:`${$}: Failed to parse YAML frontmatter: ${J instanceof Error?J.message:String(J)}`},{cause:J});try{return EV.default(Y,{})}catch(X){throw new $X({path:$,message:`${$}: Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`},{cause:X})}}}var $X=N1.create("ConfigFrontmatterError",D.object({path:D.string(),message:D.string()}));var Lr=C0.create({service:"config"});function ZX($,Z,J,Y){let X=$.safeParse(Z);if(X.success)return X.data;if(Y?.ignoreInvalid)return;throw new $w({path:J,issues:X.error.issues},{cause:X.error})}async function JX($){for(let Z of await Z4.scan($.glob,{cwd:$.dir,absolute:!0,dot:!0,symlink:!0})){let J=await CV(Z).catch(async(Q)=>{let G=$X.isInstance(Q)?Q.data.message:`Failed to parse ${$.entity} ${Z}`,{Session:W}=await import("./chunk-
|
|
488
|
+
`);return $.replace(J,()=>Q)}async function CV($){let Z=await o0.readText($);try{return EV.default(Z,{})}catch(J){let Y=eD(Z);if(Y===Z)throw new $X({path:$,message:`${$}: Failed to parse YAML frontmatter: ${J instanceof Error?J.message:String(J)}`},{cause:J});try{return EV.default(Y,{})}catch(X){throw new $X({path:$,message:`${$}: Failed to parse YAML frontmatter: ${X instanceof Error?X.message:String(X)}`},{cause:X})}}}var $X=N1.create("ConfigFrontmatterError",D.object({path:D.string(),message:D.string()}));var Lr=C0.create({service:"config"});function ZX($,Z,J,Y){let X=$.safeParse(Z);if(X.success)return X.data;if(Y?.ignoreInvalid)return;throw new $w({path:J,issues:X.error.issues},{cause:X.error})}async function JX($){for(let Z of await Z4.scan($.glob,{cwd:$.dir,absolute:!0,dot:!0,symlink:!0})){let J=await CV(Z).catch(async(Q)=>{let G=$X.isInstance(Q)?Q.data.message:`Failed to parse ${$.entity} ${Z}`,{Session:W}=await import("./chunk-tnn7hm4v.js");l1.publish(W.Event.Error,{error:new N1.Unknown({message:G}).toObject()}),Lr.error(`failed to load ${$.entity}`,{[$.entity]:Z,err:Q});return});if(!J)continue;let X={name:Sj(Z,$.namePatterns),...J.data,[$.contentKey]:J.content.trim()};$.store(X,Z)}}var L8=O.String.annotate({[F$]:I.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"})}).pipe(u0(($)=>({zod:w0($)})));var _Z={};B1(_Z,{Rule:()=>T8,Object:()=>Jw,Info:()=>Er,ConfigPermission:()=>_Z,Action:()=>l6});var l6=O.Literals(["ask","allow","deny"]).annotate({identifier:"PermissionActionConfig"}).pipe(u0(($)=>({zod:w0($)}))),Jw=O.Record(O.String,l6).annotate({identifier:"PermissionObjectConfig"}).pipe(u0(($)=>({zod:w0($)}))),T8=O.Union([l6,Jw]).annotate({identifier:"PermissionRuleConfig"}).pipe(u0(($)=>({zod:w0($)}))),Tr=($)=>{if(typeof $==="object"&&$!==null&&!Array.isArray($))return{__originalKeys:globalThis.Object.keys($),...$};return $},Rr=O.StructWithRest(O.Struct({__originalKeys:O.optional(O.mutable(O.Array(O.String))),read:O.optional(T8),edit:O.optional(T8),glob:O.optional(T8),grep:O.optional(T8),list:O.optional(T8),bash:O.optional(T8),task:O.optional(T8),actor:O.optional(T8),external_directory:O.optional(T8),question:O.optional(l6),webfetch:O.optional(l6),websearch:O.optional(l6),codesearch:O.optional(l6),lsp:O.optional(T8),doom_loop:O.optional(l6),skill:O.optional(T8)}),[O.Record(O.String,T8)]),Pr=O.Union([Rr,l6]).annotate({[Zw]:Tr}),Ir=($)=>{if(typeof $==="string")return{"*":$};let Z=$,{__originalKeys:J,...Y}=Z;if(!J)return Y;let X={};for(let Q of J)if(Q in Y)X[Q]=Y[Q];return X},Er=w0(Pr).transform(Ir).meta({ref:"PermissionConfig"});var Yw=O.Number.check(O.isInt()).check(O.isGreaterThan(0)),Cr=O.Union([O.String.check(O.isPattern(/^#[0-9a-fA-F]{6}$/)),O.Literals(["primary","secondary","accent","success","warning","error","info"])]),br=O.Any.annotate({[F$]:_Z.Info}),_r=O.StructWithRest(O.Struct({model:O.optional(L8).annotate({description:"Model for this agent: a literal provider/model (e.g. anthropic/claude-opus-4-8) or a tier/group name (e.g. fast/economical/default/power). Names without a '/' are resolved as model groups, provider-aware, at spawn time."}),variant:O.optional(O.String).annotate({description:"Default model variant for this agent (applies only when using the agent's configured model)."}),temperature:O.optional(O.Number),top_p:O.optional(O.Number),prompt:O.optional(O.String),tools:O.optional(O.Record(O.String,O.Boolean)).annotate({description:"@deprecated Use 'permission' field instead"}),disable:O.optional(O.Boolean),description:O.optional(O.String).annotate({description:"Description of when to use the agent"}),mode:O.optional(O.Literals(["subagent","primary","all"])),hidden:O.optional(O.Boolean).annotate({description:"Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"}),options:O.optional(O.Record(O.String,O.Any)),color:O.optional(Cr).annotate({description:"Hex color code (e.g., #FF5733) or theme color (e.g., primary)"}),steps:O.optional(Yw).annotate({description:"Maximum number of agentic iterations before forcing text-only response"}),tool_allowlist:O.optional(O.Array(O.String)).annotate({description:"Optional list of tool IDs allowed for this agent. When set, only these tools are available."}),maxSteps:O.optional(Yw).annotate({description:"@deprecated Use 'steps' field instead."}),permission:O.optional(br)}),[O.Record(O.String,O.Any)]),Sr=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools","tool_allowlist"]),fr=($)=>{let Z={...$.options};for(let[Y,X]of Object.entries($))if(!Sr.has(Y))Z[Y]=X;let J={};for(let[Y,X]of Object.entries($.tools??{})){let Q=X?"allow":"deny";if(Y==="write"||Y==="edit"||Y==="patch"||Y==="multiedit"){J.edit=Q;continue}if(Y==="task"){J.actor=Q;continue}J[Y]=Q}return globalThis.Object.assign(J,$.permission),{...$,options:Z,permission:J,steps:$.steps??$.maxSteps}},_V=w0(_r).transform(fr).meta({ref:"AgentConfig"});async function kr($){let Z={};return await JX({dir:$,glob:"{agent,agents}/**/*.md",entity:"agent",namePatterns:["/.qitqode/agent/","/.qitqode/agents/","/agent/","/agents/"],contentKey:"prompt",store:(J,Y)=>{Z[J.name]=ZX(_V,J,Y)}}),Z}async function vr($){let Z={};return await JX({dir:$,glob:"{mode,modes}/*.md",entity:"mode",namePatterns:[],contentKey:"prompt",store:(J,Y)=>{let X=ZX(_V,J,Y,{ignoreInvalid:!0});if(X)Z[J.name]={...X,mode:"primary"}}}),Z}var p6={};B1(p6,{load:()=>yr,Info:()=>Xw,ConfigCommand:()=>p6});var Xw=O.Struct({template:O.String,description:O.optional(O.String),agent:O.optional(O.String),model:O.optional(L8),subtask:O.optional(O.Boolean)}).pipe(u0(($)=>({zod:w0($)})));async function yr($){let Z={};return await JX({dir:$,glob:"{command,commands}/**/*.md",entity:"command",namePatterns:["/.qitqode/command/","/.qitqode/commands/","/.claude/command/","/.claude/commands/","/command/","/commands/"],contentKey:"template",store:(J,Y)=>{Z[J.name]=ZX(Xw.zod,J,Y)}}),Z}var T5={};B1(T5,{readManagedPreferences:()=>lr,parseManagedPlist:()=>Kw,managedConfigDirs:()=>Ww,managedConfigDir:()=>mr,ConfigManaged:()=>T5});import xr from"os";import SV from"path";var Qw=C0.create({service:"config"}),hr="ai.qitqode.managed",gr="ai.opencode.managed",ur=new Set(["PayloadDisplayName","PayloadIdentifier","PayloadType","PayloadUUID","PayloadVersion","_manualProfile"]);function Gw($="qitqode"){switch(process.platform){case"darwin":return`/Library/Application Support/${$}`;case"win32":return SV.join(process.env.ProgramData||"C:\\ProgramData",$);default:return`/etc/${$}`}}function mr(){return Ww().at(-1)}function Ww(){let $=process.env.QITQODE_TEST_MANAGED_CONFIG_DIR;if($)return[$];return[Gw("opencode"),Gw()]}function Kw($){let Z=JSON.parse($);for(let J of Object.keys(Z))if(ur.has(J))delete Z[J];return JSON.stringify(Z)}async function lr(){if(process.platform!=="darwin")return;let $=xr.userInfo().username,Z=[gr,hr].flatMap((J)=>[SV.join("/Library/Managed Preferences",$,`${J}.plist`),SV.join("/Library/Managed Preferences",`${J}.plist`)]);for(let J of Z){if(!await o0.exists(J))continue;Qw.info("reading macOS managed preferences",{path:J});let Y=await f1.run(["plutil","-convert","json","-o","-",J],{nothrow:!0});if(Y.code!==0){Qw.warn("failed to convert managed preferences plist",{path:J});continue}return{source:`mobileconfig:${J}`,text:Kw(Y.stdout.toString())}}return}var fZ=C0.create({service:"config"});function Hw($){let{fs:Z,authSvc:J,accountSvc:Y,env:X,npmSvc:Q,readConfigFile:G,loadConfig:W,loadFile:K,getGlobal:U}=$,V=L.fn("Config.ensureGitignore")(function*(B){let z=SZ.join(B,".gitignore");if(!(yield*Z.existsSafe(z)))yield*Z.writeFileString(z,["node_modules","package.json","package-lock.json","bun.lock",".gitignore"].join(`
|
|
489
489
|
`)).pipe(L.catchIf((A)=>A.reason._tag==="PermissionDenied",()=>L.void))});return{loadInstanceState:L.fn("Config.loadInstanceState")(function*(B){let z=yield*J.all().pipe(L.orDie),F={},A=new Set,N,j=L.fnUntraced(function*(P){if(P.startsWith("http://")||P.startsWith("https://"))return"global";if(P==="QITQODE_CONFIG_CONTENT")return"local";if(yield*Vw.use((_)=>L.succeed(S8.containsPath(P,_))))return"local";return"global"}),w=Cj({info:$.info,readConfigFile:G,resolvePluginScope:j});for(let[P,_]of Object.entries(z))if(_.type==="wellknown"){let C=P.replace(/\/+$/,"");process.env[_.key]=_.token,fZ.debug("fetching remote config",{url:`${C}/.well-known/opencode`});let f=yield*L.promise(()=>fetch(`${C}/.well-known/opencode`,{signal:AbortSignal.timeout(1000)}));if(!f.ok)throw Error(`failed to fetch remote config from ${C}: ${f.status}`);let y=(yield*L.promise(()=>f.json())).config??{};if(!y.$schema)y.$schema="https://opencode.ai/config.json";let k=`${C}/.well-known/opencode`,g=yield*W(JSON.stringify(y),{dir:SZ.dirname(k),source:k});F=yield*w.merge(F,k,g,"global"),fZ.debug("loaded remote config from well-known",{url:C})}let q=yield*U();if(F=yield*w.merge(F,F0.Path.config,q,"global"),b0.QITQODE_CONFIG)F=yield*w.merge(F,b0.QITQODE_CONFIG,yield*K(b0.QITQODE_CONFIG)),fZ.debug("loaded custom config",{path:b0.QITQODE_CONFIG});if(!b0.QITQODE_DISABLE_PROJECT_CONFIG)for(let P of yield*YX.files("qitqode",B.directory,B.worktree).pipe(L.orDie))F=yield*w.merge(F,P,yield*K(P),"local");F.agent=F.agent||{},F.mode=F.mode||{},F.plugin=F.plugin||[];let M=yield*YX.directories(B.directory,B.worktree);if(b0.QITQODE_CONFIG_DIR)fZ.debug("loading config from QITQODE_CONFIG_DIR",{path:b0.QITQODE_CONFIG_DIR});let E=[];for(let P of yield*YX.claudeCommandDirectories(B.directory,B.worktree))F.command=j1(F.command??{},yield*L.promise(()=>p6.load(P)));for(let P of M){if(P.endsWith(".qitqode")||P===b0.QITQODE_CONFIG_DIR)for(let f of["qitqode.json","qitqode.jsonc"]){let b=SZ.join(P,f);fZ.debug(`loading config from ${b}`),F=yield*w.merge(F,b,yield*K(b)),F.agent??={},F.mode??={},F.plugin??=[]}yield*V(P).pipe(L.orDie);let _=yield*Q.install(P,{add:[{name:"@qitqode/plugin",version:Uw?void 0:O$}]}).pipe(L.exit,L.tap((f)=>z9.isFailure(f)?L.sync(()=>{fZ.warn("background dependency install failed",{dir:P,error:String(f.cause)})}):L.void),L.asVoid,L.forkDetach);E.push(_),F.command=j1(F.command??{},yield*L.promise(()=>p6.load(P))),F.agent=j1(F.agent??{},yield*L.promise(()=>d6.load(P))),F.agent=j1(F.agent??{},yield*L.promise(()=>d6.loadMode(P)));let C=yield*L.promise(()=>s8.load(P));F=yield*w.mergePluginOrigins(F,P,C)}if(process.env.QITQODE_CONFIG_CONTENT){let _=yield*W(process.env.QITQODE_CONFIG_CONTENT,{dir:B.directory,source:"QITQODE_CONFIG_CONTENT"});F=yield*w.merge(F,"QITQODE_CONFIG_CONTENT",_,"local"),fZ.debug("loaded custom config from QITQODE_CONFIG_CONTENT")}let R=O1.getOrUndefined(yield*Y.active().pipe(L.catch(()=>L.succeed(O1.none()))));if(R?.active_org_id){let{id:P,active_org_id:_,url:C}=R;yield*L.gen(function*(){let[f,b]=yield*L.all([Y.config(P,_),Y.token(P)],{concurrency:2});if(O1.isSome(b))process.env.QITQODE_CONSOLE_TOKEN=b.value,yield*X.set("QITQODE_CONSOLE_TOKEN",b.value);if(O1.isSome(f)){let y=`${C}/api/config`,k=yield*W(JSON.stringify(f.value),{dir:SZ.dirname(y),source:y});for(let g of Object.keys(k.provider??{}))A.add(g);F=yield*w.merge(F,y,k,"global")}}).pipe(L.withSpan("Config.loadActiveOrgConfig"),L.catch((f)=>{return fZ.debug("failed to fetch remote account config",{error:f instanceof Error?f.message:String(f)}),L.void}))}for(let P of T5.managedConfigDirs()){if(!(yield*L.promise(()=>o0.exists(P))))continue;for(let _ of["qitqode.json","qitqode.jsonc"]){let C=SZ.join(P,_);F=yield*w.merge(F,C,yield*K(C),"global")}}let T=yield*L.promise(()=>T5.readManagedPreferences());if(T){let P=yield*W(T.text,{dir:SZ.dirname(T.source),source:T.source});F=w.mergeMcpOrigins(l9(F,P),T.source,P,"qitqode")}if(!b0.QITQODE_DISABLE_CLAUDE_CODE_MCP)F=yield*w.mergeClaudeMcp(F,SZ.join(F0.Path.home,".claude.json")),F=yield*w.mergeClaudeMcp(F,SZ.join(B.directory,".claude.json"));return F=bj(F,{username:dr.userInfo().username,permissionOverride:b0.QITQODE_PERMISSION,disableAutoCompact:b0.QITQODE_DISABLE_AUTOCOMPACT,disablePrune:b0.QITQODE_DISABLE_PRUNE}),{config:F,directories:M,deps:E,consoleState:{consoleManagedProviders:Array.from(A),activeOrgName:N,switchableOrgCount:0}}},L.provideService(C$.Service,Z)),ensureGitignore:V}}var R5={};B1(R5,{Layout:()=>pr,ConfigLayout:()=>R5});var pr=O.Literals(["auto","stretch"]).annotate({identifier:"LayoutConfig"}).pipe(u0(($)=>({zod:w0($)})));var P5={};B1(P5,{Server:()=>Bw,ConfigServer:()=>P5});class Bw extends O.Class("ServerConfig")({port:O.optional(O.Number.check(O.isInt()).check(O.isGreaterThan(0))).annotate({description:"Port to listen on"}),hostname:O.optional(O.String).annotate({description:"Hostname to listen on"}),mdns:O.optional(O.Boolean).annotate({description:"Enable mDNS service discovery"}),mdnsDomain:O.optional(O.String).annotate({description:"Custom domain name for mDNS service (default: qitqode.local)"}),cors:O.optional(O.mutable(O.Array(O.String))).annotate({description:"Additional domains to allow for CORS"})}){static zod=w0(this)}var XJ={};B1(XJ,{Info:()=>cr,Entry:()=>zw,ConfigFormatter:()=>XJ});var zw=O.Struct({disabled:O.optional(O.Boolean),command:O.optional(O.mutable(O.Array(O.String))),environment:O.optional(O.Record(O.String,O.String)),extensions:O.optional(O.mutable(O.Array(O.String)))}).pipe(u0(($)=>({zod:w0($)}))),cr=O.Union([O.Boolean,O.Record(O.String,zw)]).pipe(u0(($)=>({zod:w0($)})));var XX={};B1(XX,{Kind:()=>Fw,Info:()=>ir,ConfigHistory:()=>XX});var Fw=O.Literals(["user_text","assistant_text","tool_input","tool_error","reasoning","tool_output"]),ir=O.Struct({kinds:O.optional(O.Array(Fw)).annotate({description:"Which part kinds the history FTS index should cover. Defaults to text (user/assistant) + tool input + tool errors. Add 'reasoning' or 'tool_output' to grow recall at the cost of database size. Note: enabling 'tool_output' reclassifies completed tools from kind='tool_input' to kind='tool_output' (input remains searchable in the body, but kind:['tool_input'] filter will then only match pending/error tools)."})});var QJ={};B1(QJ,{requiresExtensionsForCustomServers:()=>qw,Info:()=>nr,Entry:()=>Ow,Disabled:()=>Aw,ConfigLSP:()=>QJ});var Aw=O.Struct({disabled:O.Literal(!0)}).pipe(u0(($)=>({zod:w0($)}))),Ow=O.Union([Aw,O.Struct({command:O.mutable(O.Array(O.String)),extensions:O.optional(O.mutable(O.Array(O.String))),disabled:O.optional(O.Boolean),env:O.optional(O.Record(O.String,O.String)),initialization:O.optional(O.Record(O.String,O.Unknown))})]).pipe(u0(($)=>({zod:w0($)}))),qw=O.makeFilter(($)=>{if(typeof $==="boolean")return;let Z=new Set(Object.values(_7).map((Y)=>Y.id));return Object.entries($).every(([Y,X])=>{if("disabled"in X&&X.disabled)return!0;if(Z.has(Y))return!0;return"extensions"in X&&Boolean(X.extensions)})?void 0:"For custom LSP servers, 'extensions' array is required."}),nr=O.Union([O.Boolean,O.Record(O.String,Ow)]).check(qw).pipe(u0(($)=>({zod:w0($)})));var GJ={};B1(GJ,{Model:()=>jw,Info:()=>Mw,ConfigProvider:()=>GJ});var Nw=O.Number.check(O.isInt()).check(O.isGreaterThan(0)),jw=O.Struct({id:O.optional(O.String),name:O.optional(O.String),family:O.optional(O.String),release_date:O.optional(O.String),attachment:O.optional(O.Boolean),reasoning:O.optional(O.Boolean),temperature:O.optional(O.Boolean),tool_call:O.optional(O.Boolean),interleaved:O.optional(O.Union([O.Literal(!0),O.Struct({field:O.Literals(["reasoning_content","reasoning_details"])})])),cost:O.optional(O.Struct({input:O.Number,output:O.Number,cache_read:O.optional(O.Number),cache_write:O.optional(O.Number),context_over_200k:O.optional(O.Struct({input:O.Number,output:O.Number,cache_read:O.optional(O.Number),cache_write:O.optional(O.Number)}))})),limit:O.optional(O.Struct({context:O.Number,input:O.optional(O.Number),output:O.Number})),modalities:O.optional(O.Struct({input:O.mutable(O.Array(O.Literals(["text","audio","image","video","pdf"]))),output:O.mutable(O.Array(O.Literals(["text","audio","image","video","pdf"])))})),experimental:O.optional(O.Boolean),status:O.optional(O.Literals(["alpha","beta","deprecated"])),cachePromptTTL:O.optional(O.Literals(["5m","1h"])).annotate({description:"Prompt-cache breakpoint TTL for Anthropic/OpenRouter. '1h' keeps the cached prefix alive for one hour (2x write cost) instead of the 5m default. Ignored by providers whose SDK doesn't support a cache TTL."}),provider:O.optional(O.Struct({npm:O.optional(O.String),api:O.optional(O.String)})),options:O.optional(O.Record(O.String,O.Any)),headers:O.optional(O.Record(O.String,O.String)),variants:O.optional(O.Record(O.String,O.StructWithRest(O.Struct({disabled:O.optional(O.Boolean).annotate({description:"Disable this variant for the model"})}),[O.Record(O.String,O.Any)])).annotate({description:"Variant-specific configuration"}))}).pipe(u0(($)=>({zod:w0($)})));class Mw extends O.Class("ProviderConfig")({api:O.optional(O.String),name:O.optional(O.String),env:O.optional(O.mutable(O.Array(O.String))),id:O.optional(O.String),npm:O.optional(O.String),whitelist:O.optional(O.mutable(O.Array(O.String))),blacklist:O.optional(O.mutable(O.Array(O.String))),options:O.optional(O.StructWithRest(O.Struct({apiKey:O.optional(O.String),baseURL:O.optional(O.String),enterpriseUrl:O.optional(O.String).annotate({description:"GitHub Enterprise URL for copilot authentication"}),setCacheKey:O.optional(O.Boolean).annotate({description:"Enable promptCacheKey for this provider (default false)"}),timeout:O.optional(O.Union([Nw,O.Literal(!1)]).annotate({description:"Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."})).annotate({description:"Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."}),chunkTimeout:O.optional(Nw).annotate({description:"Timeout in milliseconds between streamed SSE chunks for this provider. If no chunk arrives within this window, the request is aborted."})}),[O.Record(O.String,O.Any)])),models:O.optional(O.Record(O.String,jw))}){static zod=w0(this)}var WJ={};B1(WJ,{Info:()=>or,ConfigSkills:()=>WJ});var or=O.Struct({paths:O.optional(O.Array(O.String)).annotate({description:"Additional paths to skill folders"}),urls:O.optional(O.Array(O.String)).annotate({description:"URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)"})}).pipe(u0(($)=>({zod:w0($)})));var a8=O.Any.annotate({[F$]:d6.Info}),sr=O.Any.annotate({[F$]:_Z.Info}),rr=O.Any.annotate({[F$]:C0.Level}),m$=O.Number.check(O.isInt()).check(O.isGreaterThan(0)),I5=O.Number.check(O.isInt()).check(O.isGreaterThanOrEqualTo(0)),ar=O.Struct({$schema:O.optional(O.String).annotate({description:"JSON schema reference for configuration validation"}),logLevel:O.optional(rr).annotate({description:"Log level"}),server:O.optional(P5.Server).annotate({description:"Server configuration for qitqode serve and web commands"}),command:O.optional(O.Record(O.String,p6.Info)).annotate({description:"Command configuration, see https://opencode.ai/docs/commands"}),skills:O.optional(WJ.Info).annotate({description:"Additional skill folder paths"}),watcher:O.optional(O.Struct({ignore:O.optional(O.mutable(O.Array(O.String)))})),snapshot:O.optional(O.Boolean).annotate({description:"Enable or disable snapshot tracking. When false, filesystem snapshots are not recorded and undoing or reverting will not undo/redo file changes. Defaults to true."}),plugin:O.optional(O.mutable(O.Array(s8.Spec))),share:O.optional(O.Literals(["manual","auto","disabled"])).annotate({description:"Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing"}),autoshare:O.optional(O.Boolean).annotate({description:"@deprecated Use 'share' field instead. Share newly created sessions automatically"}),autoupdate:O.optional(O.Union([O.Boolean,O.Literal("notify")])).annotate({description:"Update behavior. Defaults to notifications only; set true to auto-install patch updates, false to disable checks, or 'notify' to show notifications"}),disabled_providers:O.optional(O.mutable(O.Array(O.String))).annotate({description:"Disable providers that are loaded automatically"}),enabled_providers:O.optional(O.mutable(O.Array(O.String))).annotate({description:"When set, ONLY these providers will be enabled. All other providers will be ignored"}),model:O.optional(L8).annotate({description:"Model to use in the format of provider/model, eg anthropic/claude-2"}),small_model:O.optional(L8).annotate({description:"Small model to use for tasks like title generation in the format of provider/model"}),model_groups:O.optional(O.Record(O.String,O.Union([L8,O.Struct({default:L8,models:O.optional(O.mutable(O.Array(L8)))})]))).annotate({description:"Named model groups (capability tiers, e.g. fast/economical/default/power). Each group has a default model and optional member models. A group name can be used anywhere a provider/model string is accepted."}),default_agent:O.optional(O.String).annotate({description:"Default agent to use when none is specified. Must be a primary agent. Falls back to 'build' if not set or if the specified agent is invalid."}),username:O.optional(O.String).annotate({description:"Custom username to display in conversations instead of system username"}),mode:O.optional(O.StructWithRest(O.Struct({build:O.optional(a8),plan:O.optional(a8)}),[O.Record(O.String,a8)])).annotate({description:"@deprecated Use `agent` field instead."}),agent:O.optional(O.StructWithRest(O.Struct({plan:O.optional(a8),build:O.optional(a8),general:O.optional(a8),explore:O.optional(a8),title:O.optional(a8),summary:O.optional(a8),compaction:O.optional(a8)}),[O.Record(O.String,a8)])).annotate({description:"Agent configuration, see https://opencode.ai/docs/agents"}),provider:O.optional(O.Record(O.String,GJ.Info)).annotate({description:"Custom provider configurations and model overrides"}),mcp:O.optional(O.Record(O.String,O.Union([IZ.Info,O.Any.annotate({[F$]:I.object({enabled:I.boolean()}).strict()})]))).annotate({description:"MCP (Model Context Protocol) server configurations"}),formatter:O.optional(XJ.Info),lsp:O.optional(QJ.Info),instructions:O.optional(O.mutable(O.Array(O.String))).annotate({description:"Additional instruction files or patterns to include"}),layout:O.optional(R5.Layout).annotate({description:"@deprecated Always uses stretch layout."}),permission:O.optional(sr),tools:O.optional(O.Record(O.String,O.Boolean)),tool:O.optional(O.Struct({invocation_style:O.optional(O.Literals(["json","shell"])).annotate({description:"Default invocation style for all tools. 'json' (default) exposes the original Zod schema; 'shell' exposes a single `script` parameter and uses the tool's shell.parse mapping."}),invocation_style_by_tool:O.optional(O.Record(O.String,O.Literals(["json","shell"]))).annotate({description:"Per-tool override of invocation_style. Keys are tool IDs. A tool without a `shell` field falls back to JSON regardless of this setting."})})).annotate({description:"Tool invocation style configuration (JSON vs shell-style)."}),enterprise:O.optional(O.Struct({url:O.optional(O.String).annotate({description:"Enterprise URL"})})),compaction:O.optional(O.Struct({auto:O.optional(O.Boolean).annotate({description:"Enable automatic compaction when context is full (default: true)"}),prune:O.optional(O.Boolean).annotate({description:"Enable pruning of old tool outputs (default: true)"}),tail_turns:O.optional(I5).annotate({description:"Number of recent user turns, including their following assistant/tool responses, to keep verbatim during compaction (default: 2)"}),preserve_recent_tokens:O.optional(I5).annotate({description:"Maximum number of tokens from recent turns to preserve verbatim after compaction"}),reserved:O.optional(I5).annotate({description:"Token buffer for compaction. Leaves enough window to avoid overflow during compaction."})})),checkpoint:O.optional(O.Struct({thresholds:O.optional(O.Array(O.String)).annotate({description:'Context fill thresholds that trigger checkpoint writes. Strings may be percentages ("40%"), absolute tokens ("100K", "1.5M"), or mixed ("100K", "50%"). Each threshold must be <= window - 20K reserved. Default: ["40%", "60%", "80%"].'}),reserved:O.optional(I5).annotate({description:"Token buffer reserved for checkpoint operations. Default: 20000."}),max_writer_failures:O.optional(m$).annotate({description:"Maximum consecutive writer failures per session before checkpointing stops retrying until process restart. Default: 3."}),fork:O.optional(O.Boolean).annotate({description:"Whether to fork the parent agent's message prefix into the writer session for prefix-cache reuse. Requires provider cache-breakpoint support. Default: false."}),push_caps:O.optional(O.Struct({tasks_ledger:O.optional(m$).annotate({description:"Token cap for the tasks ledger section of rebuild context. Default: 2000."}),focus_task:O.optional(m$).annotate({description:"Token cap for the focus task body in rebuild context. Default: 4000."}),actor_ledger:O.optional(m$).annotate({description:"Token cap for the actor ledger section of rebuild context. Default: 500."}),memory_titles:O.optional(m$).annotate({description:"Token cap for memory titles in rebuild context. Default: 500."}),global:O.optional(m$).annotate({description:"Token cap for the global memory section (global/MEMORY.md) of rebuild context. Default: 6000."}),checkpoint:O.optional(m$).annotate({description:"Token cap for the session checkpoint section (checkpoint.md) of rebuild context. Default: 11000."}),memory:O.optional(m$).annotate({description:"Token cap for the project memory section (MEMORY.md) of rebuild context. Default: 10000."}),notes:O.optional(m$).annotate({description:"Token cap for the session notes (notes.md) of rebuild context. Default: 6000."}),design_decisions:O.optional(m$).annotate({description:"Token cap for \xA710 Design decisions section of checkpoint.md (writer-side budget validation). Default: 3000."}),open_notes:O.optional(m$).annotate({description:"Token cap for \xA711 Open notes section of checkpoint.md (writer-side budget validation). Default: 800."}),recent_user:O.optional(I5).annotate({description:"Token cap for the recent user input section (verbatim user messages from the live DB, FIFO eviction). Default: 16000. Set 0 to disable."}),recent_user_per_msg:O.optional(m$).annotate({description:"Per-message cap inside recent user input section; oversized messages get head/tail truncation with messageID elision marker. Default: 2000."})})).annotate({description:"Per-section token caps for rebuild context (renderRebuildContext). Each section is loaded up to its cap so the rebuild stays within a predictable budget."}),task_archive_days:O.optional(m$).annotate({description:"Number of days after task done/abandoned before it's filtered out of `list({include_archived: false})`. Rows are NOT deleted \u2014 see v9 for true GC. Default: 7."}),task_cleanup_days:O.optional(m$).annotate({description:"[deprecated] Alias for task_archive_days. Will be removed in v9."}),memory_reconcile_on_search:O.optional(O.Boolean).annotate({description:"Whether to reconcile memory state on search operations. Default: true."}),memory_search_score_floor:O.optional(O.Number).annotate({description:"Relative BM25 floor for memory.search (OR-joined query): keep results scoring >= this fraction of the top hit, dropping common-word-only noise. The #1 result is always kept. Default: 0.15. Set 0 to keep all matches."})})),memory:O.optional(O.Struct({cc_index:O.optional(O.Boolean).annotate({description:"Index Claude Code memory (~/.claude/projects/<slug>/memory) and expose under scope='cc'. Default: false. Note: when enabled, every qitqode agent (build/explore/subagents) can search these memories via the builtin `memory` tool \u2014 including CC's `type: user` (your role/preferences) and `type: feedback` (your guidance) categories. CC originally writes them for future CC sessions; flipping this on widens the consumer set to qitqode agents on the same machine. Leave disabled (default) if you don't want personal context recallable from a prompt-injection-vulnerable agent."})})),history:O.optional(XX.Info).annotate({description:"Trajectory (conversation history) FTS index configuration."}),dream:O.optional(O.Struct({auto:O.optional(O.Boolean).annotate({description:"Auto-trigger dream memory consolidation on new session start. Default: true."}),interval_days:O.optional(I5).annotate({description:"Minimum days between automatic dream runs. Set to 0 to trigger on every new session. Default: 7."})})),distill:O.optional(O.Struct({auto:O.optional(O.Boolean).annotate({description:"Auto-trigger distill workflow packaging on new session start. Default: true."}),interval_days:O.optional(I5).annotate({description:"Minimum days between automatic distill runs. Default: 30."})})),voice:O.optional(O.Struct({asr_model:O.optional(L8).annotate({description:"Model to use for voice ASR transcription in provider/model format, e.g. openai/whisper-1."}),control_model:O.optional(L8).annotate({description:"Model to use for voice control (multimodal) in provider/model format, e.g. openai/gpt-4o."})})).annotate({description:"Voice input provider and model configuration."}),experimental:O.optional(O.Struct({disable_paste_summary:O.optional(O.Boolean),batch_tool:O.optional(O.Boolean).annotate({description:"Enable the batch tool"}),openTelemetry:O.optional(O.Boolean).annotate({description:"Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"}),primary_tools:O.optional(O.mutable(O.Array(O.String))).annotate({description:"Tools that should only be available to primary agents."}),continue_loop_on_deny:O.optional(O.Boolean).annotate({description:"Continue the agent loop when a tool call is denied"}),mcp_timeout:O.optional(m$).annotate({description:"Timeout in milliseconds for model context protocol (MCP) requests"}),predict_next_prompt:O.optional(O.Boolean).annotate({description:"Predict the user's likely next prompt after each turn and show it as inline ghost text (Tab to accept). Enabled by default; set to false to disable."}),maxMode:O.optional(O.Struct({candidates:O.optional(m$).annotate({description:"Number of parallel reasoning candidates per step in max mode (default 5)."})})).annotate({description:"Max mode (experimental): the 'max' agent runs N parallel reasoning candidates each step, picks the best via a judge call, and executes only the winner."})})),workflow:O.optional(O.Struct({maxConcurrentAgents:O.optional(O.Number).annotate({description:"Process-wide ceiling on subagents running concurrently across ALL workflow runs (including nested children). Default min(16, 2x CPU cores). No upper clamp: the previous 2x-cores hard cap was removed so an operator can match real provider capacity \u2014 but that also means a misconfigured value (e.g. an extra zero) can exhaust provider rate limits or host memory. This is the only concurrency ceiling, so set it deliberately."}),maxDepth:O.optional(O.Number).annotate({description:"Max nesting depth for workflow()-calls-workflow. Default 8. Exceeding it fails the run."}),maxLifecycleAgents:O.optional(O.Number).annotate({description:"Hard ceiling on total agents a single workflow run may spawn over its life. Default 1000. Over-cap agent() calls return null (graceful degradation). PER-RUN, not tree-wide: each child workflow has its own independent budget, so a deep nesting can spawn maxDepth \xD7 this over the whole tree (concurrent in-flight is still bounded by maxConcurrentAgents)."}),scriptDeadlineMs:O.optional(O.Number).annotate({description:"Wall-clock budget for a whole workflow script, in milliseconds. Default 12h. The sandbox interrupt handler enforces this as a hard kill-switch."})})).annotate({description:"Dynamic workflow runtime settings."})}),E5=w0(ar).strict().meta({ref:"Config"});var er=C0.create({service:"config"}),$a=P5.Server.zod,Za=R5.Layout.zod;class J4 extends S1.Service()("@qitqode/Config"){}var Ja=N1.create("ConfigDirectoryTypoError",I.object({path:I.string(),dir:I.string(),suggestion:I.string()})),Lw=T0.effect(J4,L.gen(function*(){let $=yield*C$.Service,Z=yield*k8.Service,J=yield*n7.Service,Y=yield*u6.Service,X=yield*O6.Service,{readConfigFile:Q,loadConfig:G,loadFile:W}=Lj({fs:$,info:E5}),K=Rj(W),[U,V]=yield*L.cachedInvalidateWithTTL(K().pipe(L.tapError((E)=>L.sync(()=>er.error("failed to load global config, using defaults",{error:String(E)}))),L.orElseSucceed(()=>({}))),Z8.infinity),H=L.fn("Config.getGlobal")(function*(){return yield*U}),{loadInstanceState:B}=Hw({fs:$,authSvc:Z,accountSvc:J,env:Y,npmSvc:X,info:E5,readConfigFile:Q,loadConfig:G,loadFile:W,getGlobal:H}),z=yield*B0.make(L.fn("Config.state")(function*(E){return yield*B(E).pipe(L.orDie)})),F=L.fn("Config.get")(function*(){return yield*B0.use(z,(E)=>E.config)}),A=L.fn("Config.directories")(function*(){return yield*B0.use(z,(E)=>E.directories)}),N=L.fn("Config.getConsoleState")(function*(){return yield*B0.use(z,(E)=>E.consoleState)}),j=L.fn("Config.waitForDependencies")(function*(){yield*B0.useEffect(z,(E)=>L.forEach(E.deps,Dw.join,{concurrency:"unbounded"}).pipe(L.asVoid))}),w=L.fn("Config.update")(function*(E){let R=yield*B0.directory,T=tr.join(R,"config.json"),P=yield*W(T);yield*$.writeFileString(T,JSON.stringify(j1(o7(P),o7(E)),null,2)).pipe(L.orDie),yield*L.promise(()=>S8.dispose())}),q=L.fn("Config.invalidate")(function*(E){yield*V;let R=S8.disposeAll().catch(()=>{return}).finally(()=>D7.emit("event",{directory:"global",payload:{type:Qj.Disposed.type,properties:{}}}));if(E)yield*L.promise(()=>R)}),M=L.fn("Config.updateGlobal")(function*(E){let R=yield*L.promise(()=>Mj()),T=(yield*Q(R))??"{}",P;if(!R.endsWith(".jsonc")){let _=r8.schema(E5,r8.jsonc(T,R),R),C=j1(o7(_),o7(E));yield*$.writeFileString(R,JSON.stringify(C,null,2)).pipe(L.orDie),P=C}else{let _=eU(T,o7(E));P=r8.schema(E5,r8.jsonc(_,R),R),yield*$.writeFileString(R,_).pipe(L.orDie)}return yield*q(),P});return J4.of({get:F,getGlobal:H,getConsoleState:N,update:w,updateGlobal:M,invalidate:q,directories:A,waitForDependencies:j})})),Ya=Lw.pipe(T0.provide(ww.defaultLayer),T0.provide(C$.defaultLayer),T0.provide(u6.defaultLayer),T0.provide(k8.defaultLayer),T0.provide(n7.defaultLayer),T0.provide(O6.defaultLayer));var QX={};B1(QX,{report:()=>Xa,pretty:()=>Rw,Diagnostic:()=>QX});var Tw=20;function Rw($){let J={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[$.severity||1],Y=$.range.start.line+1,X=$.range.start.character+1;return`${J} [${Y}:${X}] ${$.message}`}function Xa($,Z){let J=Z.filter((G)=>G.severity===1);if(J.length===0)return"";let Y=J.slice(0,Tw),X=J.length-Tw,Q=X>0?`
|
|
490
490
|
... and ${X} more`:"";return`<diagnostics file="${$}">
|
|
491
491
|
${Y.map(Rw).join(`
|
|
@@ -785,7 +785,7 @@ Exact commands you ran or commands the user/task asked to be runnable later. Kee
|
|
|
785
785
|
`)}async function ON0($,Z){let Y=`---
|
|
786
786
|
written-at: ${Date.now()}
|
|
787
787
|
---
|
|
788
|
-
`,X=Z.match(/^---\n[\s\S]*?\n---\n/),Q=X?Y+Z.slice(X[0].length):Y+Z;await Bun.write($,Q)}async function Km($){return{"actor.postStop":{matcher:{agentType:{excludeOnly:["checkpoint-writer","title","summary","dream","distill","compaction","main"]}},run:async(Z,J)=>{let Y=Z.task_id;if(!Y)return;if(Z.canWrite===!1)return;let X=Z.sessionID,Q=cu(X,Y),G;try{G=await Bun.file(Q).text()}catch{G=void 0}if(G===void 0){J.continue=!0,J.reason=Wm({kind:"missing",taskId:Y,filePath:Q});return}let W=AN0.filter((K)=>!G.includes(K));if(W.length>0){J.continue=!0,J.reason=Wm({kind:"incomplete",taskId:Y,filePath:Q,missing:W});return}try{await BN0.mkdir(zN0.dirname(Q),{recursive:!0}),await ON0(Q,G)}catch(K){FN0.error("frontmatter injection failed",{err:K,filePath:Q})}}}}}var wA;((zg0)=>{function $(Q){let G=s8.pluginSpecifier(Q);return{spec:G,options:s8.pluginOptions(Q),deprecated:Um(G)}}async function Z(Q,G){let W="";try{W=await Bm(Q.spec)}catch(U){return{ok:!1,stage:"install",error:U}}if(!W)return{ok:!1,stage:"install",error:Error(`Plugin ${Q.spec} target is empty`)};let K;try{K=await zm(Q.spec,W,G)}catch(U){return{ok:!1,stage:"entry",error:U}}if(!K.entry)return{ok:!1,stage:"missing",value:{...Q,source:K.source,target:K.target,pkg:K.pkg,message:`Plugin ${Q.spec} does not expose a ${G} entrypoint`}};if(K.source==="npm")try{await Hm(K.target,O$,K.pkg)}catch(U){return{ok:!1,stage:"compatibility",error:U}}return{ok:!0,value:{...Q,source:K.source,target:K.target,entry:K.entry,pkg:K.pkg}}}zg0.resolve=Z;async function J(Q){let G;try{G=await import(Q.entry)}catch(W){return{ok:!1,error:W}}if(!G)return{ok:!1,error:Error(`Plugin ${Q.spec} module is empty`)};return{ok:!0,value:{...Q,mod:G}}}zg0.load=J;async function Y(Q,G,W,K,U,V){let H=Q.plan;if(H.deprecated)return;V?.start?.(Q,W);let B=await Z(H,G);if(!B.ok){if(B.stage==="missing"){if(U){let F=await U(B.value,Q.origin,W);if(F!==void 0)return F}V?.missing?.(Q,W,B.value.message,B.value);return}V?.error?.(Q,W,B.stage,B.error);return}let z=await J(B.value);if(!z.ok){V?.error?.(Q,W,"load",z.error,B.value);return}if(!K)return z.value;return K(z.value,Q.origin,W)}async function X(Q){let G=Q.items.map((V)=>({origin:V,plan:$(V.spec)})),W=[];for(let V of G)W.push(Y(V,Q.kind,!1,Q.finish,Q.missing,Q.report));let K=await Promise.all(W);if(Q.wait){let V;for(let H=0;H<G.length;H++){if(K[H]!==void 0)continue;let B=G[H];if(!B||Vm(B.plan.spec)!=="file")continue;V??=Q.wait(),await V,K[H]=await Y(B,Q.kind,!0,Q.finish,Q.missing,Q.report)}}let U=[];for(let V of K)if(V!==void 0)U.push(V);return U}zg0.loadExternal=X})(wA||={});var Am={worktree:Fm(async()=>(await import("./chunk-471yj527.js")).WorktreeAdaptor)},FK=new Map;async function Og0($,Z){let J=FK.get($)?.get(Z);if(J)return J;let Y=Am[Z];if(Y)return Y();throw Error(`Unknown workspace adaptor: ${Z}`)}async function qg0($){let Z=await Promise.all(Object.entries(Am).map(async([Y,X])=>{let Q=await X();return{type:Y,name:Q.name,description:Q.description}})),J=[...FK.get($)?.entries()??[]].map(([Y,X])=>({type:Y,name:X.name,description:X.description}));return[...Z,...J]}function Om($,Z,J){let Y=FK.get($)??new Map;Y.set(Z,J),FK.set($,Y)}import qN0 from"fs/promises";import eQ from"path";import{pathToFileURL as qm,fileURLToPath as NN0}from"url";var z$=C0.create({service:"plugin"}),TA={Executed:L1.define("hook.executed",D.object({event:D.enum(["actor.preStop","actor.postStop"]),hookID:D.string(),pluginName:D.string(),actorID:D.string(),agentType:D.string(),durationMs:D.number(),outcome:D.enum(["success","error","skipped"]),continueRequested:D.boolean(),reasonLength:D.number()})),ReActReentered:L1.define("hook.react.reentered",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string(),iteration:D.number(),triggeredByPlugins:D.array(D.string()),reasonPreview:D.string()})),ReActMaxReached:L1.define("hook.react.max_reached",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string()}))};class AK extends S1.Service()("@qitqode/Plugin"){}var jN0=[iR,nR,cR,eR,vu,BK,du,pu,Qm,Km];function Nm($){return typeof $==="function"}function MN0($){if(Nm($))return $;if(!$||typeof $!=="object"||!("server"in $))return;if(!Nm($.server))return;return $.server}function DN0($){let Z=new Set,J=[];for(let Y of Object.values($)){if(Z.has(Y))continue;Z.add(Y);let X=MN0(Y);if(!X)throw TypeError("Plugin export is not a function");J.push(X)}return J}async function wN0($,Z,J,Y){let X=Mm($.mod,$.spec,"server","detect");if(X){await Dm($.source,$.spec,$.target,LA(X.id,$.spec),$.pkg);let Q=LA(X.id,$.spec)??$.pkg?.pkg??$.spec,G=await X.server(Z,$.options);J.push(G),Y.push({hook:G,pluginName:Q,hookIDFor:(W)=>`${Q}#${W}`});return}for(let Q of DN0($.mod)){let G=Q.name,W=G&&G!=="default"&&G!==""?G:$.pkg?.pkg??$.spec,K=await Q(Z,$.options);J.push(K),Y.push({hook:K,pluginName:W,hookIDFor:(U)=>`${W}#${U}`})}}var wm=T0.effect(AK,L.gen(function*(){let $=yield*l1.Service,Z=yield*X8.Service,J=yield*B0.make(L.fn("Plugin.state")(function*(F){let A=[],N=[],j=yield*w7.make();function w(f){j.fork($.publish($9.Event.Error,{error:new N1.Unknown({message:f}).toObject()}))}let{Server:q}=yield*L.promise(()=>import("./chunk-f57rqsby.js")),M=LH({baseUrl:"http://localhost:4096",directory:F.directory,headers:b0.QITQODE_SERVER_PASSWORD?{Authorization:`Basic ${Buffer.from(`${b0.QITQODE_SERVER_USERNAME??"qitqode"}:${b0.QITQODE_SERVER_PASSWORD}`).toString("base64")}`}:void 0,fetch:async(...f)=>(await q.Default()).app.fetch(...f)}),E=yield*Z.get(),R={client:M,project:F.project,worktree:F.worktree,directory:F.directory,experimental_workspace:{register(f,b){Om(F.project.id,f,b)}},get serverUrl(){return q.url??new URL("http://localhost:4096")},$:typeof Bun>"u"?void 0:Bun.$};for(let f of jN0){z$.info("loading internal plugin",{name:f.name});let b=yield*L.tryPromise({try:()=>f(R),catch:(y)=>{z$.error("failed to load internal plugin",{name:f.name,error:y})}}).pipe(L.option);if(b._tag==="Some")A.push(b.value),N.push({hook:b.value,pluginName:f.name,hookIDFor:(y)=>`${f.name}#${y}`})}let T={},P=yield*L.tryPromise(()=>import("./chunk-6rak9ez9.js")).pipe(L.option);if(P._tag==="Some")Object.assign(T,P.value.modules??{});else{let f=eQ.join(eQ.dirname(NN0(import.meta.url)),"..","ext"),y=(yield*L.promise(()=>qN0.readdir(f).catch(()=>[]))).filter((k)=>k.endsWith(".ts")&&!k.endsWith(".d.ts")&&k!=="_manifest.ts");for(let k of y){let g=yield*L.tryPromise({try:()=>import(qm(eQ.join(f,k)).href),catch:(d)=>z$.error("failed to import extension",{name:k,error:d})}).pipe(L.option);if(g._tag==="Some")T[k.replace(/\.ts$/,"")]=g.value}}for(let[f,b]of Object.entries(T)){let y=Object.entries(b).find(([g,d])=>typeof d==="function"&&g.endsWith("Plugin"))?.[1];if(!y)continue;z$.info("loading extension",{name:f});let k=yield*L.tryPromise({try:()=>y(R),catch:(g)=>z$.error("failed to load extension",{name:f,error:g})}).pipe(L.option);if(k._tag==="Some")A.push(k.value),N.push({hook:k.value,pluginName:f,hookIDFor:(g)=>`${f}#${g}`})}let _=b0.QITQODE_PURE?[]:E.plugin_origins??[];if(b0.QITQODE_PURE&&E.plugin_origins?.length)z$.info("skipping external plugins in pure mode",{count:E.plugin_origins.length});if(_.length)yield*Z.waitForDependencies();let C=yield*L.promise(()=>wA.loadExternal({items:_,kind:"server",report:{start(f){z$.info("loading plugin",{path:f.plan.spec})},missing(f,b,y){z$.warn("plugin has no server entrypoint",{path:f.plan.spec,message:y})},error(f,b,y,k,g){let d=f.plan.spec,p=k instanceof Error?k.cause??k:k,t=y==="load"?FZ(k):FZ(p);if(y==="install"){let r=jm(d);z$.error("failed to install plugin",{pkg:r.pkg,version:r.version,error:t}),w(`Failed to install plugin ${r.pkg}@${r.version}: ${t}`);return}if(y==="compatibility"){z$.warn("plugin incompatible",{path:d,error:t}),w(`Plugin ${d} skipped: ${t}`);return}if(y==="entry"){z$.error("failed to resolve plugin server entry",{path:d,error:t}),w(`Failed to load plugin ${d}: ${t}`);return}z$.error("failed to load plugin",{path:d,target:g?.entry,error:t}),w(`Failed to load plugin ${d}: ${t}`)}}}));for(let f of C){if(!f)continue;yield*L.tryPromise({try:()=>wN0(f,R,A,N),catch:(b)=>{let y=FZ(b);return z$.error("failed to load plugin",{path:f.spec,error:y}),y}}).pipe(L.catch(()=>{return L.void}))}for(let f of A)yield*L.tryPromise({try:()=>Promise.resolve(f.config?.(E)),catch:(b)=>{z$.error("plugin config hook failed",{error:b})}}).pipe(L.ignore);return yield*$.subscribeAll().pipe(I$.runForEach((f)=>L.sync(()=>{for(let b of A)b.event?.({event:f})})),L.forkScoped),{hooks:A,hooksWithMeta:N}})),Y=yield*B0.make(L.fn("Plugin.fileHooks")(function*(){let F=[],A=[],N=yield*Z.get(),j=yield*Z.directories();for(let w of j){let q=Z4.scanSync("{hook,hooks}/*.{js,ts}",{cwd:w,absolute:!0,dot:!0,symlink:!0});for(let M of q){let E=yield*L.tryPromise({try:()=>import(`${qm(M).href}?v=${Date.now()}`),catch:(T)=>T}).pipe(L.catch((T)=>{return z$.error("failed to load file hook",{path:M,error:FZ(T)}),L.succeed(void 0)}));if(!E)continue;let R=E.default??E;if(R&&typeof R==="object"){let T=eQ.basename(M,eQ.extname(M));F.push(R),A.push({hook:R,pluginName:`file:${T}`,hookIDFor:(P)=>`file:${T}#${P}`}),z$.info("loaded file hook",{path:M,name:T})}}}return{hooks:F,meta:A}})),X=(F,A)=>L.gen(function*(){let N=yield*B0.get(J),j=yield*B0.get(Y),w=[],q=[],M=[],E=!1;for(let T of[...N.hooksWithMeta,...j.meta]){let P=T.hook[A];if(!P)continue;let _=typeof P==="function"?P:P.run,C=typeof P==="function"?void 0:P.matcher;if(!HR(C,F)){yield*$.publish(TA.Executed,{event:A,hookID:T.hookIDFor(A),pluginName:T.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:0,outcome:"skipped",continueRequested:!1,reasonLength:0});continue}let f=Date.now(),b={continue:!1},y="success";yield*L.tryPromise({try:()=>_(F,b),catch:(g)=>g}).pipe(L.tapError((g)=>L.gen(function*(){y="error",z$.error(`${A} hook failed`,{pluginName:T.pluginName,hookID:T.hookIDFor(A),error:g}),yield*$.publish($9.Event.Error,{sessionID:F.sessionID,error:new N1.Unknown({message:`${A} hook (${T.pluginName}) failed: ${FZ(g)}`}).toObject()})})),L.ignore);let k=Date.now()-f;if(yield*$.publish(TA.Executed,{event:A,hookID:T.hookIDFor(A),pluginName:T.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:k,outcome:y,continueRequested:b.continue===!0,reasonLength:b.reason?.length??0}),b.continue===!0&&b.reason&&b.reason.length>0)E=!0,w.push(b.reason),q.push(T.pluginName),M.push(T.hookIDFor(A));else if(b.continue===!0)z$.warn(`${A} hook returned continue=true without reason; ignored`,{pluginName:T.pluginName})}return{continue:E,reason:w.length>0?w.join(`
|
|
788
|
+
`,X=Z.match(/^---\n[\s\S]*?\n---\n/),Q=X?Y+Z.slice(X[0].length):Y+Z;await Bun.write($,Q)}async function Km($){return{"actor.postStop":{matcher:{agentType:{excludeOnly:["checkpoint-writer","title","summary","dream","distill","compaction","main"]}},run:async(Z,J)=>{let Y=Z.task_id;if(!Y)return;if(Z.canWrite===!1)return;let X=Z.sessionID,Q=cu(X,Y),G;try{G=await Bun.file(Q).text()}catch{G=void 0}if(G===void 0){J.continue=!0,J.reason=Wm({kind:"missing",taskId:Y,filePath:Q});return}let W=AN0.filter((K)=>!G.includes(K));if(W.length>0){J.continue=!0,J.reason=Wm({kind:"incomplete",taskId:Y,filePath:Q,missing:W});return}try{await BN0.mkdir(zN0.dirname(Q),{recursive:!0}),await ON0(Q,G)}catch(K){FN0.error("frontmatter injection failed",{err:K,filePath:Q})}}}}}var wA;((zg0)=>{function $(Q){let G=s8.pluginSpecifier(Q);return{spec:G,options:s8.pluginOptions(Q),deprecated:Um(G)}}async function Z(Q,G){let W="";try{W=await Bm(Q.spec)}catch(U){return{ok:!1,stage:"install",error:U}}if(!W)return{ok:!1,stage:"install",error:Error(`Plugin ${Q.spec} target is empty`)};let K;try{K=await zm(Q.spec,W,G)}catch(U){return{ok:!1,stage:"entry",error:U}}if(!K.entry)return{ok:!1,stage:"missing",value:{...Q,source:K.source,target:K.target,pkg:K.pkg,message:`Plugin ${Q.spec} does not expose a ${G} entrypoint`}};if(K.source==="npm")try{await Hm(K.target,O$,K.pkg)}catch(U){return{ok:!1,stage:"compatibility",error:U}}return{ok:!0,value:{...Q,source:K.source,target:K.target,entry:K.entry,pkg:K.pkg}}}zg0.resolve=Z;async function J(Q){let G;try{G=await import(Q.entry)}catch(W){return{ok:!1,error:W}}if(!G)return{ok:!1,error:Error(`Plugin ${Q.spec} module is empty`)};return{ok:!0,value:{...Q,mod:G}}}zg0.load=J;async function Y(Q,G,W,K,U,V){let H=Q.plan;if(H.deprecated)return;V?.start?.(Q,W);let B=await Z(H,G);if(!B.ok){if(B.stage==="missing"){if(U){let F=await U(B.value,Q.origin,W);if(F!==void 0)return F}V?.missing?.(Q,W,B.value.message,B.value);return}V?.error?.(Q,W,B.stage,B.error);return}let z=await J(B.value);if(!z.ok){V?.error?.(Q,W,"load",z.error,B.value);return}if(!K)return z.value;return K(z.value,Q.origin,W)}async function X(Q){let G=Q.items.map((V)=>({origin:V,plan:$(V.spec)})),W=[];for(let V of G)W.push(Y(V,Q.kind,!1,Q.finish,Q.missing,Q.report));let K=await Promise.all(W);if(Q.wait){let V;for(let H=0;H<G.length;H++){if(K[H]!==void 0)continue;let B=G[H];if(!B||Vm(B.plan.spec)!=="file")continue;V??=Q.wait(),await V,K[H]=await Y(B,Q.kind,!0,Q.finish,Q.missing,Q.report)}}let U=[];for(let V of K)if(V!==void 0)U.push(V);return U}zg0.loadExternal=X})(wA||={});var Am={worktree:Fm(async()=>(await import("./chunk-3m0t96kb.js")).WorktreeAdaptor)},FK=new Map;async function Og0($,Z){let J=FK.get($)?.get(Z);if(J)return J;let Y=Am[Z];if(Y)return Y();throw Error(`Unknown workspace adaptor: ${Z}`)}async function qg0($){let Z=await Promise.all(Object.entries(Am).map(async([Y,X])=>{let Q=await X();return{type:Y,name:Q.name,description:Q.description}})),J=[...FK.get($)?.entries()??[]].map(([Y,X])=>({type:Y,name:X.name,description:X.description}));return[...Z,...J]}function Om($,Z,J){let Y=FK.get($)??new Map;Y.set(Z,J),FK.set($,Y)}import qN0 from"fs/promises";import eQ from"path";import{pathToFileURL as qm,fileURLToPath as NN0}from"url";var z$=C0.create({service:"plugin"}),TA={Executed:L1.define("hook.executed",D.object({event:D.enum(["actor.preStop","actor.postStop"]),hookID:D.string(),pluginName:D.string(),actorID:D.string(),agentType:D.string(),durationMs:D.number(),outcome:D.enum(["success","error","skipped"]),continueRequested:D.boolean(),reasonLength:D.number()})),ReActReentered:L1.define("hook.react.reentered",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string(),iteration:D.number(),triggeredByPlugins:D.array(D.string()),reasonPreview:D.string()})),ReActMaxReached:L1.define("hook.react.max_reached",D.object({phase:D.enum(["pre","post"]),actorID:D.string(),agentType:D.string()}))};class AK extends S1.Service()("@qitqode/Plugin"){}var jN0=[iR,nR,cR,eR,vu,BK,du,pu,Qm,Km];function Nm($){return typeof $==="function"}function MN0($){if(Nm($))return $;if(!$||typeof $!=="object"||!("server"in $))return;if(!Nm($.server))return;return $.server}function DN0($){let Z=new Set,J=[];for(let Y of Object.values($)){if(Z.has(Y))continue;Z.add(Y);let X=MN0(Y);if(!X)throw TypeError("Plugin export is not a function");J.push(X)}return J}async function wN0($,Z,J,Y){let X=Mm($.mod,$.spec,"server","detect");if(X){await Dm($.source,$.spec,$.target,LA(X.id,$.spec),$.pkg);let Q=LA(X.id,$.spec)??$.pkg?.pkg??$.spec,G=await X.server(Z,$.options);J.push(G),Y.push({hook:G,pluginName:Q,hookIDFor:(W)=>`${Q}#${W}`});return}for(let Q of DN0($.mod)){let G=Q.name,W=G&&G!=="default"&&G!==""?G:$.pkg?.pkg??$.spec,K=await Q(Z,$.options);J.push(K),Y.push({hook:K,pluginName:W,hookIDFor:(U)=>`${W}#${U}`})}}var wm=T0.effect(AK,L.gen(function*(){let $=yield*l1.Service,Z=yield*X8.Service,J=yield*B0.make(L.fn("Plugin.state")(function*(F){let A=[],N=[],j=yield*w7.make();function w(f){j.fork($.publish($9.Event.Error,{error:new N1.Unknown({message:f}).toObject()}))}let{Server:q}=yield*L.promise(()=>import("./chunk-vdt8dvqs.js")),M=LH({baseUrl:"http://localhost:4096",directory:F.directory,headers:b0.QITQODE_SERVER_PASSWORD?{Authorization:`Basic ${Buffer.from(`${b0.QITQODE_SERVER_USERNAME??"qitqode"}:${b0.QITQODE_SERVER_PASSWORD}`).toString("base64")}`}:void 0,fetch:async(...f)=>(await q.Default()).app.fetch(...f)}),E=yield*Z.get(),R={client:M,project:F.project,worktree:F.worktree,directory:F.directory,experimental_workspace:{register(f,b){Om(F.project.id,f,b)}},get serverUrl(){return q.url??new URL("http://localhost:4096")},$:typeof Bun>"u"?void 0:Bun.$};for(let f of jN0){z$.info("loading internal plugin",{name:f.name});let b=yield*L.tryPromise({try:()=>f(R),catch:(y)=>{z$.error("failed to load internal plugin",{name:f.name,error:y})}}).pipe(L.option);if(b._tag==="Some")A.push(b.value),N.push({hook:b.value,pluginName:f.name,hookIDFor:(y)=>`${f.name}#${y}`})}let T={},P=yield*L.tryPromise(()=>import("./chunk-6rak9ez9.js")).pipe(L.option);if(P._tag==="Some")Object.assign(T,P.value.modules??{});else{let f=eQ.join(eQ.dirname(NN0(import.meta.url)),"..","ext"),y=(yield*L.promise(()=>qN0.readdir(f).catch(()=>[]))).filter((k)=>k.endsWith(".ts")&&!k.endsWith(".d.ts")&&k!=="_manifest.ts");for(let k of y){let g=yield*L.tryPromise({try:()=>import(qm(eQ.join(f,k)).href),catch:(d)=>z$.error("failed to import extension",{name:k,error:d})}).pipe(L.option);if(g._tag==="Some")T[k.replace(/\.ts$/,"")]=g.value}}for(let[f,b]of Object.entries(T)){let y=Object.entries(b).find(([g,d])=>typeof d==="function"&&g.endsWith("Plugin"))?.[1];if(!y)continue;z$.info("loading extension",{name:f});let k=yield*L.tryPromise({try:()=>y(R),catch:(g)=>z$.error("failed to load extension",{name:f,error:g})}).pipe(L.option);if(k._tag==="Some")A.push(k.value),N.push({hook:k.value,pluginName:f,hookIDFor:(g)=>`${f}#${g}`})}let _=b0.QITQODE_PURE?[]:E.plugin_origins??[];if(b0.QITQODE_PURE&&E.plugin_origins?.length)z$.info("skipping external plugins in pure mode",{count:E.plugin_origins.length});if(_.length)yield*Z.waitForDependencies();let C=yield*L.promise(()=>wA.loadExternal({items:_,kind:"server",report:{start(f){z$.info("loading plugin",{path:f.plan.spec})},missing(f,b,y){z$.warn("plugin has no server entrypoint",{path:f.plan.spec,message:y})},error(f,b,y,k,g){let d=f.plan.spec,p=k instanceof Error?k.cause??k:k,t=y==="load"?FZ(k):FZ(p);if(y==="install"){let r=jm(d);z$.error("failed to install plugin",{pkg:r.pkg,version:r.version,error:t}),w(`Failed to install plugin ${r.pkg}@${r.version}: ${t}`);return}if(y==="compatibility"){z$.warn("plugin incompatible",{path:d,error:t}),w(`Plugin ${d} skipped: ${t}`);return}if(y==="entry"){z$.error("failed to resolve plugin server entry",{path:d,error:t}),w(`Failed to load plugin ${d}: ${t}`);return}z$.error("failed to load plugin",{path:d,target:g?.entry,error:t}),w(`Failed to load plugin ${d}: ${t}`)}}}));for(let f of C){if(!f)continue;yield*L.tryPromise({try:()=>wN0(f,R,A,N),catch:(b)=>{let y=FZ(b);return z$.error("failed to load plugin",{path:f.spec,error:y}),y}}).pipe(L.catch(()=>{return L.void}))}for(let f of A)yield*L.tryPromise({try:()=>Promise.resolve(f.config?.(E)),catch:(b)=>{z$.error("plugin config hook failed",{error:b})}}).pipe(L.ignore);return yield*$.subscribeAll().pipe(I$.runForEach((f)=>L.sync(()=>{for(let b of A)b.event?.({event:f})})),L.forkScoped),{hooks:A,hooksWithMeta:N}})),Y=yield*B0.make(L.fn("Plugin.fileHooks")(function*(){let F=[],A=[],N=yield*Z.get(),j=yield*Z.directories();for(let w of j){let q=Z4.scanSync("{hook,hooks}/*.{js,ts}",{cwd:w,absolute:!0,dot:!0,symlink:!0});for(let M of q){let E=yield*L.tryPromise({try:()=>import(`${qm(M).href}?v=${Date.now()}`),catch:(T)=>T}).pipe(L.catch((T)=>{return z$.error("failed to load file hook",{path:M,error:FZ(T)}),L.succeed(void 0)}));if(!E)continue;let R=E.default??E;if(R&&typeof R==="object"){let T=eQ.basename(M,eQ.extname(M));F.push(R),A.push({hook:R,pluginName:`file:${T}`,hookIDFor:(P)=>`file:${T}#${P}`}),z$.info("loaded file hook",{path:M,name:T})}}}return{hooks:F,meta:A}})),X=(F,A)=>L.gen(function*(){let N=yield*B0.get(J),j=yield*B0.get(Y),w=[],q=[],M=[],E=!1;for(let T of[...N.hooksWithMeta,...j.meta]){let P=T.hook[A];if(!P)continue;let _=typeof P==="function"?P:P.run,C=typeof P==="function"?void 0:P.matcher;if(!HR(C,F)){yield*$.publish(TA.Executed,{event:A,hookID:T.hookIDFor(A),pluginName:T.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:0,outcome:"skipped",continueRequested:!1,reasonLength:0});continue}let f=Date.now(),b={continue:!1},y="success";yield*L.tryPromise({try:()=>_(F,b),catch:(g)=>g}).pipe(L.tapError((g)=>L.gen(function*(){y="error",z$.error(`${A} hook failed`,{pluginName:T.pluginName,hookID:T.hookIDFor(A),error:g}),yield*$.publish($9.Event.Error,{sessionID:F.sessionID,error:new N1.Unknown({message:`${A} hook (${T.pluginName}) failed: ${FZ(g)}`}).toObject()})})),L.ignore);let k=Date.now()-f;if(yield*$.publish(TA.Executed,{event:A,hookID:T.hookIDFor(A),pluginName:T.pluginName,actorID:F.actorID,agentType:F.agentType,durationMs:k,outcome:y,continueRequested:b.continue===!0,reasonLength:b.reason?.length??0}),b.continue===!0&&b.reason&&b.reason.length>0)E=!0,w.push(b.reason),q.push(T.pluginName),M.push(T.hookIDFor(A));else if(b.continue===!0)z$.warn(`${A} hook returned continue=true without reason; ignored`,{pluginName:T.pluginName})}return{continue:E,reason:w.length>0?w.join(`
|
|
789
789
|
|
|
790
790
|
`):void 0,contributingPluginNames:q,contributingHookIDs:M}}),Q=L.fn("Plugin.triggerActorPreStop")(function*(F){return yield*X(F,"actor.preStop")}),G=L.fn("Plugin.triggerActorPostStop")(function*(F){return yield*X(F,"actor.postStop")}),W=5000,K=3,U=new Map,V=L.fn("Plugin.trigger")(function*(F,A,N){if(!F)return N;let j=yield*B0.get(J),w=yield*B0.get(Y);for(let q of j.hooksWithMeta){let M=q.hook[F];if(!M)continue;yield*L.promise(async()=>M(A,N))}for(let q of w.meta){let M=q.hook[F];if(!M)continue;let E=q.hookIDFor(F);if((U.get(E)??0)>=3){z$.warn("hook circuit-breaker open, skipping",{hook:E});continue}let R=structuredClone(N);if(!(yield*L.tryPromise({try:async()=>{await Promise.race([Promise.resolve(M(A,N)),new Promise((P,_)=>setTimeout(()=>_(Error("hook timed out after 5000ms")),5000))])},catch:(P)=>P}).pipe(L.map(()=>!1),L.catch((P)=>{Object.assign(N,R);let _=(U.get(E)??0)+1;return U.set(E,_),z$.error("file hook failed, output rolled back",{hook:E,event:F,error:FZ(P),consecutiveFailures:_,circuitOpen:_>=3}),L.succeed(!0)}))))U.delete(E)}return N}),H=L.fn("Plugin.list")(function*(){return(yield*B0.get(J)).hooks}),B=L.fn("Plugin.init")(function*(){yield*B0.get(J),yield*B0.get(Y)}),z=L.fn("Plugin.reloadFileHooks")(function*(){yield*B0.invalidate(Y)});return AK.of({trigger:V,list:H,init:B,reloadFileHooks:z,triggerActorPreStop:Q,triggerActorPostStop:G})})),LN0=wm.pipe(T0.provide(l1.layer),T0.provide(X8.defaultLayer));import nN0 from"path";var LK=h6(Tm(),1);var Z9={};B1(Z9,{variants:()=>Q5,topP:()=>mm,topK:()=>lm,temperature:()=>um,smallOptions:()=>pm,schema:()=>om,providerOptions:()=>cm,options:()=>dm,message:()=>Em,maxOutputTokens:()=>im,OUTPUT_TOKEN_MAX:()=>NK});var Pm=32000;function TN0($){if($.startsWith("image/"))return"image";if($.startsWith("audio/"))return"audio";if($.startsWith("video/"))return"video";if($==="application/pdf")return"pdf";return}function RN0($){let Z=$.id.toLowerCase(),J=$.api.id.toLowerCase();if(Z.includes("claude")||J.includes("claude")||$.providerID==="anthropic")return!0;if(Z.includes("gpt")||J.includes("gpt"))return!0;return $.capabilities.input.image}function qK($){switch($){case"@ai-sdk/github-copilot":return"copilot";case"@ai-sdk/azure":return"azure";case"@ai-sdk/openai":return"openai";case"@ai-sdk/amazon-bedrock":return"bedrock";case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":return"anthropic";case"@ai-sdk/google-vertex":return"vertex";case"@ai-sdk/google":return"google";case"@ai-sdk/gateway":return"gateway";case"@openrouter/ai-sdk-provider":return"openrouter"}return}function PN0($,Z,J){if(Z.api.npm==="@ai-sdk/anthropic"||Z.api.npm==="@ai-sdk/amazon-bedrock")$=$.map((Y)=>{if(typeof Y.content==="string"){if(Y.content==="")return;return Y}if(!Array.isArray(Y.content))return Y;let X=Y.content.filter((Q)=>{if(Q.type==="text"||Q.type==="reasoning")return Q.text!=="";return!0});if(X.length===0)return;return{...Y,content:X}}).filter((Y)=>Y!==void 0&&Y.content!=="");if(Z.api.id.includes("claude")){let Y=(X)=>X.replace(/[^a-zA-Z0-9_-]/g,"_");$=$.map((X)=>{if(X.role==="assistant"&&Array.isArray(X.content))return{...X,content:X.content.map((Q)=>{if(Q.type==="tool-call"||Q.type==="tool-result")return{...Q,toolCallId:Y(Q.toolCallId)};return Q})};if(X.role==="tool"&&Array.isArray(X.content))return{...X,content:X.content.map((Q)=>{if(Q.type==="tool-result")return{...Q,toolCallId:Y(Q.toolCallId)};return Q})};return X})}if(["@ai-sdk/anthropic","@ai-sdk/google-vertex/anthropic"].includes(Z.api.npm))$=$.flatMap((Y)=>{if(Y.role!=="assistant"||!Array.isArray(Y.content))return[Y];let X=Y.content,Q=X.findIndex((G)=>G.type==="tool-call");if(Q===-1)return[Y];if(!X.slice(Q).some((G)=>G.type!=="tool-call"))return[Y];return[{...Y,content:X.filter((G)=>G.type!=="tool-call")},{...Y,content:X.filter((G)=>G.type==="tool-call")}]});if(Z.providerID==="mistral"||Z.api.id.toLowerCase().includes("mistral")||Z.api.id.toLowerCase().includes("devstral")){let Y=(Q)=>{return Q.replace(/[^a-zA-Z0-9]/g,"").substring(0,9).padEnd(9,"0")},X=[];for(let Q=0;Q<$.length;Q++){let G=$[Q],W=$[Q+1];if(G.role==="assistant"&&Array.isArray(G.content))X.push({...G,content:G.content.map((K)=>{if(K.type==="tool-call"||K.type==="tool-result")return{...K,toolCallId:Y(K.toolCallId)};return K})});else if(G.role==="tool"&&Array.isArray(G.content))X.push({...G,content:G.content.map((K)=>{if(K.type==="tool-result")return{...K,toolCallId:Y(K.toolCallId)};return K})});else X.push(G);if(G.role==="tool"&&W?.role==="user")X.push({role:"assistant",content:[{type:"text",text:"Done."}]})}return X}if(typeof Z.capabilities.interleaved==="object"&&Z.capabilities.interleaved.field){let Y=Z.capabilities.interleaved.field;return $.map((X)=>{if(X.role==="assistant"&&Array.isArray(X.content)){let G=X.content.filter((K)=>K.type==="reasoning").map((K)=>K.text).join(""),W=X.content.filter((K)=>K.type!=="reasoning");if(G)return{...X,content:W,providerOptions:{...X.providerOptions,openaiCompatible:{...X.providerOptions?.openaiCompatible,[Y]:G}}};return{...X,content:W}}return X})}return $}function IN0($){if($.api.npm==="@ai-sdk/anthropic"||$.api.npm==="@ai-sdk/google-vertex/anthropic")return!0;if($.providerID==="anthropic"||$.providerID==="google-vertex-anthropic")return!0;if($.api.npm==="@ai-sdk/amazon-bedrock")return!0;if($.api.npm==="@openrouter/ai-sdk-provider"||$.api.npm==="@ai-sdk/github-copilot"||$.api.npm==="@ai-sdk/alibaba")return $.api.id.includes("claude")||$.api.id.includes("anthropic")||$.id.includes("claude")||$.id.includes("anthropic");return!1}function EN0($,Z){let J=Z.cachePromptTTL==="1h"?{ttl:"1h"}:{},Y={anthropic:{cacheControl:{type:"ephemeral",...J}},openrouter:{cacheControl:{type:"ephemeral",...J}},bedrock:{cachePoint:{type:"default"}},openaiCompatible:{cache_control:{type:"ephemeral"}},copilot:{copilot_cache_control:{type:"ephemeral"}},alibaba:{cacheControl:{type:"ephemeral"}}},X=[],Q=$.filter((K)=>K.role==="system");if(Q.length>0)X.push(Q[Q.length-1]);let G=$.filter((K)=>K.role!=="system"),W=G.findLastIndex((K)=>K.role==="user");if(W>=1){X.push(G[W-1]);let K=Math.floor(W/2);if(K>0&&K<W-1)X.push(G[K])}else if(W===0)X.push(G[0]);for(let K of Rm(X)){if(!(Z.providerID==="anthropic"||Z.providerID.includes("bedrock")||Z.api.npm==="@ai-sdk/amazon-bedrock")&&Array.isArray(K.content)&&K.content.length>0){let H=K.content[K.content.length-1];if(H&&typeof H==="object"&&H.type!=="tool-approval-request"&&H.type!=="tool-approval-response"){H.providerOptions=j1(H.providerOptions??{},Y);continue}}K.providerOptions=j1(K.providerOptions??{},Y)}return $}function CN0($,Z){return $.map((J)=>{if(J.role!=="user"||!Array.isArray(J.content))return J;let Y=J.content.map((X)=>{if(X.type!=="file"&&X.type!=="image")return X;if(X.type==="image"){let V=String(X.image);if(V.startsWith("data:")){let H=V.match(/^data:([^;]+);base64,(.*)$/);if(H&&(!H[2]||H[2].length===0))return{type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let Q=X.type==="image"?String(X.image).split(";")[0].replace("data:",""):X.mediaType,G=X.type==="file"?X.filename:void 0,W=TN0(Q);if(!W)return X;if(W==="image"?RN0(Z):Z.capabilities.input[W])return X;return{type:"text",text:`ERROR: Cannot read ${G?`"${G}"`:W} (this model does not support ${W} input). Inform the user.`}});return{...J,content:Y}})}function bN0($){if(!$.startsWith("data:"))return;let Z=$.slice($.indexOf(",")+1);if(!Z)return 0;let J=Z.endsWith("==")?2:Z.endsWith("=")?1:0;return Math.floor(Z.length*3/4)-J}function _N0($,Z,J){if(Z===void 0&&J===void 0)return $;let Y=$.reduce((Q,G)=>G.role==="user"&&Array.isArray(G.content)?Q+G.content.filter((W)=>W.type==="image").length:Q,0),X=Z===void 0?0:Math.max(0,Y-Z);return $.map((Q)=>{if(Q.role!=="user"||!Array.isArray(Q.content))return Q;let G=Q.content.map((W)=>{if(W.type!=="image")return W;if(X>0)return X--,{type:"text",text:`[Image omitted: exceeds the configured limit of ${Z} prompt image(s).]`};if(J!==void 0){let K=bN0(String(W.image));if(K!==void 0&&K>J)return{type:"text",text:`[Image omitted: exceeds the configured ${J}-byte prompt image size limit.]`}}return W});return{...Q,content:G}})}function Im($,Z,J,Y={}){if($=CN0($,Z),$=_N0($,Y.maxImages,Y.maxSize),$=PN0($,Z,J),IN0(Z))$=EN0($,Z);let X=qK(Z.api.npm);if(X&&X!==Z.providerID){let Q=(G)=>{if(!G)return G;if(!(Z.providerID in G))return G;let W={...G};return W[X]=W[Z.providerID],delete W[Z.providerID],W};$=$.map((G)=>{if(!Array.isArray(G.content))return{...G,providerOptions:Q(G.providerOptions)};return{...G,providerOptions:Q(G.providerOptions),content:G.content.map((W)=>{if(W.type==="tool-approval-request"||W.type==="tool-approval-response")return{...W};return{...W,providerOptions:Q(W.providerOptions)}})}})}return $}var NK=b0.QITQODE_EXPERIMENTAL_OUTPUT_TOKEN_MAX||Pm;function Em($,Z,J){return Im($,Z,J,{maxImages:b0.QITQODE_MAX_PROMPT_IMAGES,maxSize:b0.QITQODE_MAX_PROMPT_IMAGE_SIZE})}function Cm($){return $()}var U6=["low","medium","high"],bm=["none","minimal",...U6,"xhigh"];function _m($){if($)return Object.fromEntries($.map((Z)=>[Z,{thinking:{type:"adaptive"},effort:Z}]));return{high:{thinking:{type:"enabled",budgetTokens:16000}},max:{thinking:{type:"enabled",budgetTokens:31999}}}}function SN0($){if(["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((Z)=>$.includes(Z)))return["low","medium","high","xhigh","max"];if(["opus-4-6","opus-4.6","sonnet-4-6","sonnet-4.6"].some((Z)=>$.includes(Z)))return["low","medium","high","max"];return null}function Sm($){if(!$.capabilities.reasoning)return{};let Z=$.id.toLowerCase(),J=SN0($.api.id);if(Z.includes("deepseek")||Z.includes("minimax")||Z.includes("glm")||Z.includes("mistral")||Z.includes("kimi")||Z.includes("k2p5")||Z.includes("qwen")||Z.includes("big-pickle"))return{};if(Z.includes("grok")&&Z.includes("grok-3-mini")){if($.api.npm==="@openrouter/ai-sdk-provider")return{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}};return{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}}}if(Z.includes("grok"))return{};switch($.api.npm){case"@openrouter/ai-sdk-provider":if(!$.id.includes("gpt")&&!$.id.includes("gemini-3")&&!$.id.includes("claude"))return{};return Object.fromEntries(bm.map((K)=>[K,{reasoning:{effort:K}}]));case"@ai-sdk/gateway":if($.id.includes("anthropic"))return _m(J);if($.id.includes("google")){if(Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};return Object.fromEntries(["low","high"].map((K)=>[K,{includeThoughts:!0,thinkingLevel:K}]))}return Object.fromEntries(bm.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/github-copilot":if($.id.includes("gemini"))return{};if($.id.includes("claude"))return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));let Y=Cm(()=>{if(Z.includes("5.1-codex-max")||Z.includes("5.2")||Z.includes("5.3"))return[...U6,"xhigh"];let K=[...U6];if(Z.includes("gpt-5")&&$.release_date>="2025-12-04")K.push("xhigh");return K});return Object.fromEntries(Y.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/cerebras":case"@ai-sdk/togetherai":case"@ai-sdk/xai":case"@ai-sdk/deepinfra":case"venice-ai-sdk-provider":case"@ai-sdk/openai-compatible":return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/azure":if(Z==="o1-mini")return{};let X=["low","medium","high"];if(Z.includes("gpt-5-")||Z==="gpt-5")X.unshift("minimal");return Object.fromEntries(X.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/openai":if(Z==="gpt-5-pro")return{};let Q=Cm(()=>{if(Z.includes("codex")){if(Z.includes("5.2")||Z.includes("5.3"))return[...U6,"xhigh"];return U6}let K=[...U6];if(Z.includes("gpt-5-")||Z==="gpt-5")K.unshift("minimal");if($.release_date>="2025-11-13")K.unshift("none");if($.release_date>="2025-12-04")K.push("xhigh");return K});return Object.fromEntries(Q.map((K)=>[K,{reasoningEffort:K,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]));case"@ai-sdk/anthropic":case"@ai-sdk/google-vertex/anthropic":if($.providerID==="github-copilot"){if($.api.id.includes("opus-4.7"))return Object.fromEntries(["medium"].map((K)=>[K,{reasoningEffort:K}]))}if(J)return Object.fromEntries(J.map((K)=>[K,{thinking:{type:"adaptive",...["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((U)=>$.api.id.includes(U))?{display:"summarized"}:{}},effort:K}]));return{high:{thinking:{type:"enabled",budgetTokens:Math.max(1,Math.min(16000,Math.floor($.limit.output/2-1)))}},max:{thinking:{type:"enabled",budgetTokens:Math.max(1,Math.min(31999,$.limit.output-1))}}};case"@ai-sdk/amazon-bedrock":if(J)return Object.fromEntries(J.map((K)=>[K,{reasoningConfig:{type:"adaptive",maxReasoningEffort:K,...["opus-4-7","opus-4.7","opus-4-8","opus-4.8"].some((U)=>$.api.id.includes(U))?{display:"summarized"}:{}}}]));if($.api.id.includes("anthropic"))return{high:{reasoningConfig:{type:"enabled",budgetTokens:16000}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}};return Object.fromEntries(U6.map((K)=>[K,{reasoningConfig:{type:"enabled",maxReasoningEffort:K}}]));case"@ai-sdk/google-vertex":case"@ai-sdk/google":if(Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};let G=["low","high"];if(Z.includes("3.1"))G=["low","medium","high"];return Object.fromEntries(G.map((K)=>[K,{thinkingConfig:{includeThoughts:!0,thinkingLevel:K}}]));case"@ai-sdk/mistral":return{};case"@ai-sdk/cohere":return{};case"@ai-sdk/groq":let W=["none",...U6];return Object.fromEntries(W.map((K)=>[K,{reasoningEffort:K}]));case"@ai-sdk/perplexity":return{};case"@jerome-benoit/sap-ai-provider-v2":if($.api.id.includes("anthropic"))return _m(J);if($.api.id.includes("gemini")&&Z.includes("2.5"))return{high:{thinkingConfig:{includeThoughts:!0,thinkingBudget:16000}},max:{thinkingConfig:{includeThoughts:!0,thinkingBudget:24576}}};if($.api.id.includes("gpt")||/\bo[1-9]/.test($.api.id))return Object.fromEntries(U6.map((K)=>[K,{reasoningEffort:K}]));return{}}return{}}function Q5($){return Sm($)}function fm($){let Z=$.id.toLowerCase();if(Z.includes("qwen"))return 0.55;if(Z.includes("claude"))return;if(Z.includes("gemini"))return 1;if(Z.includes("glm-4.6"))return 1;if(Z.includes("glm-4.7"))return 1;if(Z.includes("minimax-m2"))return 1;if(Z.includes("kimi-k2")){if(["thinking","k2.","k2p","k2-5"].some((J)=>Z.includes(J)))return 1;return 0.6}return}function km($){let Z=$.id.toLowerCase();if(Z.includes("qwen"))return 1;if(["minimax-m2","gemini","kimi-k2.5","kimi-k2p5","kimi-k2-5"].some((J)=>Z.includes(J)))return 0.95;return}function vm($){let Z=$.id.toLowerCase();if(Z.includes("minimax-m2")){if(["m2.","m25","m21"].some((J)=>Z.includes(J)))return 40;return 20}if(Z.includes("gemini"))return 64;return}function ym($){let Z={};if($.model.providerID==="openai"||$.model.api.npm==="@ai-sdk/openai"||$.model.api.npm==="@ai-sdk/github-copilot")Z.store=!1;if($.model.api.npm==="@ai-sdk/azure")Z.store=!0,Z.promptCacheKey=$.sessionID;if($.model.api.npm==="@openrouter/ai-sdk-provider"||$.model.api.npm==="@llmgateway/ai-sdk-provider"){if(Z.usage={include:!0},$.model.api.id.includes("gemini-3"))Z.reasoning={effort:"high"}}if($.model.providerID==="baseten"||$.model.providerID==="opencode"&&["kimi-k2-thinking","glm-4.6"].includes($.model.api.id))Z.chat_template_args={enable_thinking:!0};if(["zai","zhipuai"].some((Y)=>$.model.providerID.includes(Y))&&$.model.api.npm==="@ai-sdk/openai-compatible")Z.thinking={type:"enabled",clear_thinking:!1};if($.model.providerID==="openai"||$.providerOptions?.setCacheKey)Z.promptCacheKey=$.sessionID;if($.model.api.npm==="@ai-sdk/google"||$.model.api.npm==="@ai-sdk/google-vertex"){if($.model.capabilities.reasoning){if(Z.thinkingConfig={includeThoughts:!0},$.model.api.id.includes("gemini-3"))Z.thinkingConfig.thinkingLevel="high"}}let J=$.model.api.id.toLowerCase();if(($.model.api.npm==="@ai-sdk/anthropic"||$.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(J.includes("k2p5")||J.includes("kimi-k2.5")||J.includes("kimi-k2p5")))Z.thinking={type:"enabled",budgetTokens:Math.max(1,Math.min(16000,Math.floor($.model.limit.output/2-1)))};if($.model.providerID==="alibaba-cn"&&$.model.capabilities.reasoning&&$.model.api.npm==="@ai-sdk/openai-compatible"&&!J.includes("kimi-k2-thinking"))Z.enable_thinking=!0;if($.model.api.id.includes("gpt-5")&&!$.model.api.id.includes("gpt-5-chat")){if(!$.model.api.id.includes("gpt-5-pro")){if(Z.reasoningEffort="medium",$.model.api.npm==="@ai-sdk/openai"||$.model.api.npm==="@ai-sdk/azure"||$.model.api.npm==="@ai-sdk/github-copilot")Z.reasoningSummary="auto"}if($.model.api.id.includes("gpt-5.")&&!$.model.api.id.includes("codex")&&!$.model.api.id.includes("-chat")&&$.model.providerID!=="azure")Z.textVerbosity="low";if($.model.providerID.startsWith("opencode"))Z.promptCacheKey=$.sessionID,Z.include=["reasoning.encrypted_content"],Z.reasoningSummary="auto"}if($.model.providerID==="venice")Z.promptCacheKey=$.sessionID;if($.model.providerID==="openrouter")Z.prompt_cache_key=$.sessionID;if($.model.api.npm==="@ai-sdk/gateway")Z.gateway={caching:"auto"};return Z}function xm($){if($.providerID==="openai"||$.api.npm==="@ai-sdk/openai"||$.api.npm==="@ai-sdk/github-copilot"){if($.api.id.includes("gpt-5")){if($.api.id.includes("5.")||$.api.id.includes("5-mini"))return{store:!1,reasoningEffort:"low"};return{store:!1,reasoningEffort:"minimal"}}return{store:!1}}if($.providerID==="google"){if($.api.id.includes("gemini-3"))return{thinkingConfig:{thinkingLevel:"minimal"}};return{thinkingConfig:{thinkingBudget:0}}}if($.providerID==="openrouter"||$.providerID==="llmgateway"){if($.api.id.includes("google"))return{reasoning:{enabled:!1}};return{reasoningEffort:"minimal"}}if($.providerID==="venice")return{veniceParameters:{disableThinking:!0}};return{}}var fN0={amazon:"bedrock"};function hm($,Z){if($.api.npm==="@ai-sdk/gateway"){let Y=$.api.id.indexOf("/"),X=Y>0?$.api.id.slice(0,Y):void 0,Q=X?fN0[X]??X:void 0,G=Z.gateway,W=Object.fromEntries(Object.entries(Z).filter(([V])=>V!=="gateway")),K=Object.keys(W).length>0,U={};if(G!==void 0)U.gateway=G;if(K)if(Q)U[Q]=W;else if(G&&typeof G==="object"&&!Array.isArray(G))U.gateway={...G,...W};else U.gateway=W;return U}let J=qK($.api.npm)??$.providerID;if($.api.npm==="@ai-sdk/azure")return{openai:Z,azure:Z};return{[J]:Z}}function gm($,Z){return Math.min($.limit.output,Z)||Z}function um($){return fm($)}function mm($){return km($)}function lm($){return vm($)}function dm($){return ym($)}function pm($){return xm($)}function cm($,Z){return hm($,Z)}function im($){return gm($,NK)}function kN0($){let Z=$,J=Z.anyOf??Z.oneOf;if(!J?.length)return $;let Y=new Map;for(let W of J){if(!W.properties)continue;for(let[K,U]of Object.entries(W.properties))if(U&&typeof U==="object"&&"const"in U){if(!Y.has(K))Y.set(K,new Set);Y.get(K).add(U.const)}}let X;for(let[W,K]of Y)if(K.size===J.length){X=W;break}let Q={},G={};for(let W of J){if(!W.properties)continue;let K=X?W.properties[X]?.const:void 0;for(let[U,V]of Object.entries(W.properties)){if(U===X)continue;if(!(U in Q))Q[U]=V;if(K!==void 0){if(!G[U])G[U]=[];G[U].push(K)}}}if(X)for(let[W,K]of Object.entries(G)){if(K.length===J.length)continue;let U=`(only when ${X}=${K.map((H)=>JSON.stringify(H)).join("|")})`,V=Q[W].description;Q[W]={...Q[W],description:V?`${U} ${V}`:U}}if(X){let W=J[0].properties[X],K=J.map((H)=>H.properties[X]?.const),U=W?.description??"",V=J.map((H)=>{let B=H.properties[X]?.const,z=(H.required??[]).filter((F)=>F!==X);return z.length>0?`${B}: requires ${z.join(", ")}`:`${B}: no extra required fields`}).join("; ");Q[X]={type:"string",enum:K,description:U?`${U}
|
|
791
791
|
|