@bkm016/basalt 0.1.17 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/{chunk-p78wde92.js → chunk-02q61grt.js} +2 -2
  2. package/chunk-03r6s8pm.js +2 -0
  3. package/{chunk-38g4jd6v.js → chunk-09fsdkd3.js} +3 -3
  4. package/{chunk-8r4baw9e.js → chunk-0bg4w7ht.js} +2 -2
  5. package/chunk-0s4r7k7j.js +2 -0
  6. package/chunk-27kw4nth.js +2 -0
  7. package/chunk-2ag9mvms.js +10 -0
  8. package/{chunk-9ew8cap5.js → chunk-2shwjp8q.js} +1 -1
  9. package/chunk-3114vstw.js +2 -0
  10. package/chunk-31meb34a.js +2 -0
  11. package/chunk-34w345mt.js +2 -0
  12. package/{chunk-30dxcr91.js → chunk-3amfr8zp.js} +3 -3
  13. package/chunk-40nk2jjt.js +2 -0
  14. package/{chunk-44a7f5ta.js → chunk-49bz6hg5.js} +5 -5
  15. package/{chunk-e8x8zwkg.js → chunk-4hgkwa4k.js} +2 -2
  16. package/chunk-4wfd77kc.js +2 -0
  17. package/{chunk-9vam83py.js → chunk-55kpabb3.js} +1 -1
  18. package/chunk-5p2asrj6.js +2 -0
  19. package/chunk-65hg0v7e.js +2 -0
  20. package/chunk-67qw30cj.js +3770 -0
  21. package/{chunk-b350b01x.js → chunk-6rehcf49.js} +5 -5
  22. package/chunk-6vkz3wqz.js +25 -0
  23. package/chunk-81yk0kj2.js +3 -0
  24. package/chunk-885vf5kb.js +2 -0
  25. package/{chunk-46vy2m29.js → chunk-8wy08x0d.js} +1 -1
  26. package/chunk-9cqa9trx.js +4 -0
  27. package/chunk-ae45qq4z.js +2 -0
  28. package/chunk-ag3em5yv.js +4 -0
  29. package/chunk-b5k5p49x.js +2 -0
  30. package/chunk-b84vbfjc.js +2 -0
  31. package/{chunk-cs91rmbf.js → chunk-dkpgstr2.js} +7 -7
  32. package/{chunk-4f6p4n7k.js → chunk-dzn4c87v.js} +2 -2
  33. package/{chunk-8np9b2y8.js → chunk-e2m8ap8f.js} +2 -2
  34. package/{chunk-37ndxehw.js → chunk-e5xsyr0n.js} +2 -2
  35. package/chunk-f97ma522.js +3 -0
  36. package/chunk-f9yneea6.js +3 -0
  37. package/{chunk-vqm94hz2.js → chunk-fj56fznw.js} +2 -2
  38. package/{chunk-xf7zw32f.js → chunk-fk43jgwe.js} +5 -5
  39. package/{chunk-mh4bjtfs.js → chunk-frjqjdkx.js} +4 -4
  40. package/{chunk-rqn67tm8.js → chunk-fycz7ap5.js} +1 -1
  41. package/chunk-fzefs6kn.js +3 -0
  42. package/chunk-g1n8k4dg.js +5 -0
  43. package/{chunk-qd2enpr2.js → chunk-g5mdw639.js} +2 -2
  44. package/chunk-gnvx44kj.js +10 -0
  45. package/chunk-gpympx0t.js +467 -0
  46. package/{chunk-b2wpj81x.js → chunk-gyp2jn7d.js} +1 -1
  47. package/{chunk-y0274xr2.js → chunk-hambwbfz.js} +4 -4
  48. package/{chunk-1c9nr9rs.js → chunk-j02kqpvq.js} +2 -2
  49. package/{chunk-ehnc8g6v.js → chunk-j1h7pabk.js} +5 -5
  50. package/{chunk-w55cnj0f.js → chunk-j6hn9qz6.js} +2 -2
  51. package/{chunk-m5km74eq.js → chunk-jfx4c32t.js} +2 -2
  52. package/{chunk-7mgkpn94.js → chunk-jjj8a18b.js} +6 -6
  53. package/{chunk-pdt65s31.js → chunk-k3c32v59.js} +2 -2
  54. package/{chunk-rghqprav.js → chunk-k8j3fvx5.js} +1 -1
  55. package/chunk-kcn3af9r.js +12 -0
  56. package/{chunk-pyj6avd5.js → chunk-keq5kv9b.js} +2 -2
  57. package/{chunk-evnqkyt7.js → chunk-m45dpnd1.js} +12 -12
  58. package/chunk-m4wf04dz.js +15 -0
  59. package/chunk-m8k6t63k.js +2 -0
  60. package/{chunk-0crbhhna.js → chunk-nrggp4x6.js} +1 -1
  61. package/chunk-nt549hv5.js +2 -0
  62. package/{chunk-06s9pr82.js → chunk-pg4mtrdy.js} +2 -2
  63. package/chunk-psr4rxnn.js +20 -0
  64. package/chunk-qhhv81gd.js +2 -0
  65. package/chunk-qprms4rt.js +2 -0
  66. package/chunk-r0pm6dap.js +3 -0
  67. package/{chunk-44b9yx79.js → chunk-rck0kx09.js} +1 -1
  68. package/chunk-rsn8ad6s.js +2 -0
  69. package/{chunk-zhyzhekt.js → chunk-skzh3q1s.js} +1 -1
  70. package/{chunk-g2etemv5.js → chunk-sm4b3q49.js} +2 -2
  71. package/{chunk-g5p9mj1r.js → chunk-ste3ek53.js} +2 -2
  72. package/chunk-t3mq64c8.js +3 -0
  73. package/chunk-trw86cmb.js +11 -0
  74. package/{chunk-tfhp09nj.js → chunk-tv7met41.js} +2 -2
  75. package/{chunk-pna1wh02.js → chunk-w33aapmk.js} +12 -12
  76. package/chunk-wkqrsfrb.js +389 -0
  77. package/chunk-wxngqzqs.js +3 -0
  78. package/chunk-xgfqmm46.js +2 -0
  79. package/{chunk-2eaehpp6.js → chunk-xr77j4f8.js} +3 -3
  80. package/{chunk-c8g9jjqs.js → chunk-ykstnss8.js} +2 -2
  81. package/{chunk-1w4nh5t6.js → chunk-yqv7ej5r.js} +3 -3
  82. package/chunk-z97bcdg2.js +3 -0
  83. package/chunk-z9s7pwv5.js +7 -0
  84. package/compiled.js +9 -9
  85. package/package.json +1 -1
  86. package/ui-test-worker.js +41 -41
  87. package/worker.js +1 -1
  88. package/chunk-4hf0r9hv.js +0 -12
  89. package/chunk-4w8j6n7z.js +0 -2
  90. package/chunk-4yxd2kg1.js +0 -3
  91. package/chunk-62ebm0bn.js +0 -2
  92. package/chunk-6ae9810t.js +0 -25
  93. package/chunk-6ef085c1.js +0 -20
  94. package/chunk-6exa9fp7.js +0 -3
  95. package/chunk-73t051r6.js +0 -2
  96. package/chunk-86yr2c0r.js +0 -3
  97. package/chunk-8jn0yax5.js +0 -482
  98. package/chunk-9jtvj8md.js +0 -4172
  99. package/chunk-9xjecw6c.js +0 -2
  100. package/chunk-bjvv3403.js +0 -2
  101. package/chunk-bv96b8q7.js +0 -2
  102. package/chunk-drett6hb.js +0 -2
  103. package/chunk-fzftb4n2.js +0 -10
  104. package/chunk-ge38dhv9.js +0 -3
  105. package/chunk-hggam3je.js +0 -2
  106. package/chunk-nrdszs0g.js +0 -5
  107. package/chunk-pjgt1bdx.js +0 -3
  108. package/chunk-q6tgpaf3.js +0 -2
  109. package/chunk-t33bm5aa.js +0 -2
  110. package/chunk-v9ttcf6r.js +0 -3
  111. package/chunk-vd5332ps.js +0 -2
  112. package/chunk-vv9csar7.js +0 -2
  113. package/chunk-wnd3y4c0.js +0 -10
  114. package/chunk-xba6fr5v.js +0 -2
  115. package/chunk-ypxs8djn.js +0 -2
  116. package/chunk-zcwz44db.js +0 -2
@@ -0,0 +1,467 @@
1
+ // @bun
2
+ import{ri,wn,z}from"./chunk-09fsdkd3.js";import{os,Qe,It,is,ho,as,ls,cs,Mt,ds,Fe,go,rt}from"./chunk-49bz6hg5.js";import{pn,ro,ws,no,Fi,oo}from"./chunk-trw86cmb.js";import{Xo,dn,mn,$i,t,y,St,Hi,qi,Gi,Ar,Yo,zi,yn,Zo,Yi,ti,io,Zi,es,Oe}from"./chunk-z9s7pwv5.js";import{so,xs,Sn}from"./chunk-ste3ek53.js";import{b,ue}from"./chunk-t3mq64c8.js";import{ao,B,xn,Ne,ie,ni,lo,lt,rs,Jt,Ie,D,co,wt,De,Er,H,Ue,uo,xt,fe,Yt,ce,vn,oi,Be,ae,ct,po,ii,_e,vs,ns,Ae,mo,d,_s,Z,_n,K,As}from"./chunk-kcn3af9r.js";import{r,Je}from"./chunk-g5mdw639.js";var Og=r(function(dK,Mg){var hv=["||","&&",";;&",";;",";&","|&","<(",">(","<<<","<<-","<<",">>",">&",">|","&>>","&>","<&","<>","&",";","(",")","|","<",">"],Gl=/[\n\r\u2028\u2029]/,gv=/[\s#!"$&'():;<=>@\\^`|~]/g;Mg.exports=function(o){var a=!1;return o.map(function(u){if(a&&typeof u==="string"&&Gl.test(u))throw TypeError("a token after a `comment` must not contain line terminators");if(u==="")return"''";if(u&&typeof u==="object"){if("op"in u&&u.op==="glob"){if(typeof u.pattern!=="string")throw TypeError("glob token requires a string `pattern`");if(Gl.test(u.pattern))throw TypeError("glob `pattern` must not contain line terminators");if(u.pattern==="")return"''";return u.pattern.replace(gv,"\\$&")}if("op"in u&&typeof u.op==="string"){if(hv.indexOf(u.op)<0)throw TypeError("invalid `op` value: "+JSON.stringify(u.op));return u.op.replace(/[\s\S]/g,"\\$&")}if("comment"in u&&typeof u.comment==="string"){if(Gl.test(u.comment))throw TypeError("`comment` must not contain line terminators");return a=!0,"#"+u.comment}throw TypeError("unrecognized object token shape")}if(/'/.test(u)&&/!/.test(u))return"'"+u.replace(/'/g,`'"'"'`)+"'";if(/["\s\\]/.test(u)&&!/'/.test(u))return"'"+u+"'";if(/["'\s]/.test(u))return'"'+u.replace(/(["\\$`])/g,"\\$1")+'"';return String(u).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}~])/g,"$1\\$2")}).join(" ")}});var Ug=r(function(fK,jg){var Dg="(?:"+["\\|\\|","\\&(?:\\&|>>?)",";;\\&?","[;|]\\&","\\<\\(","\\<\\<\\<","\\<\\<-","\\<\\<(?!\\()",">>",">[&|(]","<[&>]","[&;()|<>]"].join("|")+")",_g=new RegExp("^"+Dg+"$"),Lg="|&;()<> \\t",yv="'([^']*?)'",Fg="(?:\\\\[\\s\\S]|[^\\\\'])*?",Ng="\\$'"+Fg+"'",Yc=new RegExp("\\$'"+Fg+"(?:(')|\\\\?$)","g"),xv="abeEfnrtv",Iv=`\x07\b\x1B\x1B\f
3
+ \r \v`,Ev=/^#$/,Kl="'",qg='"',ku="$",Xi="",bv=4294967296;for(Xc=0;Xc<4;Xc++)Xi+=(bv*Math.random()).toString(16);var Xc,Sv=new RegExp("^"+Xi);function wv(e,o){var a=o.lastIndex,u=[],m;while(m=o.exec(e))if(u[u.length]=m,o.lastIndex===m.index)o.lastIndex+=1;return o.lastIndex=a,u}function Tv(e,o,a){var u=typeof e==="function"?e(a):e[a];if(typeof u>"u"&&a!="")u="";else if(typeof u>"u")u="$";if(typeof u==="object")return o+Xi+JSON.stringify(u)+Xi;return o+u}var Rv=/\\([0-7]{1,3}|x[\dA-Fa-f]{1,2}|u[\dA-Fa-f]{1,4}|U[\dA-Fa-f]{1,8}|c(?:\\\\|[\s\S])|[abeEfnrtv\\'"?])/g;function kv(e,o){var a=o.charAt(0);if(a==="c"){var u=o.charAt(1);return u==="?"?"\x7F":String.fromCharCode(u.charCodeAt(0)&31)}if(a==="x"||a==="u"||a==="U"){var m=parseInt(o.slice(1),16);if(m>1114111)return e;return String.fromCharCode.apply(null,m>65535?[55232+(m>>10),56320+(m&1023)]:[m])}if(a>="0"&&a<="7")return String.fromCharCode(parseInt(o,8)&255);var p=xv.indexOf(o);return p<0?o:Iv.charAt(p)}function Av(e){return e.replace(Rv,kv).split("\x00")[0]}function Pv(e,o){return Yc.lastIndex=o,!!Yc.exec(e)[1]}function $v(e,o,a){if(!a)a={};var u=a.escape||"\\",m=a.splitUnquoted===!0?`
4
+ `:typeof a.splitUnquoted==="string"?a.splitUnquoted:"",p="(\\"+u+`['"$\\`+u+Lg+"]|\\$\\$|\\$(?!"+Ng.slice(2)+`)|[^\\s'"$`+Lg+"])+",f='"(?:\\'+u+'[\\s\\S]|[^"\\'+u+'])*"',h=new RegExp(["("+Dg+")","("+Ng+"|"+p+"|"+f+"|"+yv+")+"].join("|"),"g"),I=wv(e,h);if(I.length===0)return[];if(!o)o={};var E=!1;return I.map(function(S){var R=S[0];if(!R||E)return;if(_g.test(R))return{op:R};var k=!1,A=!1,P="",M=[],V=!1,_=null,J=!1,j;function X(){j+=1;var ee,be,Xe=R.charAt(j);if(Xe==="{"){if(j+=1,R.charAt(j)==="}")throw Error("Bad substitution: "+R.slice(j-2,j+1));var Ge=1;ee=j;while(Ge>0&&ee<R.length){if(R.charAt(ee)==="{"&&R.charAt(ee-1)==="$")Ge+=1;else if(R.charAt(ee)==="}")Ge-=1;ee+=1}if(Ge!==0)throw Error("Bad substitution: "+R.slice(j));ee-=1,be=R.slice(j,ee),j=ee}else if(/[*@#?$!-]/.test(Xe))be=Xe;else{var sr=R.slice(j);if(ee=sr.match(/[^\w\d_]/),!ee)be=sr,j=R.length;else be=sr.slice(0,ee.index),j+=ee.index-1}return Tv(o,"",be)}function te(){if(_===null)return;if(_===0){if(P!=="")M[M.length]=P,P=""}else{M[M.length]=P,P="";for(var ee=1;ee<_;ee+=1)M[M.length]=""}_=null}for(j=0;j<R.length;j++){var L=R.charAt(j);if(m&&L!==ku)te();if(J=J||!k&&(L==="*"||L==="?"),A)P+=L,A=!1;else if(k)if(L===k)k=!1;else if(k==Kl)P+=L;else if(L===u)if(j+=1,L=R.charAt(j),L===qg||L===u||L===ku)P+=L;else P+=u+L;else if(L===ku)P+=X();else P+=L;else if(L===qg||L===Kl)k=L,V=!0;else if(_g.test(L))return{op:R};else if(Ev.test(L)){E=!0;var se={comment:e.slice(S.index+j+1)};if(P.length)return[P,se];return[se]}else if(L===u)A=!0;else if(L===ku&&R.charAt(j+1)===Kl&&Pv(R,j))te(),V=!0,P+=Av(R.slice(j+2,Yc.lastIndex-1)),j=Yc.lastIndex-1;else if(L===ku){var he=X();if(!m)P+=he;else for(var Me=0;Me<he.length;Me+=1){var We=he.charAt(Me);if(m.indexOf(We)<0)te(),P+=We;else if(_===null)_=We===" "||We==="\t"||We===`
5
+ `?0:1;else if(We!==" "&&We!=="\t"&&We!==`
6
+ `)_+=1}}else P+=L}if(J)return{op:"glob",pattern:P};if(m){if(_!==null&&_>0){M[M.length]=P,P="";for(var Q=1;Q<_;Q+=1)M[M.length]=""}if(P!==""||V&&M.length===0)M[M.length]=P;return M}return P}).reduce(function(S,R){if(typeof R>"u")return S;return[].concat(R).forEach(function(k){S[S.length]=k}),S},[])}jg.exports=function(o,a,u){var m=$v(o,a,u);if(typeof a!=="function")return m;return m.reduce(function(p,f){if(typeof f==="object")return p[p.length]=f,p;var h=f.split(RegExp("("+Xi+".*?"+Xi+")","g"));if(h.length===1)return p[p.length]=h[0],p;return h.filter(Boolean).forEach(function(I){p[p.length]=Sv.test(I)?JSON.parse(I.split(Xi)[1]):I}),p},[])}});var Vo={};Je(Vo,{AssistantMessageEventStream:()=>B,AssistantMessageFrameEncoder:()=>eR,DEFAULT_MAX_AGENT_RETRY_DELAY_MS:()=>nR,EventStream:()=>ao,InMemoryCredentialStore:()=>lo,InMemoryModelsStore:()=>co,ModelsError:()=>D,StringEnum:()=>uD,Type:()=>Le,appendAssistantMessageDiagnostic:()=>Ie,calculateCost:()=>Z,clampThinkingLevel:()=>K,cleanupSessionResources:()=>xs,collapseSystemMessages:()=>Be,contentText:()=>Er,createAssistantMessageDiagnostic:()=>Jt,createAssistantMessageEventStream:()=>xn,createFauxCore:()=>Fi,createInitialSystemMessage:()=>uo,createModels:()=>mo,createProvider:()=>d,declarationsEqual:()=>po,defaultProviderAuthContext:()=>ni,envApiKeyAuth:()=>b,extractDiagnosticError:()=>rs,fauxAssistantMessage:()=>no,fauxProvider:()=>oo,fauxText:()=>pn,fauxThinking:()=>ro,fauxToolCall:()=>ws,formatThrownValue:()=>lt,getCurrentSystemMessage:()=>vn,getCurrentSystemPrompt:()=>oi,getCurrentTools:()=>ce,getDeclaredTools:()=>_e,getInitialSystemMessage:()=>fe,getModelType:()=>wt,getOverflowPatterns:()=>nD,getSupportedThinkingLevels:()=>_n,getSystemMessageText:()=>H,getToolStateChanges:()=>ii,hasApi:()=>_s,hasNonAdditiveToolChanges:()=>ns,hasToolRedefinitions:()=>vs,isContextOverflow:()=>Ea,isModelType:()=>De,isRecoverableLength:()=>rD,isRetryableAssistantError:()=>sR,lazyApi:()=>ie,lazyOAuth:()=>ue,lazyStream:()=>Ne,modelsAreEqual:()=>As,normalizeContext:()=>xt,parseJsonWithRepair:()=>wn,parseStreamingJson:()=>z,reduceAssistantMessageFrames:()=>Zq,registerSessionResourceCleanup:()=>so,renderSystemMessageUpdate:()=>Ue,repairJson:()=>ri,resolveTranscript:()=>ae,resolveTranscriptTools:()=>Ae,retryAssistantCall:()=>aD,retryDelayMs:()=>oR,toToolDeclaration:()=>ct,uuidv7:()=>Sn,validateToolArguments:()=>lu,validateToolCall:()=>zj,withoutInitialSystemMessage:()=>Yt});var O={};Je(O,{Counted:()=>Xl,Entries:()=>on,EntriesRegExp:()=>Yl,Every:()=>Zr,EveryAll:()=>Mn,GraphemeCount:()=>eM,HasPropertyKey:()=>me,IsArray:()=>$e,IsBigInt:()=>Fr,IsBoolean:()=>nn,IsClassInstance:()=>oy,IsConstructor:()=>Jl,IsDeepEqual:()=>Oa,IsEqual:()=>v,IsFunction:()=>Ps,IsGreaterEqualThan:()=>va,IsGreaterThan:()=>ta,IsInteger:()=>tm,IsLessEqualThan:()=>$s,IsLessThan:()=>Pu,IsMaxLength:()=>sy,IsMinLength:()=>iy,IsMultipleOf:()=>ny,IsNull:()=>Ao,IsNumber:()=>Dt,IsObject:()=>mt,IsObjectNotArray:()=>Jo,IsString:()=>ht,IsSymbol:()=>Ql,IsUndefined:()=>er,IsUnsafePropertyKey:()=>$u,IsValueLike:()=>ra,Keys:()=>xe,ShiftLeft:()=>yt,Some:()=>Ma,SomeAll:()=>ay,Symbols:()=>uy,Values:()=>Zl});var ca={};Je(ca,{Hash:()=>id,HashCode:()=>By});var Ft={};Je(Ft,{ExtendsFalse:()=>nt,ExtendsTrue:()=>Ee,ExtendsUnion:()=>Pd,IsExtendsFalse:()=>vd,IsExtendsTrue:()=>Cd,IsExtendsTrueLike:()=>Io,IsExtendsUnion:()=>$d,Match:()=>br});var Le={};Je(Le,{Any:()=>qa,Array:()=>F,BigInt:()=>Lu,Boolean:()=>N,Call:()=>tw,Capitalize:()=>uw,Codec:()=>pm,Conditional:()=>gw,Constructor:()=>Ms,ConstructorParameters:()=>xw,Cyclic:()=>Ns,Decode:()=>Wy,DecodeBuilder:()=>mm,Dependent:()=>ua,Encode:()=>zy,EncodeBuilder:()=>cm,Enum:()=>My,Evaluate:()=>Cn,Exclude:()=>Ew,Extends:()=>$n,ExtendsResult:()=>Ft,Extract:()=>Sw,Function:()=>Os,Generic:()=>bi,Identifier:()=>Nu,Immutable:()=>Vy,Index:()=>kw,Infer:()=>_u,InstanceType:()=>Xw,Instantiate:()=>Do,Integer:()=>x,Interface:()=>NS,Intersect:()=>Ln,IsAny:()=>_r,IsArray:()=>At,IsBigInt:()=>wo,IsBoolean:()=>Wn,IsCall:()=>Ja,IsCodec:()=>Hn,IsConstructor:()=>zr,IsCyclic:()=>ar,IsDependent:()=>jr,IsEnum:()=>Xr,IsEnumValue:()=>vy,IsFunction:()=>Vr,IsGeneric:()=>Na,IsIdentifier:()=>Yy,IsImmutable:()=>ma,IsInfer:()=>Qr,IsInteger:()=>hn,IsIntersect:()=>Ke,IsKind:()=>Se,IsLiteral:()=>gt,IsNever:()=>So,IsNull:()=>Ds,IsNumber:()=>$r,IsObject:()=>ze,IsOptional:()=>tn,IsParameter:()=>rx,IsReadonly:()=>la,IsRecord:()=>tr,IsRef:()=>Xt,IsRefine:()=>lm,IsRest:()=>Ai,IsSchema:()=>Or,IsString:()=>Yr,IsSymbol:()=>Fs,IsTemplateLiteral:()=>mr,IsThis:()=>km,IsTuple:()=>dt,IsUndefined:()=>ps,IsUnion:()=>ye,IsUnknown:()=>Jr,IsUnsafe:()=>um,IsVoid:()=>To,KeyOf:()=>Zw,Literal:()=>i,Lowercase:()=>cw,Mapped:()=>aT,Module:()=>JT,Never:()=>nr,NonNullable:()=>pT,Null:()=>Nn,Number:()=>re,Object:()=>l,Omit:()=>dT,Optional:()=>n,Parameter:()=>da,Parameters:()=>gT,Partial:()=>xT,Pick:()=>RT,Readonly:()=>Jy,ReadonlyObject:()=>af,ReadonlyType:()=>PT,Record:()=>at,RecordKey:()=>ki,RecordPattern:()=>gn,RecordValue:()=>dr,Ref:()=>en,Refine:()=>Qy,Required:()=>GT,Rest:()=>ha,ReturnType:()=>HT,Script:()=>ZT,String:()=>s,Symbol:()=>ja,TemplateLiteral:()=>nS,This:()=>Rm,Tuple:()=>Br,Uncapitalize:()=>mw,Undefined:()=>Ga,Union:()=>g,Unknown:()=>Y,Unsafe:()=>Sr,Uppercase:()=>pw,Void:()=>Am,With:()=>pp});var cu={};Je(cu,{Clear:()=>bk,Entries:()=>hF,Get:()=>xF,Has:()=>yF,IsDate:()=>iu,IsDateTime:()=>yp,IsDuration:()=>xp,IsEmail:()=>Ip,IsHostname:()=>Ap,IsIPv4:()=>Cp,IsIPv6:()=>vp,IsIdnEmail:()=>Pp,IsIdnHostname:()=>$p,IsIri:()=>Op,IsIriReference:()=>Mp,IsJsonPointer:()=>Lp,IsJsonPointerUriFragment:()=>_p,IsRegex:()=>Np,IsRelativeJsonPointer:()=>qp,IsTime:()=>au,IsUri:()=>jp,IsUriReference:()=>Dp,IsUriTemplate:()=>Fp,IsUrl:()=>Up,IsUuid:()=>Bp,Reset:()=>wk,Set:()=>gF,Test:()=>Sk});var Ve=10,dv=15000000;function st(e){if(!e||typeof e!=="object")return!1;let o=e;return typeof o.name==="string"&&o.name.length>0&&o.name.length<=255&&typeof o.mimeType==="string"&&o.mimeType.length>0&&typeof o.kind==="string"&&io.includes(o.kind)&&typeof o.data==="string"&&o.data.length>0&&o.data.length<=dv}function jl(e){return e?.map((o)=>({...o,id:`att_${crypto.randomUUID().slice(0,8)}`}))}import{closeSync as wg,existsSync as Tg,fsyncSync as Rg,mkdirSync as kg,openSync as Ag,readFileSync as Pg,renameSync as $g,writeFileSync as Cg}from"fs";import{dirname as Ul,join as vg}from"path";class Ni{path;deviceIdPath;providers={};dirty=!1;closed=!1;chains=new Map;constructor(e){this.path=vg(e,"auth.json"),this.deviceIdPath=vg(e,"device-id")}load(){if(!Tg(this.path))return;let e;try{e=JSON.parse(Pg(this.path,"utf8"))}catch{this.quarantine();return}let o=Bl(e);if(o?.version!==1){this.quarantine();return}let a=Bl(o.providers);if(!a){this.quarantine();return}for(let[u,m]of Object.entries(a)){if(!fv(m))continue;this.providers[u]=m}}deviceId(){if(Tg(this.deviceIdPath)){let o=Pg(this.deviceIdPath,"utf8").trim();if(o)return o}let e=crypto.randomUUID();return kg(Ul(this.deviceIdPath),{recursive:!0}),Cg(this.deviceIdPath,`${e}
7
+ `),e}migrateOpenAISubscription(){let e=this.providers.openai;if(e?.type!=="oauth")return;let o={...this.providers};o[St]??=e,delete o.openai;try{this.persist(o)}catch(a){throw Error("\u8F6C\u79FB ChatGPT \u8BA2\u9605\u51ED\u636E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u65B0\u542F\u52A8",{cause:a})}this.providers=o,this.dirty=!1}async read(e,o){return o?.signal?.throwIfAborted(),this.flush(),this.providers[e]?structuredClone(this.providers[e]):void 0}async list(e){return e?.signal?.throwIfAborted(),this.flush(),Object.entries(this.providers).map(([o,a])=>({providerId:o,type:a.type}))}modify(e,o,a){return this.enqueue(e,()=>this.applyModify(e,o),a)}delete(e,o){return this.enqueue(e,()=>{if(!(e in this.providers)){this.flush();return}let a={...this.providers};delete a[e],this.persist(a),this.providers=a,this.dirty=!1},o)}async close(){this.closed=!0;try{while(this.chains.size)await Promise.all(this.chains.values());this.flush()}catch(e){throw this.closed=!1,e}}enqueue(e,o,a){if(this.closed)return Promise.reject(Error("\u51ED\u636E\u5B58\u50A8\u6B63\u5728\u5173\u95ED"));let u=a?.signal;if(u?.aborted)return Promise.reject(u.reason);let m=this.chains.get(e)??Promise.resolve(),p,f=m.then(()=>{if(u?.throwIfAborted(),p)u?.removeEventListener("abort",p);return o()}),h=f.then(()=>{return},()=>{return});if(this.chains.set(e,h),h.then(()=>{if(this.chains.get(e)===h)this.chains.delete(e)}),!u)return f;return new Promise((I,E)=>{let S=()=>E(u.reason);if(p=S,u.addEventListener("abort",S,{once:!0}),f.then((R)=>{u.removeEventListener("abort",S),I(R)},(R)=>{u.removeEventListener("abort",S),E(R)}),u.aborted)S()})}async applyModify(e,o){this.flush();let a=this.providers[e]?structuredClone(this.providers[e]):void 0,u=await o(a);if(u===void 0)return a?structuredClone(a):void 0;return this.providers[e]=structuredClone(u),this.dirty=!0,this.flush(),structuredClone(u)}flush(){if(!this.dirty)return;this.persist(this.providers),this.dirty=!1}persist(e){kg(Ul(this.path),{recursive:!0});let o=`${this.path}.tmp-${process.pid}`,a=Ag(o,"w",384);try{Cg(a,`${JSON.stringify({version:1,providers:e},null,2)}
8
+ `),Rg(a)}finally{wg(a)}if($g(o,this.path),process.platform==="win32")return;let u=Ag(Ul(this.path),"r");try{Rg(u)}catch(m){if(!(m instanceof Error&&("code"in m)&&["EINVAL","ENOTSUP","EOPNOTSUPP"].includes(String(m.code))))throw m}finally{wg(u)}}quarantine(){try{$g(this.path,`${this.path}.corrupt-${Date.now()}`)}catch{}this.providers={}}}function Bl(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function fv(e){let o=Bl(e);if(!o)return!1;if(o.type==="api_key")return o.key===void 0||typeof o.key==="string";if(o.type!=="oauth")return!1;return typeof o.refresh==="string"&&typeof o.access==="string"&&typeof o.expires==="number"}var Cv=Og(),Hl=Ug();import{AsyncLocalStorage as vv}from"async_hooks";var q=new vv;var Mv=3,Bg=160,Ov=new Set(["bash","sh","zsh","dash","ash","ksh","mksh"]),_v=new Set(["if","then","else","elif","while","until","do","coproc","select","!"]),Hg=/^[A-Za-z_][A-Za-z0-9_]*=/,Lv=new Set([";","&&","||","|","|&","&","(",")",";;",";&",";;&"]),Nv=new Set([">",">>","<","<<",">|",">&","<&","<<<","<>","&>","&>>"]),qv=/(^|[^A-Za-z0-9_])(bash|sh|zsh|dash|ash|ksh|mksh|pwsh|powershell)(?![A-Za-z0-9_])/,Dv=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path","--config-env"]),Fv=new Set(["command","builtin","nohup","time","exec"]),jv=new Map([["sudo",["-u","-g","-h","-p","-t","-T","--user","--group","--host","--prompt"]],["doas",["-u","-C"]],["env",["-u","--unset","-C","--chdir","-S","--split-string"]],["nice",["-n","--adjustment"]]]);function Zc(e){return{out:e.out,depth:e.depth+1}}function Gg(e){return(e.split(/[\\/]/).pop()??e).toLowerCase().replace(/\.exe$/,"")}function Wl(e,o,a,u){let m=e.length,p=0,f=o;while(f<m){let h=e.charAt(f);if(h==="\\"){f+=2;continue}if(h==="'"||h==='"'||h==="`"){let I=f+1;while(I<m){let E=e.charAt(I);if(E==="\\"){I+=2;continue}if(E===h)break;I++}f=I+1;continue}if(h===a)p++;else if(h===u){if(p--,p===0)return f+1}f++}return m}function Uv(e){let o={text:"",subs:[],heredocs:[]},a=[],u=[],m=e.length,p=0,f=0,h=null,I=(E)=>{if(e.charAt(E)==="`"){let A=E+1;while(A<m){let P=e.charAt(A);if(P==="\\"){A+=2;continue}if(P==="`")break;A++}return o.subs.push(e.slice(E+1,A)),A<m?A+1:m}if(e.charAt(E+1)==="("){let A=Wl(e,E+1,"(",")");if(e.charAt(E+2)==="(")return a.push(e.slice(E,A)),A;return o.subs.push(e.slice(E+2,A-1)),A}let R=Wl(e,E+1,"{","}"),k=e.slice(E+2,R-1);for(let A=0;A<k.length;A++){let P=k.charAt(A);if(P==="\\"){A++;continue}if(P==="`"){let M=k.indexOf("`",A+1);o.subs.push(M<0?k.slice(A+1):k.slice(A+1,M)),A=M<0?k.length:M;continue}if(P==="$"&&k.charAt(A+1)==="("){let M=Wl(k,A+1,"(",")");o.subs.push(k.slice(A+2,M-1)),A=M-1}}return R};while(p<m){let E=e.charAt(p);if(h==="'"){if(E==="'")h=null;a.push(E),p++;continue}if(h==='"'){if(E==="\\"){if(!'$`"\\\n'.includes(e.charAt(p+1)))a.push("\\");a.push(E,e.charAt(p+1)),p+=2;continue}if(E==='"'){h=null,a.push(E),p++;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}a.push(E),p++;continue}if(E==="'"||E==='"'){h=E,a.push(E),p++;continue}if(E==="\\"){a.push(E,e.charAt(p+1)),p+=2;continue}if(E==="`"||E==="$"&&(e.charAt(p+1)==="("||e.charAt(p+1)==="{")){p=I(p);continue}if(E==="#"){let S=a.at(-1);if(S===void 0||`
9
+ ;&|()`.includes(S)){while(p<m&&e.charAt(p)!==`
10
+ `)p++;continue}a.push(E),p++;continue}if(E==="<"&&e.charAt(p+1)==="<"&&e.charAt(p+2)!=="<"){let S=p+2;if(e.charAt(S)==="-")S++;a.push(e.slice(p,S));let R=S;while(R<m&&(e.charAt(R)===" "||e.charAt(R)==="\t"))R++;let k="";while(R<m){let A=e.charAt(R);if(A==="'"||A==='"'){let P=e.indexOf(A,R+1);if(P<0)break;k+=e.slice(R+1,P),R=P+1;continue}if(A==="\\"){k+=e.charAt(R+1),R+=2;continue}if(` \r
11
+ ;&|()<>`.includes(A))break;k+=A,R++}if(k)u.push(k);p=S;continue}if(E===`
12
+ `){if(u.length>0){let S=qv.test(a.slice(f).join(""));p++;for(let R of u.splice(0)){let k=p,A=m;while(p<m){let P=e.indexOf(`
13
+ `,p),M=P<0?m:P;if(e.slice(p,M).trim()===R){A=p,p=P<0?m:P+1;break}p=P<0?m:P+1}if(S&&A>k)o.heredocs.push(e.slice(k,A))}}else p++;a.push(";",`
14
+ `),f=a.length;continue}a.push(E),p++}return o.text=a.join(""),o}function Au(e,o){if(o.depth>Mv)return;let a=Uv(e),u;try{u=Hl(a.text)}catch{return}let m=[];for(let p of u){if(typeof p==="string"){m.push({kind:"word",text:p});continue}if("pattern"in p){m.push({kind:"word",text:p.pattern});continue}if("op"in p)m.push({kind:"op",text:p.op})}Bv(m,o);for(let p of a.subs)Au(p,Zc(o));for(let p of a.heredocs)Au(p,Zc(o))}function Bv(e,o){let a=[],u=()=>{if(a.length>0)Gv(a,o);a=[]};for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;if(p.kind==="op"){if(Lv.has(p.text)){u();continue}if(Nv.has(p.text)){if(/^\d+$/.test(a.at(-1)??""))a.pop();m++}continue}a.push(p.text)}u()}function Gv(e,o){let a=0;for(;;){let f=e[a];if(f===void 0)return;if(_v.has(f)||Hg.test(f)){a++;continue}let h=Hv(Gg(f),e,a);if(h===a)break;a=h}let u=e[a];if(u===void 0)return;let m=Gg(u),p=e.slice(a+1);if(m==="git"){zv(u,p,o);return}if(Ov.has(m)){Kv(p,o);return}if(m==="powershell"||m==="pwsh")Kg(p,/^-(command|c)$/i,o);if(m==="cmd")Kg(p,/^\/[ck]$/i,o)}function Kg(e,o,a){for(let u=0;u<e.length;u++)if(o.test(e[u]??"")){let m=e.slice(u+1).join(" ");if(m.trim())Au(m,Zc(a));return}}function Kv(e,o){for(let a=0;a<e.length;a++){let u=e[a]??"";if(u==="-o"||u==="-O"||u==="--init-file"||u==="--rcfile"){a++;continue}if(u.startsWith("--"))continue;let m=/^-[a-zA-Z]*c(.*)$/.exec(u);if(m){let p=m[1]||e[a+1];if(p)Au(p,Zc(o));return}if(u.startsWith("-")||u==="")continue;return}}function Hv(e,o,a){if(Fv.has(e)){let p=a+1;while(o[p]?.startsWith("-"))p++;return p}let u=jv.get(e);if(!u)return a;let m=a+1;for(;;){let p=o[m];if(p===void 0)return m;if(u.includes(p)){m+=2;continue}if(Hg.test(p)||p.startsWith("-")){m++;continue}return m}}function Wo(e,o){return e.some((a)=>a.length>1&&a.startsWith("-")&&!a.startsWith("--")&&a.slice(1).includes(o))}function fo(e,o){return e.some((a)=>a===`--${o}`||a.startsWith(`--${o}=`))}var Wv={reset:()=>"reset \u79FB\u52A8\u6216\u56DE\u6EDA HEAD/\u7D22\u5F15",clean:(e)=>(Wo(e,"f")||Wo(e,"i")||fo(e,"force")||fo(e,"interactive"))&&!(Wo(e,"n")||fo(e,"dry-run"))?"clean -f \u5220\u9664\u672A\u8DDF\u8E2A\u6587\u4EF6\uFF0C\u4E0D\u53EF\u6062\u590D":void 0,checkout:(e)=>Wo(e,"f")||fo(e,"force")||e.includes("--")||e.includes(".")?"checkout \u653E\u5F03\u5DE5\u4F5C\u533A\u6539\u52A8":void 0,switch:(e)=>Wo(e,"f")||fo(e,"force")||Wo(e,"C")||fo(e,"force-create")?"switch \u5F3A\u5236\u6A21\u5F0F\u8986\u76D6\u672C\u5730\u72B6\u6001":void 0,restore:()=>"restore \u653E\u5F03\u5DE5\u4F5C\u533A\u6216\u7D22\u5F15\u4E2D\u7684\u6539\u52A8",push:(e)=>Wo(e,"f")||fo(e,"force")||fo(e,"force-with-lease")||fo(e,"force-if-includes")||fo(e,"delete")||fo(e,"mirror")||e.some((o)=>o.startsWith("+")||o.startsWith(":"))?"\u5F3A\u5236\u63A8\u9001\u6216\u5220\u9664\u8FDC\u7AEF\u5F15\u7528\u6539\u5199\u8FDC\u7AEF\u5386\u53F2":void 0,commit:(e)=>fo(e,"amend")?"commit --amend \u6539\u5199\u6700\u8FD1\u4E00\u6B21\u63D0\u4EA4":void 0,rebase:()=>"rebase \u91CD\u5199\u63D0\u4EA4\u5386\u53F2",branch:(e)=>Wo(e,"D")||Wo(e,"M")?"branch -D/-M \u5F3A\u5236\u5220\u9664\u6216\u8986\u76D6\u5206\u652F\uFF0C\u672A\u5408\u5E76\u63D0\u4EA4\u5C06\u4E22\u5931":void 0,stash:(e)=>e[0]==="drop"||e[0]==="clear"?"stash drop/clear \u5220\u9664\u50A8\u85CF\u8BB0\u5F55":void 0,"update-ref":()=>"update-ref \u76F4\u63A5\u6539\u5199\u6216\u5220\u9664\u5F15\u7528\uFF0C\u7ED5\u8FC7\u5E38\u89C4\u68C0\u67E5",reflog:(e)=>e[0]==="expire"||e[0]==="delete"?"\u6E05\u7406 reflog \u5207\u65AD\u8BEF\u5220\u6570\u636E\u7684\u6062\u590D\u9014\u5F84":void 0,gc:(e)=>fo(e,"prune")?"gc --prune \u7ACB\u5373\u9500\u6BC1\u4E0D\u53EF\u8FBE\u5BF9\u8C61\uFF0C\u5207\u65AD\u6062\u590D\u9014\u5F84":void 0,"filter-branch":()=>"filter-branch \u5168\u91CF\u91CD\u5199\u5386\u53F2","filter-repo":()=>"filter-repo \u5168\u91CF\u91CD\u5199\u5386\u53F2",rm:(e)=>Wo(e,"f")||fo(e,"force")?"git rm -f \u5F3A\u5236\u5220\u9664\u542B\u672A\u63D0\u4EA4\u6539\u52A8\u7684\u8DDF\u8E2A\u6587\u4EF6":void 0,worktree:(e)=>e[0]==="remove"&&(Wo(e,"f")||fo(e,"force"))?"worktree remove --force \u9500\u6BC1\u6574\u4E2A\u5DE5\u4F5C\u6811":void 0};function zv(e,o,a){let u=0;for(;;){let I=o[u];if(I===void 0)break;if(Dv.has(I)){u+=2;continue}if(/^--[a-z][a-z0-9-]*=.+/i.test(I)||/^-[Cc].+/.test(I)||I.startsWith("-")){u++;continue}break}let m=o[u]?.toLowerCase();if(!m)return;let p=Wv[m];if(!p)return;let f=p(o.slice(u+1));if(!f)return;let h=[e,...o.slice(u)].join(" ");a.out.push({rule:m,fragment:h.length>Bg?`${h.slice(0,Bg)}\u2026`:h,reason:f})}function zo(e){let o={out:[],depth:0};return Au(e,o),o.out}function Wg(e){let o=e.slice(0,5).map((u)=>`${u.fragment}\uFF08${u.reason}\uFF09`),a=e.length>o.length?` \u7B49 ${e.length} \u5904`:"";return`${o.join("\uFF1B")}${a}`}var zl=new Map;function Vv(e,o,a,u,m){let p=`sa${Math.random().toString(36).slice(2,10)}${Date.now().toString(36)}`;return new Promise((f)=>{let h=(E)=>{if(!zl.delete(p))return;m?.removeEventListener("abort",I),f(E)},I=()=>{zg(e,p),h("aborted")};if(zl.set(p,{session:e,finish:h}),e.appendExtension({namespace:mn,kind:"requested",schemaVersion:1,payload:{id:p,sessionID:e.id,command:o.slice(0,4000),summary:u.slice(0,5).map(({fragment:E,reason:S})=>({fragment:E,reason:S})),askedAt:Date.now()},display:{text:`\u5371\u9669 git \u6307\u4EE4\u5F85\u6388\u6743\uFF1A${a}`}}),m?.aborted)I();else m?.addEventListener("abort",I,{once:!0})})}function zg(e,o){try{e.appendExtension({namespace:mn,kind:"cancelled",schemaVersion:1,payload:{id:o,sessionID:e.id,resolvedAt:Date.now()},display:{text:"\u6388\u6743\u7B49\u5F85\u88AB\u4E2D\u65AD"}})}catch{}}function Kn(e,o,a){let u=zl.get(o);if(!u||u.session!==e){if(!Jv(e,o))return"unknown";return zg(e,o),"expired"}return e.appendExtension({namespace:mn,kind:"answered",schemaVersion:1,payload:{id:o,sessionID:e.id,approved:a,resolvedAt:Date.now()},display:{text:a?"\u7528\u6237\u5141\u8BB8\u6267\u884C":"\u7528\u6237\u62D2\u7EDD\u6267\u884C"}}),u.finish(a?"approved":"denied"),"answered"}function Jv(e,o){let a=!1;for(let u of e.entries(0,["extension"],!1)){if(u.type!=="extension"||u.namespace!==mn)continue;let m=u.payload;if(!m||typeof m!=="object"||!("id"in m)||m.id!==o)continue;if(u.kind==="requested")a=!0;else if(u.kind==="answered"||u.kind==="cancelled")return!1}return a}function jo(e){return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${Wg(e)}\u3002\u6A21\u578B\u4E0D\u5F97\u6267\u884C\u56DE\u6EDA\u3001\u9500\u6BC1\u6570\u636E\u6216\u6539\u5199\u5386\u53F2\u7C7B\u64CD\u4F5C\u3002`}async function He(e,o){let a=zo(e);if(!a.at(0))return;let m=Wg(a),p=q.getStore();if(p?.info().kind!=="main")return`[shell-guard] \u62E6\u622A\u5371\u9669 git \u6307\u4EE4\uFF1A${m}\u3002\u6B64\u5904\u6CA1\u6709\u53EF\u7528\u7684\u7528\u6237\u6388\u6743\u901A\u9053\uFF0C\u8BF7\u5411\u7528\u6237\u8BF4\u660E\u540E\u679C\uFF0C\u7531\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u6267\u884C\u3002`;if(o?.aborted)return`${jo(a)}\uFF08\u8FD0\u884C\u5DF2\u4E2D\u65AD\uFF09`;let f=await Vv(p,e,m,a,o);if(f==="approved")return;return`[shell-guard] \u5371\u9669 git \u6307\u4EE4 ${m} \u672A\u6267\u884C\uFF1A${f==="denied"?"\u7528\u6237\u62D2\u7EDD\u6267\u884C\u8BE5\u547D\u4EE4":"\u7B49\u5F85\u7528\u6237\u7B54\u590D\u671F\u95F4\u8FD0\u884C\u88AB\u4E2D\u65AD"}\u3002\u4E0D\u8981\u518D\u91CD\u8BD5\u6216\u53D8\u76F8\u6267\u884C\uFF1B\u786E\u6709\u9700\u8981\u8BF7\u7528\u6237\u672C\u4EBA\u5728\u7EC8\u7AEF\u8FD0\u884C\u3002`}var ks={assign:0,create:0,clone:0,discard:0,update:0};function ea(e,o,a){return e>=o&&e<=a}function Qg(e){return e===8205}function Qv(e){return ea(e,55296,56319)}function Vg(e){return ea(e,127462,127487)}function Xg(e){return ea(e,65024,65039)}function Yg(e){return ea(e,768,879)||ea(e,6832,6911)||ea(e,7616,7679)||ea(e,65056,65071)}function em(e){return e>65535?2:1}function Jg(e,o){while(o<e.length){let a=e.codePointAt(o);if(Yg(a)||Xg(a))o+=em(a);else break}return o}function Vl(e,o){let a=e.codePointAt(o),u=o+em(a);u=Jg(e,u);while(u<e.length-1&&Qg(e.codePointAt(u))){let m=e.codePointAt(u+1);u+=1+em(m),u=Jg(e,u)}if(Vg(a)&&u<e.length&&Vg(e.codePointAt(u)))u+=em(e.codePointAt(u));return u}function Zg(e){return e>=768&&(Qv(e)||Yg(e)||Xg(e)||Qg(e))}function ey(e){let o=0,a=0;while(a<e.length)a=Vl(e,a),o++;return o}function Xv(e,o){let a=0,u=0;while(u<e.length)if(u=Vl(e,u),++a>=o)return!0;return!1}function Yv(e,o){let a=0,u=0;while(u<e.length)if(u=Vl(e,u),++a>o)return!1;return!0}function ty(e,o){if(o===0)return!0;if(e.length<o)return!1;let a=0;while(!0){if(Zg(e.charCodeAt(a)))return Xv(e,o);if(++a>=o)return!0}}function ry(e,o){if(e.length<=o)return!0;let a=0;while(!0){if(Zg(e.charCodeAt(a)))return Yv(e,o);if(++a>o)return!1}}function $e(e){return Array.isArray(e)}function Fr(e){return v(typeof e,"bigint")}function nn(e){return v(typeof e,"boolean")}function Jl(e){if(er(e)||!Ps(e))return!1;let o=Function.prototype.toString.call(e);if(/^class\s/.test(o))return!0;if(/\[native code\]/.test(o))return!0;return!1}function Ps(e){return v(typeof e,"function")}function tm(e){return Number.isInteger(e)}function Ao(e){return v(e,null)}function Dt(e){return Number.isFinite(e)}function Jo(e){return mt(e)&&!$e(e)}function mt(e){return v(typeof e,"object")&&!Ao(e)}function ht(e){return v(typeof e,"string")}function Ql(e){return v(typeof e,"symbol")}function er(e){return v(e,void 0)}function v(e,o){return e===o}function ta(e,o){return e>o}function Pu(e,o){return e<o}function $s(e,o){return e<=o}function va(e,o){return e>=o}function ny(e,o){if(Fr(e)||Fr(o))return BigInt(e)%BigInt(o)===0n;let a=0.0000000001;if(!Dt(e))return!0;if(tm(e)&&1/o%1===0)return!0;let u=e%o;return Math.min(Math.abs(u),Math.abs(u-o),Math.abs(u+o))<a}function oy(e){if(!mt(e))return!1;let o=globalThis.Object.getPrototypeOf(e);if(Ao(o))return!1;return v(typeof o.constructor,"function")&&!(v(o.constructor,globalThis.Object)||v(o.constructor.name,"Object"))}function ra(e){return Fr(e)||nn(e)||Ao(e)||Dt(e)||ht(e)||er(e)}function eM(e){return ey(e)}function sy(e,o){return ry(e,o)}function iy(e,o){return ty(e,o)}function Zr(e,o,a){return e.every((u,m)=>m<o||a(u,m))}function Mn(e,o,a){let u=!0;return e.forEach((m,p)=>{if(p>=o&&!a(m,p))u=!1}),u}function Ma(e,o){return e.some((a,u)=>o(a,u))}function ay(e,o){let a=!1;return e.forEach((u,m)=>{if(o(u,m))a=!0}),a}function Xl(e,o){return e.reduce((a,u,m)=>o(u,m)?++a:a,0)}function yt(e,o,a){return v(e.length,0)?a():o(e[0],e.slice(1))}function $u(e){return v(e,"__proto__")||v(e,"constructor")||v(e,"prototype")}function me(e,o){return $u(o)?Object.prototype.hasOwnProperty.call(e,o):(o in e)}function Yl(e){return xe(e).map((o)=>[new RegExp(`^${o}$`),e[o]])}function on(e){return Object.entries(e)}function xe(e){return Object.getOwnPropertyNames(e)}function uy(e){return Object.getOwnPropertySymbols(e)}function Zl(e){return Object.values(e)}function tM(e,o){if(!mt(o))return!1;let a=xe(e);return v(a.length,xe(o).length)&&a.every((u)=>Oa(e[u],o[u]))}function rM(e,o){return $e(o)&&v(e.length,o.length)&&e.every((a,u)=>Oa(e[u],o[u]))}function Oa(e,o){return $e(e)?rM(e,o):mt(e)?tM(e,o):v(e,o)}var nM=/^[\p{ID_Start}_$][\p{ID_Continue}_$\u200C\u200D]*$/u;function oM(e){return nM.test(e)}function An(e,o){return`(${e} && ${o})`}function yr(e,o){return`(${e} || ${o})`}function Bn(e){return`!(${e})`}function rm(e){return`Array.isArray(${e})`}function cy(e){return`typeof ${e} === "bigint"`}function sM(e){return`typeof ${e} === "boolean"`}function iM(e){return`Number.isInteger(${e})`}function aM(e){return`${e} === null`}function my(e){return`Number.isFinite(${e})`}function py(e){return An(ly(e),Bn(rm(e)))}function ly(e){return`typeof ${e} === "object" && ${e} !== null`}function dy(e){return`typeof ${e} === "string"`}function uM(e){return`typeof ${e} === "symbol"`}function ed(e){return`${e} === undefined`}function cM(e){return`typeof ${e} === "function"`}function mM(e){return`Guard.IsConstructor(${e})`}function bo(e,o){return`${e} === ${o}`}function fy(e,o){return`${e} > ${o}`}function td(e,o){return`${e} < ${o}`}function na(e,o){return`${e} <= ${o}`}function Cu(e,o){return`${e} >= ${o}`}function pM(e,o){return`Guard.IsMinLength(${e}, ${o})`}function lM(e,o){return`Guard.IsMaxLength(${e}, ${o})`}function Cs(e,o,a,u){return v(o,"0")?`${e}.every((${a[0]}, ${a[1]}) => (${u}))`:`${e}.every((${a[0]}, ${a[1]}) => (${a[1]} < ${o}) || (${u}))`}function dM(e,o,a){return`${e}.some((${o[0]}, ${o[1]}) => ${a})`}function fM(e,o,a){return`((value) => { let result = false; value.forEach((${o[0]}, ${o[1]}) => { if (${a}) result = true }); return result })(${e})`}function nm(e,o,a){return`${e}.reduce((result, ${o[0]}, ${o[1]}) => (${a}) ? ++result : result, 0)`}function hy(e){return`Object.entries(${e})`}function oa(e){return`Object.getOwnPropertyNames(${e})`}function sa(e,o){return v(o,'"__proto__"')||v(o,'"constructor"')?`Object.prototype.hasOwnProperty.call(${e}, ${o})`:`${o} in ${e}`}function gy(e,o){return`Guard.IsDeepEqual(${e}, ${o})`}function hM(e){return`[${e.join(", ")}]`}function xi(e,o){return`((${e.join(", ")}) => ${o})`}function Ir(e,o){return`${e}(${o.join(", ")})`}function rd(e,o){return`new ${e}(${o.join(", ")})`}function Et(e,o){return`${e}${oM(o)?`.${o}`:`[${Te(o)}]`}`}function Te(e){if(!ra(e))throw Error("Unsupported Constant");return ht(e)?JSON.stringify(e):`${e}`}function gM(e,o,a){return`(${e} ? ${o} : ${a})`}function om(e){return`{ ${e.join("; ")}; }`}function Qs(e,o){return`const ${e} = ${o}`}function yy(e,o){return`if(${e}) { ${o} }`}function sm(e){return`return ${e}`}function On(e){return v(e.length,0)?"true":e.reduce((o,a)=>An(o,a))}function nd(e){return v(e.length,0)?"false":e.reduce((o,a)=>yr(o,a))}function yM(e,o){return`Guard.IsMultipleOf(${e}, ${o})`}function xM(e){return e instanceof Boolean}function IM(e){return e instanceof Number}function EM(e){return e instanceof String}function xy(e){return globalThis.ArrayBuffer.isView(e)}function Iy(e){return e instanceof globalThis.RegExp}function bM(e){return e instanceof globalThis.Date}function SM(e){return e instanceof globalThis.Set}function wM(e){return e instanceof globalThis.Map}var RM={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function ts(){return RM}function Ii(e){return ts().immutableTypes?Object.freeze(e):e}function fn(e,o){return ks.assign+=1,Ii({...e,...o})}function kM(e){return e}function AM(e){return me(e,"~kind")||me(e,"~unsafe")}function PM(e){let o={};for(let a of xe(e)){if($u(a))continue;let u=Object.getOwnPropertyDescriptor(e,a);if(u.value=ia(u.value),v(u.enumerable,!0))o[a]=u.value;else Object.defineProperty(o,a,u)}return o}function $M(e){let o={};for(let a of xe(e)){if($u(a))continue;o[a]=ia(e[a])}for(let a of uy(e))o[a]=ia(e[a]);return o}function CM(e){return oy(e)?kM(e):AM(e)?PM(e):$M(e)}function vM(e){return e.map((o)=>ia(o))}function MM(e){return e.slice()}function OM(e){return new RegExp(e.source,e.flags)}function _M(e){return new Map(ia([...e.entries()]))}function LM(e){return new Set(ia([...e.values()]))}function ia(e){return xy(e)?MM(e):Iy(e)?OM(e):wM(e)?_M(e):SM(e)?LM(e):$e(e)?vM(e):mt(e)?CM(e):e}function _a(e){return ks.clone+=1,ia(e)}function NM(e,o){for(let a of Object.keys(o))Object.defineProperty(e,a,{configurable:!0,writable:!0,enumerable:!1,value:o[a]});return e}function Ey(e,o){return{...e,...o}}function _t(e,o,a={}){ks.create+=1;let u=Ey(o,a),m=ts().enumerableKind?Ey(u,e):NM(u,e);return Ii(m)}function ss(e,o){ks.discard+=1;let a={};for(let u of xe(e)){if(o.includes(u))continue;let m=Object.getOwnPropertyDescriptor(e,u);m.value=_a(m.value),Object.defineProperty(a,u,m)}return Ii(a)}function Tt(e,o,a){ks.update+=1;let u=ts(),m=_a(e);for(let p of Object.keys(o))Object.defineProperty(m,p,{configurable:!0,writable:!0,enumerable:u.enumerableKind,value:o[p]});for(let p of Object.keys(a))Object.defineProperty(m,p,{configurable:!0,enumerable:!0,writable:!0,value:a[p]});return Ii(m)}function Se(e,o){return mt(e)&&me(e,"~kind")&&v(e["~kind"],o)}function Or(e){return mt(e)}function we(e,o,a){return _t({"~kind":"Deferred"},{type:"deferred",action:e,parameters:o,options:a},{})}function Ei(e){return Se(e,"Deferred")}function qM(e){return Tt(e,{"~readonly":!0},{})}function Mu(e,o){return Tt(qM(e),{},o)}function by(e,o,a,u){let m=pe(e,o,a);return Mu(m,u)}function DM(e){return Tt(e,{"~optional":!0},{})}function Ou(e,o){return Tt(DM(e),{},o)}function Sy(e,o,a,u){let m=pe(e,o,a);return Ou(m,u)}function F(e,o){return _t({"~kind":"Array"},{type:"array",items:e},o)}function At(e){return Se(e,"Array")}function La(e){return ss(e,["~kind","type","items"])}function Ms(e,o,a={}){return _t({"~kind":"Constructor"},{type:"constructor",parameters:e,instanceType:o},a)}function zr(e){return Se(e,"Constructor")}function wy(e){return ss(e,["~kind","type","parameters","instanceType"])}function Os(e,o,a={}){return _t({["~kind"]:"Function"},{type:"function",parameters:e,returnType:o},a)}function Vr(e){return Se(e,"Function")}function Ty(e){return ss(e,["~kind","type","parameters","returnType"])}function en(e,o){return _t({["~kind"]:"Ref"},{$ref:e},o)}function Xt(e){return Se(e,"Ref")}function bi(e,o){return _t({"~kind":"Generic"},{type:"generic",parameters:e,expression:o})}function Na(e){return Se(e,"Generic")}function qa(e){return _t({["~kind"]:"Any"},{},e)}function _r(e){return Se(e,"Any")}var Ry="(?!)";function nr(e){return _t({"~kind":"Never"},{not:{}},e)}function So(e){return Se(e,"Never")}function Ls(e,o={}){return we("AddOptional",[e],o)}function aa(e,o={}){return Ou(e,o)}function n(e){return aa(e)}function tn(e){return Or(e)&&me(e,"~optional")}function ky(e){return xe(e).filter((o)=>!tn(e[o]))}function im(e){return xe(e)}function am(e){return Zl(e)}function l(e,o={}){let a=ky(e),u=a.length>0?{required:a}:{};return _t({"~kind":"Object"},{type:"object",...u,properties:e},o)}function ze(e){return Se(e,"Object")}function Ay(e){return ss(e,["~kind","type","properties","required"])}function Y(e){return _t({["~kind"]:"Unknown"},{},e)}function Jr(e){return Se(e,"Unknown")}function Ns(e,o,a){let u=xe(e).reduce((m,p)=>({...m,[p]:Tt(e[p],{},{$id:p})}),{});return _t({["~kind"]:"Cyclic"},{$defs:u,$ref:o},a)}function ar(e){return Se(e,"Cyclic")}function Sr(e){return Tt(e,{["~unsafe"]:null},{})}function um(e){return Jo(e)&&me(e,"~unsafe")&&Ao(e["~unsafe"])}function Pn(e,o){return o[e.length]?.(...e)??(()=>{throw Error("Invalid Arguments")})()}function _u(...e){let[o,a]=Pn(e,{2:(u,m)=>[u,m,m],1:(u)=>[u,Y(),Y()]});return _t({["~kind"]:"Infer"},{type:"infer",name:o,extends:a},{})}function Qr(e){return Se(e,"Infer")}function ua(e,o,a,u={}){return _t({"~kind":"Dependent"},{if:e,then:o,else:a},u)}function jr(e){return Se(e,"Dependent")}function Py(e){return ss(e,["~kind","if","then","else"])}function $y(e){return Jo(e)}function Cy(e){return xe(e).filter((a)=>isNaN(a)).reduce((a,u)=>[...a,e[u]],[])}function vy(e){return ht(e)||Dt(e)}function My(e,o){let a=$y(e)?Cy(e):e;return _t({"~kind":"Enum"},{enum:a},o)}function Xr(e){return Se(e,"Enum")}function Ln(e,o={}){return _t({"~kind":"Intersect"},{allOf:e},o)}function Ke(e){return Se(e,"Intersect")}function Oy(e){return ss(e,["~kind","allOf"])}var od=void 0;function FM(){try{return Ly("null")(),!0}catch{return!1}}function _y(){if(er(od))od=FM();return od&&ts().useAcceleration}function Ly(...e){return new globalThis.Function(...e)}function Ur(){throw Error("Unreachable")}function jM(e){let o=new Set,a=e;while(a&&a!==Object.prototype){for(let u of Reflect.ownKeys(a))if(u!=="constructor"&&typeof u!=="symbol")o.add(u);a=Object.getPrototypeOf(a)}return[...o]}function UM(e){return typeof e==="number"}var Gn;(function(e){e[e.Array=0]="Array",e[e.BigInt=1]="BigInt",e[e.Boolean=2]="Boolean",e[e.Date=3]="Date",e[e.Constructor=4]="Constructor",e[e.Function=5]="Function",e[e.Null=6]="Null",e[e.Number=7]="Number",e[e.Object=8]="Object",e[e.RegExp=9]="RegExp",e[e.String=10]="String",e[e.Symbol=11]="Symbol",e[e.TypeArray=12]="TypeArray",e[e.Undefined=13]="Undefined"})(Gn||(Gn={}));var Da=BigInt("14695981039346656037"),[BM,GM]=[BigInt("1099511628211"),BigInt("18446744073709551616")],KM=Array.from({length:256}).map((e,o)=>BigInt(o)),Fy=new Float64Array(1),jy=new DataView(Fy.buffer),Uy=new Uint8Array(Fy.buffer);function Tn(e){Da=Da^KM[e],Da=Da*BM%GM}function HM(e){Tn(Gn.Array);for(let o of e)Si(o)}function WM(e){Tn(Gn.BigInt),jy.setBigInt64(0,e);for(let o of Uy)Tn(o)}function qy(e){Tn(Gn.Boolean),Tn(e?1:0)}function zM(e){Tn(Gn.Constructor),Si(e.toString())}function VM(e){Tn(Gn.Date),Si(e.getTime())}function JM(e){Tn(Gn.Function),Si(e.toString())}function QM(e){Tn(Gn.Null)}function Dy(e){Tn(Gn.Number),jy.setFloat64(0,e,!0);for(let o of Uy)Tn(o)}function XM(e){Tn(Gn.Object);for(let o of jM(e).sort())Si(o),Si(e[o])}function YM(e){Tn(Gn.RegExp),sd(e.toString())}var ZM=new TextEncoder;function sd(e){Tn(Gn.String);for(let o of ZM.encode(e))Tn(o)}function eO(e){Tn(Gn.Symbol),Si(e.toString())}function tO(e){Tn(Gn.TypeArray);let o=new Uint8Array(e.buffer);for(let a=0;a<o.length;a++)Tn(o[a])}function rO(e){return Tn(Gn.Undefined)}function Si(e){return xy(e)?tO(e):bM(e)?VM(e):Iy(e)?YM(e):xM(e)?qy(e.valueOf()):EM(e)?sd(e.valueOf()):IM(e)?Dy(e.valueOf()):UM(e)?Dy(e):$e(e)?HM(e):nn(e)?qy(e):Fr(e)?WM(e):Jl(e)?zM(e):Ao(e)?QM(e):mt(e)?XM(e):ht(e)?sd(e):Ql(e)?eO(e):er(e)?rO(e):Ps(e)?JM(e):Ur()}function By(e){return Da=BigInt("14695981039346656037"),Si(e),Da}function id(e){return By(e).toString(16).padStart(16,"0")}function Gy(e){switch(e.keyword){case"additionalProperties":return"must not have additional properties";case"anyOf":return"must match a schema in anyOf";case"boolean":return"schema is false";case"const":return"must be equal to constant";case"contains":return"must contain at least 1 valid item";case"dependencies":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"dependentRequired":return`must have properties ${e.params.dependencies.join(", ")} when property ${e.params.property} is present`;case"enum":return"must be equal to one of the allowed values";case"exclusiveMaximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"exclusiveMinimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"format":return`must match format "${e.params.format}"`;case"if":return`must match "${e.params.failingKeyword}" schema`;case"maxItems":return`must not have more than ${e.params.limit} items`;case"maxLength":return`must not have more than ${e.params.limit} characters`;case"maxProperties":return`must not have more than ${e.params.limit} properties`;case"maximum":return`must be ${e.params.comparison} ${e.params.limit}`;case"minItems":return`must not have fewer than ${e.params.limit} items`;case"minLength":return`must not have fewer than ${e.params.limit} characters`;case"minProperties":return`must not have fewer than ${e.params.limit} properties`;case"minimum":return`must be ${e.params.comparison} ${e.params.limit}`;case"multipleOf":return`must be multiple of ${e.params.multipleOf}`;case"not":return"must not be valid";case"oneOf":return"must match exactly one schema in oneOf";case"pattern":return`must match pattern "${e.params.pattern}"`;case"propertyNames":return`property names ${e.params.propertyNames.join(", ")} are invalid`;case"required":return`must have required properties ${e.params.requiredProperties.join(", ")}`;case"type":return typeof e.params.type==="string"?`must be ${e.params.type}`:`must be either ${e.params.type.join(" or ")}`;case"unevaluatedItems":return"must not have unevaluated items";case"unevaluatedProperties":return"must not have unevaluated properties";case"uniqueItems":return"must not have duplicate items";case"~refine":return e.params.message;default:return"an unknown validation error occurred"}}var nO=Gy;function Ky(){return nO}class cm{constructor(e,o){this.type=e,this.decode=o}Encode(e){let o=this.type,a=Hn(o)?(p)=>this.decode(o["~codec"].decode(p)):this.decode,u=Hn(o)?(p)=>o["~codec"].encode(e(p)):e,m={decode:a,encode:u};return Tt(this.type,{"~codec":m},{})}}class mm{constructor(e){this.type=e}Decode(e){return new cm(this.type,e)}}function pm(e){return new mm(e)}function Wy(e,o){return pm(e).Decode(o).Encode(()=>{throw Error("Encode not implemented")})}function zy(e,o){return pm(e).Decode(()=>{throw Error("Decode not implemented")}).Encode(o)}function Hn(e){return Or(e)&&me(e,"~codec")&&mt(e["~codec"])&&me(e["~codec"],"encode")&&me(e["~codec"],"decode")}function Vy(e){return Fa(e)}function ma(e){return Or(e)&&me(e,"~immutable")}function qs(e,o={}){return we("AddReadonly",[e],o)}function pa(e,o={}){return Mu(e,o)}function Jy(e){return pa(e)}function la(e){return Or(e)&&me(e,"~readonly")}function sO(e,o){let a=lm(e)?[...e["~refine"],o]:[o];return Tt(e,{"~refine":a},{})}function Qy(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,()=>"Refine Error"]});return sO(o,{check:a,error:u})}function iO(e){return Jo(e)&&me(e,"check")&&me(e,"error")&&Ps(e.check)&&Ps(e.error)}function lm(e){return Or(e)&&me(e,"~refine")&&$e(e["~refine"])&&Zr(e["~refine"],0,(o)=>iO(o))}var Xy="-?(?:0|[1-9][0-9]*)n";function Lu(e){return _t({"~kind":"BigInt"},{type:"bigint"},e)}function wo(e){return Se(e,"BigInt")}function N(e){return _t({"~kind":"Boolean"},{type:"boolean"},e)}function Wn(e){return Se(e,"Boolean")}function Nu(e){return _t({"~kind":"Identifier"},{name:e})}function Yy(e){return Se(e,"Identifier")}var dm="-?(?:0|[1-9][0-9]*)";function x(e){return _t({"~kind":"Integer"},{type:"integer"},e)}function hn(e){return Se(e,"Integer")}class Zy extends Error{constructor(e){super("Invalid Literal value");Object.defineProperty(this,"cause",{value:{value:e},writable:!1,configurable:!1,enumerable:!1})}}function aO(e){return Fr(e)?"bigint":nn(e)?"boolean":Dt(e)?"number":ht(e)?"string":(()=>{throw new Zy(e)})()}function i(e,o){return _t({"~kind":"Literal"},{type:aO(e),const:e},o)}function fm(e){return Fr(e)||nn(e)||Dt(e)||ht(e)}function ex(e){return gt(e)&&Fr(e.const)}function tx(e){return gt(e)&&nn(e.const)}function hm(e){return gt(e)&&Dt(e.const)}function gm(e){return gt(e)&&ht(e.const)}function gt(e){return Se(e,"Literal")}function Nn(e){return _t({"~kind":"Null"},{type:"null"},e)}function Ds(e){return Se(e,"Null")}var ym="-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?";function re(e){return _t({"~kind":"Number"},{type:"number"},e)}function $r(e){return Se(e,"Number")}function ja(e){return _t({"~kind":"Symbol"},{type:"symbol"},e)}function Fs(e){return Se(e,"Symbol")}function da(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[m,p,p],1:(m)=>[m,Y(),Y()]});return _t({"~kind":"Parameter"},{name:o,extends:a,equals:u},{})}function rx(e){return Se(e,"Parameter")}var xm=".*";function s(e){return _t({"~kind":"String"},{type:"string"},e)}function Yr(e){return Se(e,"String")}function g(e,o={}){return _t({"~kind":"Union"},{anyOf:e},o)}function ye(e){return Se(e,"Union")}function nx(e){return ss(e,["~kind","anyOf"])}function qu(e){let o=ox(e);return v(o.length,2)?o[0]:[]}function uO(e){return!0}function sx(e){return yt(e,(o,a)=>cO(o)?sx(a):!1,()=>!0)}function ix(e){return v(e.length,0)?!1:sx(e)}function cO(e){return ye(e)?ix(e.anyOf):gt(e)?uO(e.const):!1}function Im(e){return ix(e)}function Em(e){return _t({["~kind"]:"TemplateLiteral"},{type:"string",pattern:e},{})}function ax(e,o,a=[]){return yt(e,(u,m)=>ax(m,o,[...a,`${u}${o}`]),()=>a)}function mO(e,o){return v(e.length,0)?[`${o}`]:ax(e,o)}function ux(e,o,a=[]){return yt(o,(u,m)=>ux(e,m,[...a,...cx(e,u)]),()=>a)}function cx(e,o){return ye(o)?ux(e,o.anyOf):gt(o)?mO(e,o.const):Ur()}function mx(e,o){return yt(o,(a,u)=>mx(cx(e,a),u),()=>e)}function pO(e){return e.map((o)=>i(o))}function lO(e){let o=mx([],e),a=pO(o);return g(a)}function dO(e){return v(e.length,0)?Ur():v(e.length,1)&&gt(e[0])?e[0]:lO(e)}function ad(e){let o=qu(e);return v(o.length,0)?s():Im(o)?dO(o):Em(e)}function Du(e){let o=ad(e);return mr(o)?s():o}function yo(e,o){let u={[e]:o};return _t({["~kind"]:"Record"},{type:"object",patternProperties:u})}function px(e){return yo(us,e)}function lx(e){return l({true:e,false:e})}function Br(e,o={}){let[a,u,m]=[e,e.length,!1];return _t({["~kind"]:"Tuple"},{type:"array",additionalItems:m,items:a,minItems:u},o)}function dt(e){return Se(e,"Tuple")}function dx(e){return ss(e,["~kind","type","items","minItems","additionalItems"])}function fO(e){return ss(e,["~readonly"])}function ud(e,o){return Tt(fO(e),{},o)}function fx(e,o,a,u){let m=pe(e,o,a);return ud(m,u)}function hx(e,o={}){return we("RemoveReadonly",[e],o)}function gx(e,o={}){return ud(e,o)}function hO(e){return ss(e,["~optional"])}function cd(e,o){return Tt(hO(e),{},o)}function yx(e,o,a,u){let m=pe(e,o,a);return cd(m,u)}function xx(e,o={}){return we("RemoveOptional",[e],o)}function bm(e,o={}){return cd(e,o)}function md(e){return e.reduceRight((a,u,m)=>({[m]:u,...a}),{})}function Ix(e){let o=md(e.items);return l(o)}function pd(e){return ze(e)||dt(e)}function gO(e,o){return la(e)?la(o)?!0:!1:!1}function yO(e,o){return tn(e)?tn(o)?!0:!1:!1}function xO(e,o){let a=gO(e,o),u=yO(e,o),m=Cr([e,o]),p=gx(bm(m));return a&&u?pa(aa(p)):a&&!u?pa(p):!a&&u?aa(p):p}function IO(e,o,a){return a in e?a in o?xO(e[a],o[a]):e[a]:(a in o)?o[a]:nr()}function EO(e,o){return[...new Set([...xe(e),...xe(o)])].reduce((m,p)=>({...m,[p]:IO(e,o,p)}),{})}function Ex(e){return ze(e)?e.properties:dt(e)?md(e.items):{}}function bx(e,o){let a=Ex(e),u=Ex(o),m=EO(a,u);return l(m)}function bO(e,o){let a=Ua(e,o);return v(a,ju)?e:v(a,Uu)?o:v(a,Fu)?o:nr()}function SO(e,o){let a=pd(e),u=pd(o);return a&&u?bx(e,o):a&&!u?e:!a&&u?o:bO(e,o)}function Sx(e,o){return So(e)?e:_r(e)?e:Jr(e)?o:So(o)?o:_r(o)?o:Jr(o)?e:SO(e,o)}function wO(e,o){return ye(e)||ye(o)}function TO(e,o){let a=qo(e),u=qo(o);return wO(a,u)?Cr([a,u]):Sx(a,u)}function wx(e,o,a=[]){return yt(o,(u,m)=>wx(e,m,[...a,TO(u,e)]),()=>v(a.length,0)?[e]:a)}function Tx(e,o,a=[]){return yt(e,(u,m)=>Tx(m,o,[...a,...Bu([u],o)]),()=>a)}function Bu(e,o=[]){return yt(e,(a,u)=>ye(a)?Bu(u,Tx(a.anyOf,o)):Bu(u,wx(a,o)),()=>o)}function RO(e,o){let a=$n({},e,o);return Io(a)?[]:[e]}function Rx(e,o,a=[]){return yt(e,(u,m)=>Rx(m,o,[...a,...RO(u,o)]),()=>a)}function Sm(e,o){let a=qo(e),u=ye(a)?a.anyOf:[a],m=Rx(u,o);return xo(m)}function ms(e,o,a){let u=Cr([e,o]),m=Sm(a,e);return xo([u,m])}function zn(e,o=[]){return yt(e,(a,u)=>zn(u,[...o,i(a)]),()=>xo(o))}function Cr(e){let o=Bu(e),a=ld(o);return xo(a)}function qn(e){let o=Du(e);return qo(o)}function xo(e){let o=ld(e);return wi(o)}function qo(e){return jr(e)?ms(e.if,e.then,e.else):Xr(e)?zn(e.enum):Ke(e)?Cr(e.allOf):mr(e)?qn(e.pattern):ye(e)?xo(e.anyOf):e}function wi(e){return v(e.length,1)?e[0]:v(e.length,0)?nr():g(e)}function kx(e,o){let a=zn(e);return Ti(a,o)}function Ax(e,o){return yo(Ri,o)}function Px(e,o){let a=Cr(e);return Ti(a,o)}function $x(e,o){return ht(e)||Dt(e)?l({[e]:o}):v(e,!1)?l({false:o}):v(e,!0)?l({true:o}):l({})}function Cx(e,o){return yo(Ba,o)}function vx(e,o){return me(e,"pattern")&&(ht(e.pattern)||e.pattern instanceof RegExp)?yo(e.pattern.toString(),o):yo(us,o)}function Mx(e,o){let a=qu(e);return Im(a)?Ti(qn(e),o):yo(e,o)}function kO(e){return ye(e)?fa(e.anyOf):[e]}function fa(e,o=[]){return yt(e,(a,u)=>fa(u,[...o,...kO(a)]),()=>o)}function AO(e){return e.some((o)=>Yr(o)||$r(o)||hn(o))}function PO(e,o){return v(AO(e),!0)?yo(us,o):void 0}function $O(e,o){return e.reduce((a,u)=>gt(u)&&(ht(u.const)||Dt(u.const))?{...a,[u.const]:o}:a,{})}function CO(e,o){let a=$O(e,o);return l(a)}function Ox(e,o){let a=fa(e),u=PO(a,o);return Or(u)?u:CO(a,o)}function Ti(e,o){return _r(e)?px(o):Wn(e)?lx(o):Xr(e)?kx(e.enum,o):hn(e)?Ax(e,o):Ke(e)?Px(e.allOf,o):gt(e)?$x(e.const,o):$r(e)?Cx(e,o):ye(e)?Ox(e.anyOf,o):Yr(e)?vx(e,o):mr(e)?Mx(e.pattern,o):l({})}function dd(e,o,a){return pt([e])?Tt(Ti(e,o),{},a):wm(e,o,a)}function _x(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return dd(p,f,m)}var Ri=`^${dm}$`,Ba=`^${ym}$`,us=`^${xm}$`;function wm(e,o,a={}){return we("Record",[e,o],a)}function at(e,o,a={}){return dd(e,o,a)}function Lx(e,o){return yo(e,o)}function Tm(e){return v(e,us)?s():v(e,Ri)?x():v(e,Ba)?re():ad(e)}function gn(e){return xe(e.patternProperties)[0]}function ki(e){let o=gn(e);return Tm(o)}function dr(e){return e.patternProperties[gn(e)]}function tr(e){return Se(e,"Record")}function ha(e){return _t({"~kind":"Rest"},{type:"rest",items:e},{})}function Ai(e){return Se(e,"Rest")}function Rm(e){return _t({["~kind"]:"This"},{$ref:"#"},e)}function km(e){return Se(e,"This")}function Ga(e){return _t({"~kind":"Undefined"},{type:"undefined"},e)}function ps(e){return Se(e,"Undefined")}function Am(e){return _t({"~kind":"Void"},{type:"void"},e)}function To(e){return Se(e,"Void")}function MO(e,o){return v(e,"Array")?F(o[0]):v(e,"Capitalize")?$m(o[0]):v(e,"ConstructorParameters")?_m(o[0]):v(e,"Evaluate")?YE(o[0]):v(e,"Exclude")?Lm(o[0],o[1]):v(e,"Extract")?Nm(o[0],o[1]):v(e,"Index")?Wu(o[0],o[1]):v(e,"InstanceType")?qm(o[0]):v(e,"Lowercase")?Cm(o[0]):v(e,"NonNullable")?Dm(o[0]):v(e,"Omit")?Fm(o[0],o[1]):v(e,"Parameters")?jm(o[0]):v(e,"Partial")?Um(o[0]):v(e,"Pick")?Bm(o[0],o[1]):v(e,"Readonly")?Gm(o[0]):v(e,"KeyOf")?zu(o[0]):v(e,"Record")?wm(o[0],o[1]):v(e,"Required")?Km(o[0]):v(e,"ReturnType")?Hm(o[0]):v(e,"Uncapitalize")?vm(o[0]):v(e,"Uppercase")?Mm(o[0]):Hu(en(e),o)}function ga(){throw Error("Unreachable")}function jx(e,o=[]){return yt(e,(a,u)=>jx(u,[...o,a[1]]),()=>o)}function Xs(e){return v(e.length,3)?[e[0],...jx(e[1])]:[]}function Ux(e){return da(e[0],e[2],e[4])}function Bx(e){return da(e[0],e[2],e[2])}function Gx(e){return da(e[0],Y(),e[2])}function Kx(e){return da(e,Y(),Y())}function Hx(e){return e}function Wx(e){return Xs(e)}function zx(e){return e[1]}function Vx(e){return Xs(e)}function Jx(e){return e[1]}function Qx(e){return MO(e[0],e[1])}function Xx(e){return null}function Yx(e){return s()}function Zx(e){return re()}function eI(e){return N()}function tI(e){return Ga()}function rI(e){return Nn()}function nI(e){return x()}function oI(e){return Lu()}function sI(e){return Y()}function iI(e){return qa()}function aI(e){return l({})}function uI(e){return nr()}function cI(e){return ja()}function mI(e){return Am()}function pI(e){return Rm()}function lI(e){return i(BigInt(e))}function dI(e){return i(v(e,"true"))}function fI(e){return i(parseFloat(e))}function hI(e){return i(e)}function gI(e){return e[1]}function yI(e){return i(e)}function xI(e){return v(e.length,3)?[e[0],e[1],...e[2]]:[e[0]]}function II(e){return e[1]}function EI(e){return Pm(e)}function bI(e){return v(e.length,6)?ua(e[1],e[3],e[5]):ua(e[1],e[3],Y())}function SI(e){return e.length>0}function wI(e){return e.reduce((o,a)=>v(a.length,3)?[...o,[a[1]]]:[...o,[]],[])}function TI(e){return v(e.length,6)?[e[1],e[3],e[5]]:[]}function RI(e){return $e(e)&&v(e.length,3)?e[1]:e}function kI(e){return v(e.length,2)?e[1]:[]}function Nx(e,o){return o.reduce((a,u)=>{let m=u;return v(m.length,1)?Wu(a,m[0]):v(m.length,0)?F(a):ga()},e)}function qx(e,o){return v(o.length,3)?Om(e,o[0],o[1],o[2]):e}function OO(e,o){return $e(o)&&v(o.length,0)?e:Wm(e,o)}function AI(e){let[o,a,u,m,p]=e;return OO(o?qx(zu(Nx(a,u)),m):qx(Nx(a,u),m),p)}function fd(e,o){return v(o.length,3)?(()=>{let[a,u,m]=o,p=fd(u,m);if(v(a,"&"))return Ke(p)?Ln([e,...p.allOf]):Ln([e,p]);if(v(a,"|"))return ye(p)?g([e,...p.anyOf]):g([e,p]);ga()})():e}function PI(e){return e}function $I(e){let[o,a]=e;return fd(o,a)}function CI(e){return e}function vI(e){let[o,a]=e;return fd(o,a)}function MI(e){return XE(e[1])}function OI(e){return e[1]}function _I(e){return bi(e[0],e[2])}function LI(e){return v(e.length,4)?_u(e[1],e[3]):v(e.length,2)?_u(e[1],Y()):ga()}function NI(e){return e}function qI(e){return`${e}`}function DI(e){return e}function FI(e){return e}function jI(e){return hn(e[3])?Ri:$r(e[3])?Ba:Fs(e[3])?us:Yr(e[3])?us:ga()}function UI(e){return e}function BI(e){return e.length>0}function GI(e){return e.length>0}function KI(e){let[o,a,u,m,p]=e;return{[a]:o&&u?qs(Ls(p)):o&&!u?qs(p):!o&&u?Ls(p):p}}function HI(e){return e}function WI(e){return Xs(e)}function zI(e){return e.reduce((o,a)=>me(a,Ri)||me(a,Ba)||me(a,us)?[o[0],fn(o[1],a)]:[fn(o[0],a),o[1]],[{},{}])}function VI(e){return zI(e[1])}function JI(e){let[o,a]=e,u=v(xe(a).length,0)?{}:{patternProperties:a};return l(o,u)}function QI(e){return v(e.length,5)?qs(Ls(e[4])):v(e.length,3)?e[2]:v(e.length,4)?v(e[2],"readonly")?qs(e[3]):Ls(e[3]):ga()}function XI(e){if(!$e(e)||!v(e.length,3))return e;let[o,a,u]=e;return o&&u?qs(Ls(a)):o&&!u?qs(a):!o&&u?Ls(a):a}function YI(e){return v(e.length,2)?ha(e[1]):v(e.length,1)?e[0]:ga()}function ZI(e){return Xs(e)}function eE(e){return Br(e[1])}function tE(e){return qs(Ls(e[4]))}function rE(e){return qs(e[3])}function nE(e){return Ls(e[3])}function oE(e){return e[2]}function sE(e){return e}function iE(e){return v(e.length,2)?ha(e[1]):v(e.length,1)?e[0]:ga()}function aE(e){return Xs(e)}function uE(e){return Os(e[1],e[4])}function cE(e){return Ms(e[2],e[5])}function Dx(e,o){return v(e,"remove")?hx(o):v(e,"add")?qs(o):o}function mE(e){return v(e.length,2)&&v(e[0],"-")?"remove":v(e.length,2)&&v(e[0],"+")?"add":v(e.length,1)?"add":"none"}function Fx(e,o){return v(e,"remove")?xx(o):v(e,"add")?Ls(o):o}function pE(e){return v(e.length,2)&&v(e[0],"-")?"remove":v(e.length,2)&&v(e[0],"+")?"add":v(e.length,1)?"add":"none"}function lE(e){return v(e.length,2)?[e[1]]:[]}function dE(e){return $e(e[6])&&v(e[6].length,1)?Gu(Nu(e[3]),e[5],e[6][0],Dx(e[1],Fx(e[8],e[10]))):Gu(Nu(e[3]),e[5],en(e[3]),Dx(e[1],Fx(e[8],e[10])))}function fE(e){return en(e)}function hE(e){return BigInt(e)}function gE(e){return parseFloat(e)}function yE(e){return v(e,"true")}function xE(e){return e}function IE(e){return null}function EE(e){return}function bE(e){return{[e[0]]:e[2]}}function SE(e){return Xs(e)}function _O(e){return e.reduce((o,a)=>fn(o,a),{})}function wE(e){return _O(e[1])}function TE(e){return Xs(e)}function RE(e){return e[1]}function kE(e){return e}function AE(e){return Lu()}function PE(e){return s()}function $E(e){return re()}function CE(e){return x()}function vE(e){return nr()}function ME(e){return i(e)}function OE(e){return e}function _E(e){return g(e[1])}function LE(e){return e.length===3?[...e[0],...e[2]]:e.length===1?[...e[0]]:[]}function NE(e){return[e[0],...e[1]]}function qE(e){return e}function DE(e){return e[1]}function FE(e){return Xs(e)}function jE(e){return v(e.length,2)?e[1]:[]}function UE(e){let o=e[2],a=e[3],[u,m]=e[4],p=v(xe(m).length,0)?{}:{patternProperties:m};return{[e[1]]:bi(o,Ku(a,u,p))}}function BE(e){let o=e[2],[a,u]=e[3],m=v(xe(u).length,0)?{}:{patternProperties:u};return{[e[1]]:Ku(o,a,m)}}function GE(e){return{[e[1]]:bi(e[2],e[4])}}function KE(e){return{[e[1]]:e[3]}}function HE(e){return null}function WE(e){return e}function zE(e){return Xs(e)}function VE(e){return e[1]}function JE(e){let[o,a]=[e[0],e[1]];return ZE(fn(o,zI(a)[0]))}function QE(e){return e}function Vu(e){return v(e.length,2)}function Pt(e,o,a){return Vu(e)?o(e[0],e[1]):a()}function qO(e,o){return v(o.indexOf(e),0)?[e,o.slice(e.length)]:[]}function Nr(e,o){for(let a=0;a<e.length;a++){let u=qO(e[a],o);if(Vu(u))return u}return[]}function hd(e,o){return Array.from({length:o-e+1},(a,u)=>String.fromCharCode(e+u))}var eb=[...hd(97,122),...hd(65,90)],gd="0",yd=hd(49,57),Ka=[gd,...yd],tb=" ",Ha=`
15
+ `;var Pi="_",zm=".",rb="$",Vm="-";var nb="//",ob="/*",FO="*/";function sb(e){let o=e.indexOf(FO);return v(o,-1)?"":e.slice(o+2)}function ib(e){let o=e.indexOf(Ha);return v(o,-1)?"":e.slice(o)}function jO(e){return e.replace(/^[ \t\r\f\v]+/,"")}function Jm(e){let o=jO(e);return o.startsWith(ob)?Jm(sb(o.slice(2))):o.startsWith(nb)?Jm(ib(o.slice(2))):o}function Rn(e){let o=e.trimStart();return o.startsWith(ob)?Rn(sb(o.slice(2))):o.startsWith(nb)?Rn(ib(o.slice(2))):o}function Qm(e,o){return Pt(Nr([e],o),(a,u)=>[a,u],()=>["",o])}function UO(e,o){return e.includes(o)}function Wa(e,o,a,u=""){return Pt(Nr(e,a),(m,p)=>UO(o,m)?Wa(e,o,p,u):Wa(e,o,p,`${u}${m}`),()=>[u,a])}function BO(e){return Nr(yd,e)}var GO=[...Ka,Pi];function KO(e){return Wa(GO,[Pi],e)}function HO(e){return Pt(Nr([gd],e),(o,a)=>[o,a],()=>Pt(BO(e),(o,a)=>Pt(KO(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[]))}function Xm(e){return HO(Rn(e))}function WO(e){return Qm(Vm,e)}function zO(e){return Pt(WO(e),(o,a)=>Pt(Xm(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function ab(e){return zO(Rn(e))}function VO(e){return Pt(ab(e),(o,a)=>Pt(Nr(["n"],a),(u,m)=>[`${o}`,m],()=>[]),()=>[])}function xd(e){return VO(e)}function Id(e,o){return Nr([e],o)}function U(e,o){return v(e,"")?["",o]:e.startsWith(Ha)?Id(e,Jm(o)):e.startsWith(tb)?Id(e,o):Id(e,Rn(o))}var ub=[...eb,Pi,rb];function JO(e){return Nr(ub,e)}var QO=[...ub,...Ka];function cb(e,o=""){return Pt(Nr(QO,e),(a,u)=>cb(u,`${o}${a}`),()=>[o,e])}function XO(e){return Pt(JO(e),(o,a)=>Pt(cb(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function Gr(e){return XO(Rn(e))}var YO=[...Ka,Pi];function ZO(e){return Vu(Nr([zm],e))}function mb(e){return Pt(Wa(YO,[Pi],e),(o,a)=>v(o,"")?[]:[o,a],()=>[])}function e_(e){return Pt(Nr([zm],e),(o,a)=>Pt(mb(a),(u,m)=>[`0${o}${u}`,m],()=>[]),()=>[])}function t_(e){return Pt(Xm(e),(o,a)=>Pt(Nr([zm],a),(u,m)=>Pt(mb(m),(p,f)=>[`${o}${u}${p}`,f],()=>[`${o}`,m]),()=>[`${o}`,a]),()=>[])}function r_(e){return ZO(e)?e_(e):t_(e)}function pb(e){return r_(Rn(e))}function n_(e){return Qm(Vm,e)}function o_(e){return Pt(n_(e),(o,a)=>Pt(pb(a),(u,m)=>[`${o}${u}`,m],()=>[]),()=>[])}function Ym(e){return o_(Rn(e))}function s_(e){return v(e,"")?[]:[e.slice(0,1),e.slice(1)]}function lb(e,o){return yt(e,(a,u)=>o.startsWith(a)?!0:lb(u,o),()=>!1)}function Ci(e,o,a=""){return Pt(s_(o),(u,m)=>lb(e,o)?[a,o]:Ci(e,m,`${a}${u}`),()=>[])}function i_(e,o,a){return Pt(Nr([e],a),(u,m)=>Pt(Ci([o],m),(p,f)=>Pt(Nr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function a_(e,o,a){return Pt(Nr([e],a),(u,m)=>Pt(Ci([Ha,o],m),(p,f)=>Pt(Nr([o],f),(h,I)=>[`${p}`,I],()=>[]),()=>[]),()=>[])}function db(e,o,a,u){return a?i_(e,o,Rn(u)):a_(e,o,Rn(u))}function u_(e,o){return Nr(e,o)}function c_(e,o){return db(e,e,!1,o)}function m_(e,o){return Pt(u_(e,o),(a,u)=>c_(a,`${a}${u}`),()=>[])}function Zm(e,o){return m_(e,Rn(o))}function fb(e,o){return Pt(Ci(e,o),(a,u)=>v(a,"")?[]:[a,u],()=>[])}var w=(e,o,a=()=>[])=>e.length===2?o(e):a(),l_=(e)=>w(w(Gr(e),([o,a])=>w(U("extends",a),([u,m])=>w(Lt(m),([p,f])=>w(U("=",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[Ux(o),a]),d_=(e)=>w(w(Gr(e),([o,a])=>w(U("extends",a),([u,m])=>w(Lt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Bx(o),a]),f_=(e)=>w(w(Gr(e),([o,a])=>w(U("=",a),([u,m])=>w(Lt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Gx(o),a]),h_=(e)=>w(Gr(e),([o,a])=>[Kx(o),a]),yb=(e)=>w(w(l_(e),([o,a])=>[o,a],()=>w(d_(e),([o,a])=>[o,a],()=>w(f_(e),([o,a])=>[o,a],()=>w(h_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[Hx(o),a]),xb=(e,o=[])=>w(w(U(",",e),([a,u])=>w(yb(u),([m,p])=>[[a,m],p])),([a,u])=>xb(u,[...o,a]),()=>[o,e]),g_=(e)=>w(w(w(yb(e),([o,a])=>w(xb(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Wx(o),a]),Sd=(e)=>w(w(U("<",e),([o,a])=>w(g_(a),([u,m])=>w(U(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[zx(o),a]),Ib=(e,o=[])=>w(w(U(",",e),([a,u])=>w(Lt(u),([m,p])=>[[a,m],p])),([a,u])=>Ib(u,[...o,a]),()=>[o,e]),y_=(e)=>w(w(w(Lt(e),([o,a])=>w(Ib(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Vx(o),a]),x_=(e)=>w(w(U("<",e),([o,a])=>w(y_(a),([u,m])=>w(U(">",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[Jx(o),a]),I_=(e)=>w(w(Gr(e),([o,a])=>w(x_(a),([u,m])=>[[o,u],m])),([o,a])=>[Qx(o),a]),Eb=(e)=>w(w(w(U(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[Xx(o),a]),bb=(e)=>w(U("string",e),([o,a])=>[Yx(o),a]),Sb=(e)=>w(U("number",e),([o,a])=>[Zx(o),a]),E_=(e)=>w(U("boolean",e),([o,a])=>[eI(o),a]),b_=(e)=>w(U("undefined",e),([o,a])=>[tI(o),a]),S_=(e)=>w(U("null",e),([o,a])=>[rI(o),a]),wb=(e)=>w(U("integer",e),([o,a])=>[nI(o),a]),w_=(e)=>w(U("bigint",e),([o,a])=>[oI(o),a]),T_=(e)=>w(U("unknown",e),([o,a])=>[sI(o),a]),R_=(e)=>w(U("any",e),([o,a])=>[iI(o),a]),k_=(e)=>w(U("object",e),([o,a])=>[aI(o),a]),A_=(e)=>w(U("never",e),([o,a])=>[uI(o),a]),Tb=(e)=>w(U("symbol",e),([o,a])=>[cI(o),a]),P_=(e)=>w(U("void",e),([o,a])=>[mI(o),a]),$_=(e)=>w(U("this",e),([o,a])=>[pI(o),a]),C_=(e)=>w(w(U("${",e),([o,a])=>w(Lt(a),([u,m])=>w(U("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[gI(o),a]),Ed=(e)=>w(Ci(["${","`"],e),([o,a])=>[yI(o),a]),Rb=(e)=>w(w(w(Ed(e),([o,a])=>w(C_(a),([u,m])=>w(Rb(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(Ed(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(Ed(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[xI(o),a]),wd=(e)=>w(w(U("`",e),([o,a])=>w(Rb(a),([u,m])=>w(U("`",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[II(o),a]),v_=(e)=>w(wd(e),([o,a])=>[EI(o),a]),M_=(e)=>w(w(w(U("if",e),([o,a])=>w(Lt(a),([u,m])=>w(U("then",m),([p,f])=>w(Lt(f),([h,I])=>w(U("else",I),([E,S])=>w(Lt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w(w(U("if",e),([o,a])=>w(Lt(a),([u,m])=>w(U("then",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>[])),([o,a])=>[bI(o),a]),O_=(e)=>w(xd(e),([o,a])=>[lI(o),a]),__=(e)=>w(w(U("true",e),([o,a])=>[o,a],()=>w(U("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[dI(o),a]),L_=(e)=>w(Ym(e),([o,a])=>[fI(o),a]),N_=(e)=>w(Zm(["'",'"'],e),([o,a])=>[hI(o),a]),q_=(e)=>w(w(w(U("keyof",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[SI(o),a]),kb=(e,o=[])=>w(w(w(U("[",e),([a,u])=>w(Lt(u),([m,p])=>w(U("]",p),([f,h])=>[[a,m,f],h]))),([a,u])=>[a,u],()=>w(w(U("[",e),([a,u])=>w(U("]",u),([m,p])=>[[a,m],p])),([a,u])=>[a,u],()=>[])),([a,u])=>kb(u,[...o,a]),()=>[o,e]),D_=(e)=>w(kb(e),([o,a])=>[wI(o),a]),F_=(e)=>w(w(w(U("extends",e),([o,a])=>w(Lt(a),([u,m])=>w(U("?",m),([p,f])=>w(Lt(f),([h,I])=>w(U(":",I),([E,S])=>w(Lt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[TI(o),a]),j_=(e)=>w(w(w(U("(",e),([o,a])=>w(Lt(a),([u,m])=>w(U(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(bb(e),([o,a])=>[o,a],()=>w(Sb(e),([o,a])=>[o,a],()=>w(E_(e),([o,a])=>[o,a],()=>w(b_(e),([o,a])=>[o,a],()=>w(S_(e),([o,a])=>[o,a],()=>w(wb(e),([o,a])=>[o,a],()=>w(w_(e),([o,a])=>[o,a],()=>w(T_(e),([o,a])=>[o,a],()=>w(R_(e),([o,a])=>[o,a],()=>w(k_(e),([o,a])=>[o,a],()=>w(A_(e),([o,a])=>[o,a],()=>w(Tb(e),([o,a])=>[o,a],()=>w(P_(e),([o,a])=>[o,a],()=>w($_(e),([o,a])=>[o,a],()=>w(O_(e),([o,a])=>[o,a],()=>w(__(e),([o,a])=>[o,a],()=>w(L_(e),([o,a])=>[o,a],()=>w(N_(e),([o,a])=>[o,a],()=>w(v_(e),([o,a])=>[o,a],()=>w(M_(e),([o,a])=>[o,a],()=>w(X_(e),([o,a])=>[o,a],()=>w(eL(e),([o,a])=>[o,a],()=>w(iL(e),([o,a])=>[o,a],()=>w(sL(e),([o,a])=>[o,a],()=>w(mL(e),([o,a])=>[o,a],()=>w(I_(e),([o,a])=>[o,a],()=>w(pL(e),([o,a])=>[o,a],()=>[])))))))))))))))))))))))))))),([o,a])=>[RI(o),a]),U_=(e)=>w(w(w(U("with",e),([o,a])=>w(Gb(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[kI(o),a]),Ab=(e)=>w(w(q_(e),([o,a])=>w(j_(a),([u,m])=>w(D_(m),([p,f])=>w(F_(f),([h,I])=>w(U_(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[AI(o),a]),Pb=(e)=>w(w(w(U("&",e),([o,a])=>w(Ab(a),([u,m])=>w(Pb(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[PI(o),a]),$b=(e)=>w(w(Ab(e),([o,a])=>w(Pb(a),([u,m])=>[[o,u],m])),([o,a])=>[$I(o),a]),Cb=(e)=>w(w(w(U("|",e),([o,a])=>w($b(a),([u,m])=>w(Cb(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[CI(o),a]),ep=(e)=>w(w($b(e),([o,a])=>w(Cb(a),([u,m])=>[[o,u],m])),([o,a])=>[vI(o),a]),B_=(e)=>w(w(U("readonly",e),([o,a])=>w(ep(a),([u,m])=>[[o,u],m])),([o,a])=>[MI(o),a]),G_=(e)=>w(w(U("|",e),([o,a])=>w(ep(a),([u,m])=>[[o,u],m])),([o,a])=>[OI(o),a]),K_=(e)=>w(w(Sd(e),([o,a])=>w(U("=",a),([u,m])=>w(Lt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[_I(o),a]),H_=(e)=>w(w(w(U("infer",e),([o,a])=>w(Gr(a),([u,m])=>w(U("extends",m),([p,f])=>w(ep(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(U("infer",e),([o,a])=>w(Gr(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>[])),([o,a])=>[LI(o),a]),Lt=(e)=>w(w(H_(e),([o,a])=>[o,a],()=>w(G_(e),([o,a])=>[o,a],()=>w(B_(e),([o,a])=>[o,a],()=>w(ep(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[NI(o),a]),W_=(e)=>w(Ym(e),([o,a])=>[qI(o),a]),z_=(e)=>w(Gr(e),([o,a])=>[DI(o),a]),V_=(e)=>w(Zm(["'",'"'],e),([o,a])=>[FI(o),a]),J_=(e)=>w(w(U("[",e),([o,a])=>w(Gr(a),([u,m])=>w(U(":",m),([p,f])=>w(w(wb(f),([h,I])=>[h,I],()=>w(Sb(f),([h,I])=>[h,I],()=>w(bb(f),([h,I])=>[h,I],()=>w(Tb(f),([h,I])=>[h,I],()=>[])))),([h,I])=>w(U("]",I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[jI(o),a]),vb=(e)=>w(w(W_(e),([o,a])=>[o,a],()=>w(z_(e),([o,a])=>[o,a],()=>w(V_(e),([o,a])=>[o,a],()=>w(J_(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[UI(o),a]),Mb=(e)=>w(w(w(U("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[BI(o),a]),Ob=(e)=>w(w(w(U("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[GI(o),a]),_b=(e)=>w(w(Mb(e),([o,a])=>w(vb(a),([u,m])=>w(Ob(m),([p,f])=>w(U(":",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[KI(o),a]),tp=(e)=>w(w(w(U(",",e),([o,a])=>w(U(`
16
+ `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U(";",e),([o,a])=>w(U(`
17
+ `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U(",",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(U(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(U(`
18
+ `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))))),([o,a])=>[HI(o),a]),Lb=(e,o=[])=>w(w(tp(e),([a,u])=>w(_b(u),([m,p])=>[[a,m],p])),([a,u])=>Lb(u,[...o,a]),()=>[o,e]),Q_=(e)=>w(w(w(_b(e),([o,a])=>w(Lb(a),([u,m])=>w(w(tp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[WI(o),a]),Td=(e)=>w(w(U("{",e),([o,a])=>w(Q_(a),([u,m])=>w(U("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[VI(o),a]),X_=(e)=>w(Td(e),([o,a])=>[JI(o),a]),Y_=(e)=>w(w(w(Gr(e),([o,a])=>w(U("?",a),([u,m])=>w(U(":",m),([p,f])=>w(U("readonly",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[o,a],()=>w(w(Gr(e),([o,a])=>w(U(":",a),([u,m])=>w(U("readonly",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Gr(e),([o,a])=>w(U("?",a),([u,m])=>w(U(":",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[o,a],()=>w(w(Gr(e),([o,a])=>w(U(":",a),([u,m])=>w(Lt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])))),([o,a])=>[QI(o),a]),hb=(e)=>w(w(Y_(e),([o,a])=>[o,a],()=>w(w(Mb(e),([o,a])=>w(Lt(a),([u,m])=>w(Ob(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>[])),([o,a])=>[XI(o),a]),Nb=(e)=>w(w(w(U("...",e),([o,a])=>w(hb(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(hb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[YI(o),a]),qb=(e,o=[])=>w(w(U(",",e),([a,u])=>w(Nb(u),([m,p])=>[[a,m],p])),([a,u])=>qb(u,[...o,a]),()=>[o,e]),Z_=(e)=>w(w(w(Nb(e),([o,a])=>w(qb(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[ZI(o),a]),eL=(e)=>w(w(U("[",e),([o,a])=>w(Z_(a),([u,m])=>w(U("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[eE(o),a]),tL=(e)=>w(w(Gr(e),([o,a])=>w(U("?",a),([u,m])=>w(U(":",m),([p,f])=>w(U("readonly",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[tE(o),a]),rL=(e)=>w(w(Gr(e),([o,a])=>w(U(":",a),([u,m])=>w(U("readonly",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[rE(o),a]),nL=(e)=>w(w(Gr(e),([o,a])=>w(U("?",a),([u,m])=>w(U(":",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[nE(o),a]),oL=(e)=>w(w(Gr(e),([o,a])=>w(U(":",a),([u,m])=>w(Lt(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[oE(o),a]),gb=(e)=>w(w(tL(e),([o,a])=>[o,a],()=>w(rL(e),([o,a])=>[o,a],()=>w(nL(e),([o,a])=>[o,a],()=>w(oL(e),([o,a])=>[o,a],()=>[])))),([o,a])=>[sE(o),a]),Db=(e)=>w(w(w(U("...",e),([o,a])=>w(gb(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(gb(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[])),([o,a])=>[iE(o),a]),Fb=(e,o=[])=>w(w(U(",",e),([a,u])=>w(Db(u),([m,p])=>[[a,m],p])),([a,u])=>Fb(u,[...o,a]),()=>[o,e]),jb=(e)=>w(w(w(Db(e),([o,a])=>w(Fb(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[aE(o),a]),sL=(e)=>w(w(U("(",e),([o,a])=>w(jb(a),([u,m])=>w(U(")",m),([p,f])=>w(U("=>",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[uE(o),a]),iL=(e)=>w(w(U("new",e),([o,a])=>w(U("(",a),([u,m])=>w(jb(m),([p,f])=>w(U(")",f),([h,I])=>w(U("=>",I),([E,S])=>w(Lt(S),([R,k])=>[[o,u,p,h,E,R],k])))))),([o,a])=>[cE(o),a]),aL=(e)=>w(w(w(U("+",e),([o,a])=>w(U("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U("-",e),([o,a])=>w(U("readonly",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U("readonly",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[mE(o),a]),uL=(e)=>w(w(w(U("+",e),([o,a])=>w(U("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U("-",e),([o,a])=>w(U("?",a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U("?",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])))),([o,a])=>[pE(o),a]),cL=(e)=>w(w(w(U("as",e),([o,a])=>w(Lt(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[lE(o),a]),mL=(e)=>w(w(U("{",e),([o,a])=>w(aL(a),([u,m])=>w(U("[",m),([p,f])=>w(Gr(f),([h,I])=>w(U("in",I),([E,S])=>w(Lt(S),([R,k])=>w(cL(k),([A,P])=>w(U("]",P),([M,V])=>w(uL(V),([_,J])=>w(U(":",J),([j,X])=>w(Lt(X),([te,L])=>w(Eb(L),([se,he])=>w(U("}",he),([Me,We])=>[[o,u,p,h,E,R,A,M,_,j,te,se,Me],We]))))))))))))),([o,a])=>[dE(o),a]),pL=(e)=>w(Gr(e),([o,a])=>[fE(o),a]),lL=(e)=>w(xd(e),([o,a])=>[hE(o),a]),dL=(e)=>w(Ym(e),([o,a])=>[gE(o),a]),fL=(e)=>w(w(U("true",e),([o,a])=>[o,a],()=>w(U("false",e),([o,a])=>[o,a],()=>[])),([o,a])=>[yE(o),a]),hL=(e)=>w(Zm(['"',"'"],e),([o,a])=>[xE(o),a]),gL=(e)=>w(U("null",e),([o,a])=>[IE(o),a]),yL=(e)=>w(U("undefined",e),([o,a])=>[EE(o),a]),Ub=(e)=>w(w(vb(e),([o,a])=>w(U(":",a),([u,m])=>w(Rd(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[bE(o),a]),Bb=(e,o=[])=>w(w(tp(e),([a,u])=>w(Ub(u),([m,p])=>[[a,m],p])),([a,u])=>Bb(u,[...o,a]),()=>[o,e]),xL=(e)=>w(w(w(Ub(e),([o,a])=>w(Bb(a),([u,m])=>w(w(tp(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[SE(o),a]),Gb=(e)=>w(w(U("{",e),([o,a])=>w(xL(a),([u,m])=>w(U("}",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[wE(o),a]),Kb=(e,o=[])=>w(w(U(",",e),([a,u])=>w(Rd(u),([m,p])=>[[a,m],p])),([a,u])=>Kb(u,[...o,a]),()=>[o,e]),IL=(e)=>w(w(w(Rd(e),([o,a])=>w(Kb(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[TE(o),a]),EL=(e)=>w(w(U("[",e),([o,a])=>w(IL(a),([u,m])=>w(U("]",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[RE(o),a]),Rd=(e)=>w(w(lL(e),([o,a])=>[o,a],()=>w(dL(e),([o,a])=>[o,a],()=>w(fL(e),([o,a])=>[o,a],()=>w(hL(e),([o,a])=>[o,a],()=>w(gL(e),([o,a])=>[o,a],()=>w(yL(e),([o,a])=>[o,a],()=>w(Gb(e),([o,a])=>[o,a],()=>w(EL(e),([o,a])=>[o,a],()=>[])))))))),([o,a])=>[kE(o),a]),bL=(e)=>w(U("-?(?:0|[1-9][0-9]*)n",e),([o,a])=>[AE(o),a]),SL=(e)=>w(U(".*",e),([o,a])=>[PE(o),a]),wL=(e)=>w(U("-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?",e),([o,a])=>[$E(o),a]),TL=(e)=>w(U("-?(?:0|[1-9][0-9]*)",e),([o,a])=>[CE(o),a]),RL=(e)=>w(U("(?!)",e),([o,a])=>[vE(o),a]),kL=(e)=>w(fb(["-?(?:0|[1-9][0-9]*)n",".*","-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?","-?(?:0|[1-9][0-9]*)","(?!)","(",")","$","|"],e),([o,a])=>[ME(o),a]),AL=(e)=>w(w(bL(e),([o,a])=>[o,a],()=>w(SL(e),([o,a])=>[o,a],()=>w(wL(e),([o,a])=>[o,a],()=>w(TL(e),([o,a])=>[o,a],()=>w(RL(e),([o,a])=>[o,a],()=>w(PL(e),([o,a])=>[o,a],()=>w(kL(e),([o,a])=>[o,a],()=>[]))))))),([o,a])=>[OE(o),a]),PL=(e)=>w(w(U("(",e),([o,a])=>w(kd(a),([u,m])=>w(U(")",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[_E(o),a]),Hb=(e)=>w(w(w(bd(e),([o,a])=>w(U("|",a),([u,m])=>w(Hb(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w(w(bd(e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[]))),([o,a])=>[LE(o),a]),bd=(e)=>w(w(AL(e),([o,a])=>w(kd(a),([u,m])=>[[o,u],m])),([o,a])=>[NE(o),a]),kd=(e)=>w(w(Hb(e),([o,a])=>[o,a],()=>w(bd(e),([o,a])=>[o,a],()=>[])),([o,a])=>[qE(o),a]),ox=(e)=>w(w(U("^",e),([o,a])=>w(kd(a),([u,m])=>w(U("$",m),([p,f])=>[[o,u,p],f]))),([o,a])=>[DE(o),a]),Wb=(e,o=[])=>w(w(U(",",e),([a,u])=>w(Lt(u),([m,p])=>[[a,m],p])),([a,u])=>Wb(u,[...o,a]),()=>[o,e]),$L=(e)=>w(w(w(Lt(e),([o,a])=>w(Wb(a),([u,m])=>w(w(U(",",m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[FE(o),a]),zb=(e)=>w(w(w(U("extends",e),([o,a])=>w($L(a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[jE(o),a]),CL=(e)=>w(w(U("interface",e),([o,a])=>w(Gr(a),([u,m])=>w(Sd(m),([p,f])=>w(zb(f),([h,I])=>w(Td(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[UE(o),a]),vL=(e)=>w(w(U("interface",e),([o,a])=>w(Gr(a),([u,m])=>w(zb(m),([p,f])=>w(Td(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[BE(o),a]),ML=(e)=>w(w(U("type",e),([o,a])=>w(Gr(a),([u,m])=>w(Sd(m),([p,f])=>w(U("=",f),([h,I])=>w(Lt(I),([E,S])=>[[o,u,p,h,E],S]))))),([o,a])=>[GE(o),a]),OL=(e)=>w(w(U("type",e),([o,a])=>w(Gr(a),([u,m])=>w(U("=",m),([p,f])=>w(Lt(f),([h,I])=>[[o,u,p,h],I])))),([o,a])=>[KE(o),a]),_L=(e)=>w(w(w(U("export",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[HE(o),a]),Vb=(e)=>w(w(w(U(";",e),([o,a])=>w(U(`
19
+ `,a),([u,m])=>[[o,u],m])),([o,a])=>[o,a],()=>w(w(U(";",e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>w(w(U(`
20
+ `,e),([o,a])=>[[o],a]),([o,a])=>[o,a],()=>[]))),([o,a])=>[WE(o),a]),Jb=(e,o=[])=>w(w(Vb(e),([a,u])=>w(Ad(u),([m,p])=>[[a,m],p])),([a,u])=>Jb(u,[...o,a]),()=>[o,e]),LL=(e)=>w(w(w(Ad(e),([o,a])=>w(Jb(a),([u,m])=>w(w(Vb(m),([p,f])=>[[p],f],()=>[[],m]),([p,f])=>[[o,u,p],f]))),([o,a])=>[o,a],()=>w([[],e],([o,a])=>[o,a],()=>[])),([o,a])=>[zE(o),a]),Ad=(e)=>w(w(_L(e),([o,a])=>w(w(CL(a),([u,m])=>[u,m],()=>w(vL(a),([u,m])=>[u,m],()=>w(ML(a),([u,m])=>[u,m],()=>w(OL(a),([u,m])=>[u,m],()=>[])))),([u,m])=>w(Eb(m),([p,f])=>[[o,u,p],f]))),([o,a])=>[VE(o),a]),NL=(e)=>w(w(Ad(e),([o,a])=>w(LL(a),([u,m])=>[[o,u],m])),([o,a])=>[JE(o),a]),Qb=(e)=>w(w(NL(e),([o,a])=>[o,a],()=>w(K_(e),([o,a])=>[o,a],()=>w(Lt(e),([o,a])=>[o,a],()=>[]))),([o,a])=>[QE(o),a]);function Xb(e){let o=wd(`\`${e}\``);return v(o.length,2)?o[0]:Ur()}function DL(e){return e.join("|")}function FL(e){return e.slice(1,e.length-1)}function jL(e,o,a){return vi(o,`${a}${e}`)}function UL(e,o){return vi(e,`${o}${Xy}`)}function BL(e,o){return vi(e,`${o}${dm}`)}function GL(e,o){return vi(e,`${o}${ym}`)}function KL(e,o){return Ju(g([i("false"),i("true")]),e,o)}function HL(e,o){return vi(e,`${o}${xm}`)}function WL(e,o,a){return vi(o,`${a}${FL(e)}`)}function zL(e,o,a){let u=Qu(e,{});return Ju(u,o,a)}function VL(e,o,a){let u=zn(e);return Ju(u,o,a)}function Yb(e,o,a,u=[]){return yt(e,(m,p)=>Yb(p,o,a,[...u,Ju(m,[],"")]),()=>vi(o,`${a}(${DL(u)})`))}function Ju(e,o,a){return Xr(e)?VL(e.enum,o,a):hn(e)?BL(o,a):gt(e)?jL(e.const,o,a):wo(e)?UL(o,a):Wn(e)?KL(o,a):$r(e)?GL(o,a):Yr(e)?HL(o,a):mr(e)?WL(e.pattern,o,a):eS(e)?zL(e.parameters[0],o,a):ye(e)?Yb(e.anyOf,o,a):Ry}function vi(e,o){return yt(e,(a,u)=>Ju(a,u,o),()=>o)}function JL(e){return`^${vi(e,"")}$`}function Zb(e){let o=JL(e);return Em(o)}function Qu(e,o){return pt(e)?Tt(Zb(e),{},o):Pm(e,o)}function tS(e,o,a,u){let m=$o(e,o,a);return Qu(m,u)}function Pm(e,o={}){return we("TemplateLiteral",[e],o)}function eS(e){return Or(e)&&me(e,"action")&&v(e.action,"TemplateLiteral")}function rS(e){return Qu(e,{})}function QL(e){let o=Xb(e);return rS(o)}function nS(e,o={}){let a=ht(e)?QL(e):rS(e);return Tt(a,{},o)}function mr(e){return Se(e,"TemplateLiteral")}function Pd(e){return _t({["~kind"]:"ExtendsUnion"},{inferred:e})}function $d(e){return mt(e)&&me(e,"~kind")&&me(e,"inferred")&&v(e["~kind"],"ExtendsUnion")&&mt(e.inferred)}function Ee(e){return _t({["~kind"]:"ExtendsTrue"},{inferred:e})}function Cd(e){return mt(e)&&me(e,"~kind")&&me(e,"inferred")&&v(e["~kind"],"ExtendsTrue")&&mt(e.inferred)}function nt(){return _t({["~kind"]:"ExtendsFalse"},{})}function vd(e){return mt(e)&&me(e,"~kind")&&v(e["~kind"],"ExtendsFalse")}function Io(e){return $d(e)||Cd(e)}function br(e,o,a){return Io(e)?o(e.inferred):a()}function XL(e,o,a,u){return br($t(e,a,u),(m)=>Ee(fn(fn(e,m),{[o]:a})),()=>nt())}function YL(e,o){return Ee(e)}function ZL(e,o,a,u,m){return br($t(e,o,a),(p)=>br($t(p,o,u),(f)=>Ee(f),()=>nt()),()=>br($t(e,o,m),(p)=>Ee(p),()=>nt()))}function eN(e,o,a){let u=zn(a);return $t(e,o,u)}function oS(e,o,a){return yt(a,(u,m)=>br($t(e,o,u),(p)=>oS(p,o,m),()=>nt()),()=>Ee(e))}function tN(e,o,a){let u=qn(a);return $t(e,o,u)}function sS(e,o,a){return yt(a,(u,m)=>br($t(e,o,u),(p)=>Ee(p),()=>sS(e,o,m)),()=>nt())}function Bt(e,o,a){return _r(a)?YL(e,o):jr(a)?ZL(e,o,a.if,a.then,a.else):Xr(a)?eN(e,o,a.enum):Qr(a)?XL(e,a.name,o,a.extends):Ke(a)?oS(e,o,a.allOf):mr(a)?tN(e,o,a.pattern):ye(a)?sS(e,o,a.anyOf):Jr(a)?Ee(e):nt()}function iS(e,o,a){return Qr(a)?Bt(e,o,a):_r(a)?Ee(e):Jr(a)?Ee(e):Pd(e)}function rN(e,o){let a=ma(e),u=ma(o);return a&&u?!0:!a&&u?!0:a&&!u?!1:!0}function aS(e,o,a,u){return At(u)?rN(o,u)?$t(e,a,u.items):nt():Bt(e,o,u)}function uS(e,o,a){return wo(a)?Ee(e):Bt(e,o,a)}function cS(e,o,a){return Wn(a)?Ee(e):Bt(e,o,a)}function nN(e,o,a,u,m){let p=Qr(u)?o:u,f=Qr(u)?u:o,h=tn(o),I=tn(u);return!h&&I?nt():br($t(e,p,f),(E)=>Xu(E,a,m),()=>nt())}function oN(e,o,a,u){return yt(u,(m,p)=>nN(e,o,a,m,p),()=>tn(o)?Ee(e):nt())}function sN(e,o,a){return yt(o,(u,m)=>oN(e,u,m,a),()=>Ee(e))}function Xu(e,o,a){return sN(e,o,a)}function rp(e,o,a){return To(a)?Ee(e):$t(e,o,a)}function mS(e,o,a,u){return _r(u)?Ee(e):Jr(u)?Ee(e):zr(u)?br(Xu(e,o,u.parameters),(m)=>rp(m,a,u.instanceType),()=>nt()):nt()}function pS(e,o,a,u,m){return br($t(e,o,m),()=>$t(e,a,m),()=>$t(e,u,m))}function lS(e,o,a){let u=zn(o);return $t(e,u,a)}function dS(e,o,a,u){return _r(u)?Ee(e):Jr(u)?Ee(e):Vr(u)?br(Xu(e,o,u.parameters),(m)=>rp(m,a,u.returnType),()=>nt()):nt()}function fS(e,o,a){return hn(a)?Ee(e):$r(a)?Ee(e):Bt(e,o,a)}function hS(e,o,a){let u=Cr(o);return $t(e,u,a)}function np(e,o,a){return o===a?Ee(e):nt()}function iN(e,o,a){return gt(a)?np(e,o,a.const):wo(a)?Ee(e):Bt(e,i(o),a)}function aN(e,o,a){return gt(a)?np(e,o,a.const):Wn(a)?Ee(e):Bt(e,i(o),a)}function uN(e,o,a){return gt(a)?np(e,o,a.const):$r(a)?Ee(e):Bt(e,i(o),a)}function cN(e,o,a){return gt(a)?np(e,o,a.const):Yr(a)?Ee(e):Bt(e,i(o),a)}function gS(e,o,a){return Fr(o.const)?iN(e,o.const,a):nn(o.const)?aN(e,o.const,a):Dt(o.const)?uN(e,o.const,a):ht(o.const)?cN(e,o.const,a):Ur()}function yS(e,o,a){return Qr(a)?Bt(e,o,a):Ee(e)}function xS(e,o,a){return Ds(a)?Ee(e):Bt(e,o,a)}function IS(e,o,a){return $r(a)?Ee(e):Bt(e,o,a)}function mN(e,o,a){return tn(o)?tn(a)?Ee(e):nt():Ee(e)}function pN(e,o,a){return Qr(a)&&So(a.extends)?nt():br($t(e,o,a),(u)=>mN(u,o,a),()=>nt())}function lN(e,o){return e.reduce((a,u)=>(u in o)?Io(o[u])?{...a,...o[u].inferred}:Ur():Ur(),{})}function dN(e,o,a){let u={};for(let f of xe(a))u[f]=f in o?pN({},o[f],a[f]):tn(a[f])?Qr(a[f])?Ee(fn(e,{[a[f].name]:a[f].extends})):Ee(e):nt();let m=Zl(u).every((f)=>Io(f)),p=m?lN(xe(u),u):{};return m?Ee(p):nt()}function fN(e,o,a){let u=dN(e,o,a);return Io(u)?Ee(fn(e,u.inferred)):nt()}function hN(e,o,a){return fN(e,o,a)}function gN(e,o){return xe(o).reduce((a,u)=>({...a,[u]:me(e,u)?ye(a[u])?g([...a[u].anyOf,o[u]]):g([e[u],o[u]]):o[u]}),e)}function ES(e,o,a,u){return yt(o,(m,p)=>br($t({},e[m],a),(f)=>ES(e,p,a,gN(u,f)),()=>nt()),()=>Ee(u))}function yN(e,o,a,u){let m=xe(o);return ES(o,m,u,e)}function bS(e,o,a){return tr(a)?yN(e,o,gn(a),dr(a)):ze(a)?hN(e,o,a.properties):Bt(e,l(o),a)}function xN(e,o){return v(xe(o).length,0)?Ee(e):nt()}function IN(e,o,a,u,m){return $t(e,a,m)}function SS(e,o,a,u){return tr(u)?IN(e,Tm(o),a,Tm(gn(u)),dr(u)):ze(u)?xN(e,u.properties):_r(u)?Ee(e):Jr(u)?Ee(e):nt()}function wS(e,o,a){return Yr(a)?Ee(e):Bt(e,o,a)}function TS(e,o,a){return Fs(a)?Ee(e):Bt(e,o,a)}function RS(e,o,a){let u=qn(o);return $t(e,u,a)}function Md(e,o){return _t({"~kind":"Inferrable"},{name:e,type:o},{})}function Yu(e){return mt(e)&&me(e,"~kind")&&me(e,"name")&&me(e,"type")&&v(e["~kind"],"Inferrable")&&ht(e.name)&&mt(e.type)}function Od(e){return Ai(e)?Qr(e.items)?At(e.items.extends)?Md(e.items.name,e.items.extends.items):Jr(e.items.extends)?Md(e.items.name,e.items.extends):void 0:Ur():void 0}function op(e){return Qr(e)?Md(e.name,e.extends):void 0}function _d(e,o,a=[]){return yt(e,(u,m)=>br($t({},u,o),()=>_d(m,o,[...a,u]),()=>{return}),()=>a)}function kS(e,o,a,u){let m=_d(a,u);return $e(m)?Ee(fn(e,{[o]:Br(m)})):nt()}function sp(e,o,a,u){let m=_d(a,u);return $e(m)?Ee(fn(e,{[o]:g(m)})):nt()}function EN(e){return[...e].reverse()}function Ld(e,o){return o?EN(e):e}function bN(e){let o=e.length>0?e[0]:void 0,a=Or(o)?Od(o):void 0;return Or(a)}function SN(e,o,a,u,m,p){return br($t(e,a,m),(f)=>AS(f,o,u,p),()=>nt())}function wN(e,o,a,u,m){let p=Od(u);return Yu(p)?kS(e,p.name,Ld(a,o),p.type):yt(a,(f,h)=>SN(e,o,f,h,u,m),()=>nt())}function TN(e,o,a,u){return yt(u,(m,p)=>wN(e,o,a,m,p),()=>v(a.length,0)?Ee(e):nt())}function AS(e,o,a,u){return TN(e,o,a,u)}function RN(e,o,a){let u=Mi(e,fr([],[]),a),m=bN(u);return AS(e,m,Ld(o,m),Ld(u,m))}function PS(e,o,a){let u=op(a);return Yu(u)?sp(e,u.name,o,u.type):yt(o,(m,p)=>br($t(e,m,a),(f)=>PS(f,p,a),()=>nt()),()=>Ee(e))}function $S(e,o,a){let u=Mi(e,fr([],[]),o);return dt(a)?RN(e,u,a.items):At(a)?PS(e,u,a.items):Bt(e,Br(u),a)}function CS(e,o,a){return To(a)?Ee(e):ps(a)?Ee(e):Bt(e,o,a)}function vS(e,o,a){return yt(a,(u,m)=>br($t(e,o,u),(p)=>Ee(p),()=>vS(e,o,m)),()=>nt())}function Nd(e,o,a){return yt(o,(u,m)=>br(vS(e,u,a),(p)=>Nd(p,m,a),()=>nt()),()=>Ee(e))}function MS(e,o,a){let u=op(a);return Yu(u)?sp(e,u.name,o,u.type):ye(a)?Nd(e,o,a.anyOf):Nd(e,o,[a])}function OS(e,o,a){return Qr(a)?Bt(e,o,a):_r(a)?Ee(e):Jr(a)?Ee(e):nt()}function _S(e,o,a){return To(a)?Ee(e):Bt(e,o,a)}function $t(e,o,a){return _r(o)?iS(e,o,a):At(o)?aS(e,o,o.items,a):wo(o)?uS(e,o,a):Wn(o)?cS(e,o,a):zr(o)?mS(e,o.parameters,o.instanceType,a):jr(o)?pS(e,o.if,o.then,o.else,a):Xr(o)?lS(e,o.enum,a):Vr(o)?dS(e,o.parameters,o.returnType,a):hn(o)?fS(e,o,a):Ke(o)?hS(e,o.allOf,a):gt(o)?gS(e,o,a):So(o)?yS(e,o,a):Ds(o)?xS(e,o,a):$r(o)?IS(e,o,a):ze(o)?bS(e,o.properties,a):tr(o)?SS(e,gn(o),dr(o),a):Yr(o)?wS(e,o,a):Fs(o)?TS(e,o,a):mr(o)?RS(e,o.pattern,a):dt(o)?$S(e,o.items,a):ps(o)?CS(e,o,a):ye(o)?MS(e,o.anyOf,a):Jr(o)?OS(e,o,a):To(o)?_S(e,o,a):nt()}function kN(e,o){return Cr([...e,l(o)])}function qd(e,o,a){return pt(e)?Tt(kN(e,o),{},a):Ku(e,o,a)}function LS(e,o,a,u,m){let p=$o(e,o,a),f=Zu(e,o,u);return qd(p,f,m)}function Ku(e,o,a={}){return we("Interface",[e,o],a)}function za(e){return Or(e)&&me(e,"action")&&v(e.action,"Interface")}function NS(e,o,a={}){return qd(e,o,a)}function AN(e,o,a){return e.includes(a)?!0:ec([...e,a],o,o[a])}function qS(e,o,a){let u=am(a);return ya(e,o,u)}function ya(e,o,a){return yt(a,(u,m)=>ec(e,o,u)?!0:ya(e,o,m),()=>!1)}function ec(e,o,a){return Xt(a)?AN(e,o,a.$ref):At(a)?ec(e,o,a.items):zr(a)?ya(e,o,[...a.parameters,a.instanceType]):Vr(a)?ya(e,o,[...a.parameters,a.returnType]):za(a)?qS(e,o,a.parameters[1]):Ke(a)?ya(e,o,a.allOf):ze(a)?qS(e,o,a.properties):ye(a)?ya(e,o,a.anyOf):dt(a)?ya(e,o,a.items):tr(a)?ec(e,o,dr(a)):!1}function DS(e,o,a){return ec(e,o,a)}function PN(e,o){return o.reduce((a,u)=>DS([u],e,e[u])?[...a,u]:a,[])}function FS(e){let o=im(e);return PN(e,o)}function $N(e,o,a){return a.includes(o)?a:(o in e)?tc(e,e[o],[...a,o]):Ur()}function jS(e,o,a){let u=am(o);return Va(e,u,a)}function Va(e,o,a){return o.reduce((u,m)=>tc(e,m,u),a)}function tc(e,o,a){return Xt(o)?$N(e,o.$ref,a):At(o)?tc(e,o.items,a):zr(o)?Va(e,[...o.parameters,o.instanceType],a):Vr(o)?Va(e,[...o.parameters,o.returnType],a):za(o)?jS(e,o.parameters[1],a):Ke(o)?Va(e,o.allOf,a):ze(o)?jS(e,o.properties,a):ye(o)?Va(e,o.anyOf,a):dt(o)?Va(e,o.items,a):tr(o)?tc(e,dr(o),a):a}function US(e,o,a){return tc(e,a,[o])}function CN(e){return qa()}function vN(e){return xe(e).reduce((o,a)=>({...o,[a]:xa(e[a])}),{})}function rc(e){return e.reduce((o,a)=>[...o,xa(a)],[])}function xa(e){return Xt(e)?CN(e.$ref):At(e)?F(xa(e.items),La(e)):zr(e)?Ms(rc(e.parameters),xa(e.instanceType)):Vr(e)?Os(rc(e.parameters),xa(e.returnType)):Ke(e)?Ln(rc(e.allOf)):ze(e)?l(vN(e.properties)):tr(e)?at(ki(e),xa(dr(e))):ye(e)?g(rc(e.anyOf)):dt(e)?Br(rc(e.items)):e}function MN(e,o){return o in e?xa(e[o]):Y()}function BS(e){return MN(e.$defs,e.$ref)}function ON(e,o,a){let u=$o(e,fr([],[]),o),m=Zu({},fr([],[]),a);return Cr([...u,l(m)])}function _N(e,o){return xe(e).filter((u)=>o.includes(u)).reduce((u,m)=>{let p=e[m],f=za(p)?ON(e,p.parameters[0],p.parameters[1]):p;return{...u,[m]:f}},{})}function GS(e,o,a){let u=US(e,o,a),m=_N(e,u);return Ns(m,o)}function KS(e,o){return o in e?Xt(e[o])?KS(e,e[o].$ref):e[o]:nr()}function js(e,o){return KS(e,o)}function HS(e){return ar(e)?BS(e):um(e)?Y():e}function $n(e,o,a){let u=HS(o),m=HS(a);return $t(e,u,m)}var Fu=0,nc=1,ju=2,Uu=3;function Ua(e,o){let a=[$n({},e,o),$n({},o,e)];return Io(a[0])&&Io(a[1])?Fu:Io(a[0])&&vd(a[1])?ju:vd(a[0])&&Io(a[1])?Uu:nc}function Dd(e,o,a=[],u=o){return yt(o,(m,p)=>{let f=Ua(e,m);return v(f,ju)||v(f,Fu)?u:v(f,nc)?Dd(e,p,[...a,m],u):Dd(e,p,a,u)},()=>[...a,e])}function LN(e,o,a){let u=qo(e);return _r(u)?[u]:Jr(u)?[u]:So(u)?ip(o,a):ze(u)?ip(o,[...a,u]):ip(o,Dd(u,a))}function ip(e,o=[]){return yt(e,(a,u)=>LN(a,u,o),()=>o)}function ld(e){let o=ip(e);return fa(o)}function Fd(e,o){return Tt(qo(e),{},o)}function WS(e,o,a,u){let m=pe(e,o,a);return Fd(m,u)}function oc(e,o=[]){return Ei(e)&&v(e.action,"Conditional")?Xt(e.parameters[0])?oc(e.parameters[2],oc(e.parameters[3],[...o,e.parameters[0].$ref])):oc(e.parameters[2],oc(e.parameters[3],o)):Ei(e)&&v(e.action,"Mapped")?Ei(e.parameters[1])&&v(e.parameters[1].action,"KeyOf")&&Xt(e.parameters[1].parameters[0])?[...o,e.parameters[1].parameters[0].$ref]:o:o}function NN(e,o){return e.reduce((a,u)=>[...a,o.includes(u.name)],[])}function JS(e,o,a=[]){return yt(e,(u,m)=>yt(o,(p,f)=>JS(m,f,[...a,[p,u]]),()=>a),()=>a)}function qN(e){return mr(e)?qn(e.pattern):Xr(e)?zn(e.enum):e}function DN(e){let o=qN(e);return ye(o)?[...o.anyOf]:[o]}function FN(e,o){return e.reduce((a,u)=>[...a,[...u,o]],[])}function zS(e,o){return o.reduce((a,u)=>[...a,...FN(e,u)],[])}function VS(e){return e.reduce((o,a)=>v(a[0],!0)?zS(o,DN(a[1])):zS(o,[a[1]]),[[]])}function QS(e,o,a){let u=oc(a),m=NN(e,u),p=JS(o,m);return Ei(a)&&v(a.action,"Conditional")?VS(p):Ei(a)&&v(a.action,"Mapped")?VS(p):[o]}function jN(){return["(not-resolvable)",nr()]}function UN(){return["(not-generic)",nr()]}function BN(e,o,a){return[e,bi(o,a)]}function GN(e,o,a){return o in e?XS(e,o,e[o],a):jN()}function XS(e,o,a,u){return Na(a)?BN(o,a.parameters,a.expression):Xt(a)?GN(e,a.$ref,u):UN()}function YS(e,o,a){return XS(e,"(anonymous)",o,a)}function KN(e,o,a){if(Qr(o)||Ja(o)||Io($n({},o,a)))return;let u={parameter:e,expect:a,actual:o};throw Error(`Argument for parameter ${e} does not satisfy constraint`,{cause:u})}function ZS(e,o,a,u,m){let p=pe(e,o,m);return KN(a,p,u),fn(e,{[a]:p})}function HN(e,o,a,u,m){let p=pe(e,o,a.extends),f=pe(e,o,a.equals);return yt(m,(h,I)=>jd(ZS(e,o,a.name,p,h),o,u,I),()=>jd(ZS(e,o,a.name,p,f),o,u,[]))}function jd(e,o,a,u){return yt(a,(m,p)=>HN(e,o,m,p,u),()=>e)}function ew(e,o,a,u){return jd(e,o,a,u)}var Ud=0,Bd=0;function WN(){if(Pu(Bd,ts().maxInstantiationCount))return;throw Error("Type instantiation is excessively deep and possibly infinite")}function zN(){WN(),Bd++,Ud++}function VN(){if(Ud--,v(Ud,0))Bd=0}function JN(e){return ta(e.callstack.length,0)?e.callstack[e.callstack.length-1]:""}function QN(e,o){return v(JN(e),o)}function XN(e,o,a,u,m,p){zN();try{let f=ew(e,o,u,p),h=pe(f,fr([...o.callstack,a.$ref],o.visited),m);return pe(f,fr([],[]),h)}finally{VN()}}function YN(e,o,a,u,m,p){return p.reduce((f,h)=>{let I=XN(e,o,a,u,m,h);return[...f,I]},[])}function ZN(e,o,a,u,m,p){let f=QS(u,p,m),h=YN(e,o,a,u,m,f);return v(h.length,1)?h[0]:xo(h)}function ap(e,o,a,u){let m=$o(e,o,u),p=YS(e,a,u),f=p[0],h=p[1];return Na(h)?QN(o,f)?Hu(en(f),m):ZN(e,o,en(f),h.parameters,h.expression,m):Hu(a,m)}function Hu(e,o){return _t({["~kind"]:"Call"},{type:"call",target:e,arguments:o},{})}function tw(e,o){return ap({},fr([],[]),e,o)}function Ja(e){return Se(e,"Call")}function eq(e){return ss(e,["~immutable"])}function rw(e,o){return Tt(eq(e),{},o)}function nw(e,o,a,u){let m=pe(e,o,a);return rw(m,u)}function ow(e,o){return e(o)}function sw(e,o){return ht(o)?i(ow(e,o)):i(o)}function iw(e,o){let a=qn(o);return Ys(e,a)}function aw(e,o){let a=o.map((u)=>Ys(e,u));return g(a)}function Ys(e,o){return gt(o)?sw(e,o.const):mr(o)?iw(e,o.pattern):ye(o)?aw(e,o.anyOf):o}function $m(e,o={}){return we("Capitalize",[e],o)}function uw(e,o={}){return Gd(e,o)}function Cm(e,o={}){return we("Lowercase",[e],o)}function cw(e,o={}){return Kd(e,o)}function vm(e,o={}){return we("Uncapitalize",[e],o)}function mw(e,o={}){return Hd(e,o)}function Mm(e,o={}){return we("Uppercase",[e],o)}function pw(e,o={}){return Wd(e,o)}var tq=(e)=>e[0].toUpperCase()+e.slice(1),rq=(e)=>e.toLowerCase(),nq=(e)=>e[0].toLowerCase()+e.slice(1),oq=(e)=>e.toUpperCase();function Gd(e,o){return pt([e])?Tt(Ys(tq,e),{},o):$m(e,o)}function Kd(e,o){return pt([e])?Tt(Ys(rq,e),{},o):Cm(e,o)}function Hd(e,o){return pt([e])?Tt(Ys(nq,e),{},o):vm(e,o)}function Wd(e,o){return pt([e])?Tt(Ys(oq,e),{},o):Mm(e,o)}function lw(e,o,a,u){let m=pe(e,o,a);return Gd(m,u)}function dw(e,o,a,u){let m=pe(e,o,a);return Kd(m,u)}function fw(e,o,a,u){let m=pe(e,o,a);return Hd(m,u)}function hw(e,o,a,u){let m=pe(e,o,a);return Wd(m,u)}function Om(e,o,a,u,m={}){return we("Conditional",[e,o,a,u],m)}function gw(e,o,a,u,m={}){return zd({},fr([],[]),e,o,a,u,m)}function sq(e,o,a,u,m,p){let f=$n(e,a,u);return $d(f)?g([pe(f.inferred,o,m),pe(e,o,p)]):Cd(f)?pe(f.inferred,o,m):pe(e,o,p)}function zd(e,o,a,u,m,p,f){return pt([a,u])?Tt(sq(e,o,a,u,m,p),{},f):Om(a,u,m,p,f)}function yw(e,o,a,u,m,p,f){let h=pe(e,o,a),I=pe(e,o,u);return zd(e,o,h,I,m,p,f)}function _m(e,o={}){return we("ConstructorParameters",[e],o)}function xw(e,o={}){return Vd(e,o)}function iq(e){let o=zr(e)?e.parameters:[],a=Mi({},fr([],[]),o);return Br(a)}function Vd(e,o){return pt([e])?Tt(iq(e),{},o):_m(e,o)}function Iw(e,o,a,u){let m=pe(e,o,a);return Vd(m,u)}function Lm(e,o,a={}){return we("Exclude",[e,o],a)}function Ew(e,o,a={}){return sc(e,o,a)}function sc(e,o,a){return pt([e,o])?Tt(Sm(e,o),{},a):Lm(e,o,a)}function bw(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return sc(p,f,m)}function Nm(e,o,a={}){return we("Extract",[e,o],a)}function Sw(e,o,a={}){return Jd(e,o,a)}function aq(e,o){let a=$n({},e,o);return Io(a)?[e]:[]}function ww(e,o,a=[]){return yt(e,(u,m)=>ww(m,o,[...a,...aq(u,o)]),()=>a)}function Tw(e,o){let a=qo(e),u=ye(a)?a.anyOf:[a],m=ww(u,o);return xo(m)}function Jd(e,o,a){return pt([e,o])?Tt(Tw(e,o),{},a):Nm(e,o,a)}function Rw(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return Jd(p,f,m)}function uq(e){return e.reduce((o,a)=>fm(a)?[...o,i(a)]:o,[])}function Qa(e){let o=uq(e);return g(o)}function Wu(e,o,a={}){return we("Index",[e,o],a)}function kw(e,o,a={}){let u=$e(o)?Qa(o):o;return Qd(e,u,a)}function Aw(e,o){let a=js(e,o);return Co(a)}function Pw(e,o,a){let u=ms(e,o,a);return Co(u)}function cq(e,o){let a=xe(e).filter((S)=>!me(o,S)),u=xe(o).filter((S)=>!me(e,S)),m=xe(e).filter((S)=>me(o,S)),p=a.reduce((S,R)=>({...S,[R]:e[R]}),{}),f=u.reduce((S,R)=>({...S,[R]:o[R]}),{}),h=m.reduce((S,R)=>({...S,[R]:Cr([e[R],o[R]])}),{}),I=fn(p,f);return fn(I,h)}function $w(e){return e.reduce((o,a)=>cq(o,Co(a)),{})}function Cw(e){return e}function vw(e){let o=Ix(Br(e));return Co(o)}function mq(e,o){return xe(e).filter((m)=>(m in o)).reduce((m,p)=>({...m,[p]:xo([e[p],o[p]])}),{})}function Mw(e,o){return yt(e,(a,u)=>Mw(u,mq(o,Co(a))),()=>o)}function Ow(e){return yt(e,(o,a)=>Mw(a,Co(o)),()=>Ur())}function Co(e){return ar(e)?Aw(e.$defs,e.$ref):jr(e)?Pw(e.if,e.then,e.else):Ke(e)?$w(e.allOf):ye(e)?Ow(e.anyOf):dt(e)?vw(e.items):ze(e)?Cw(e.properties):{}}function Xa(e){let o=Co(e);return l(o)}var pq=new RegExp("^(?:0|[1-9][0-9]*)$");function Ya(e){let o=`${e}`;return pq.test(o)?parseInt(o):e}function lq(e){return i(Ya(e))}function _w(e){return e.map((o)=>Lw(o))}function Lw(e){return Ke(e)?Ln(_w(e.allOf)):ye(e)?g(_w(e.anyOf)):gt(e)?lq(e.const):e}function Nw(e,o){let a=Lw(o),u=$n({},a,re());return Io(u)?e:gt(o)&&v(o.const,"length")?re():nr()}function qw(e,o){let a=js(e,o);return Ro(a)}function Dw(e,o,a){let u=ms(e,o,a);return Ro(u)}function Fw(e){let o=zn(e);return Ro(o)}function jw(e){let o=Cr(e);return Ro(o)}function Uw(e){return[`${e}`]}function Bw(e){let o=qn(e);return Ro(o)}function Gw(e){return e.reduce((o,a)=>[...o,...Ro(a)],[])}function Ro(e){return ar(e)?qw(e.$defs,e.$ref):jr(e)?Dw(e.if,e.then,e.else):Xr(e)?Fw(e.enum):Ke(e)?jw(e.allOf):gt(e)?Uw(e.const):mr(e)?Bw(e.pattern):ye(e)?Gw(e.anyOf):[]}function Za(e){return Ro(e)}function ic(e,o){return o.map((a)=>ac(e,a))}function ac(e,o){return At(o)?F(ac(e,o.items)):zr(o)?Ms(ic(e,o.parameters),ac(e,o.instanceType)):Vr(o)?Os(ic(e,o.parameters),ac(e,o.returnType)):dt(o)?Br(ic(e,o.items)):ye(o)?g(ic(e,o.anyOf)):Ke(o)?Ln(ic(e,o.allOf)):km(o)?l(e):o}function Kw(e,o){return ac(e,o)}function dq(e,o){let a=o in e?e[o]:nr();return Kw(e,a)}function Hw(e,o){return o.reduce((a,u)=>[...a,dq(e,u)],[])}function fq(e,o){let a=Za(o),u=Hw(e,a);return xo(u)}var hq=new RegExp(Ri);function gq(e){return e.filter((a)=>hq.test(a))}function yq(e){let o=im(e),a=gq(o),u=Hw(e,a);return xo(u)}function Ww(e,o){return $r(o)?yq(e):fq(e,o)}function xq(e){return i(Ya(e))}function zw(e){return e.map((o)=>Xd(o))}function Xd(e){return Ke(e)?Ln(zw(e.allOf)):ye(e)?g(zw(e.anyOf)):gt(e)?xq(e.const):e}function Iq(e,o){return e.reduceRight((a,u,m)=>{let p=$n({},i(m),o);return Io(p)?[u,...a]:a},[])}function Eq(e,o){let a=Xd(o),u=Iq(e,a);return wi(u)}function bq(e){return wi(e)}function Vw(e,o){return gt(o)&&v(o.const,"length")?i(e.length):$r(o)||hn(o)?bq(e):Eq(e,o)}function Jw(e,o){return At(e)?Nw(e.items,o):ze(e)?Ww(e.properties,o):dt(e)?Vw(e.items,o):nr()}function Sq(e){return ar(e)||jr(e)||Ke(e)||ye(e)?Xa(e):e}function Qd(e,o,a){return pt([e,o])?Tt(Jw(Sq(e),o),{},a):Wu(e,o,a)}function Qw(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return Qd(p,f,m)}function qm(e,o={}){return we("InstanceType",[e],o)}function Xw(e,o={}){return Yd(e,o)}function wq(e){return zr(e)?e.instanceType:nr()}function Yd(e,o){return pt([e])?Tt(wq(e),{},o):qm(e,o)}function Yw(e,o,a,u={}){let m=pe(e,o,a);return Yd(m,u)}function zu(e,o={}){return we("KeyOf",[e],o)}function Zw(e,o={}){return Zd(e,o)}function eT(){return g([re(),s(),ja()])}function tT(e){return re()}function Tq(e){return e.reduce((a,u)=>fm(u)?[...a,i(Ya(u))]:Ur(),[])}function rT(e){let o=xe(e),a=Tq(o);return wi(a)}function nT(e){return ki(e)}function oT(e){let o=e.map((a,u)=>i(u));return wi(o)}function sT(e){return _r(e)?eT():At(e)?tT(e.items):ze(e)?rT(e.properties):tr(e)?nT(e):dt(e)?oT(e.items):nr()}function Rq(e){return ar(e)||jr(e)||Ke(e)||ye(e)?Xa(e):e}function Zd(e,o){return pt([e])?Tt(sT(Rq(e)),{},o):zu(e,o)}function iT(e,o,a,u){let m=pe(e,o,a);return Zd(m,u)}function Gu(e,o,a,u,m={}){return we("Mapped",[e,o,a,u],m)}function aT(e,o,a,u,m={}){return ef({},fr([],[]),e,o,a,u,m)}function kq(e){let o=qn(e);return up(o)}function Aq(e){return e.reduce((o,a)=>[...o,...up(a)],[])}function Pq(e){let o=zn(e);return up(o)}function $q(e){return Dt(e)?[i(`${e}`)]:[i(e)]}function up(e){return Xr(e)?Pq(e.enum):gt(e)?$q(e.const):mr(e)?kq(e.pattern):ye(e)?Aq(e.anyOf):[e]}function uT(e){return up(e)}function Cq(e){return mr(e)?qn(e.pattern):e}function vq(e,o,a,u,m,p){let f=fn(e,{[a.name]:u}),h=pe(f,o,m),I=Cq(h),E=pe(f,o,p);return hm(I)||gm(I)?{[I.const]:E}:{}}function Mq(e,o,a,u,m,p){return u.reduce((f,h)=>[...f,vq(e,o,a,h,m,p)],[])}function Oq(e){return e.reduce((o,a)=>[...o,l(a)],[])}function cT(e,o,a,u,m,p){let f=uT(u),h=Mq(e,o,a,f,m,p),I=Oq(h);return Cr(I)}function ef(e,o,a,u,m,p,f){return pt([u])?Tt(cT(e,o,a,u,m,p),{},f):Gu(a,u,m,p,f)}function mT(e,o,a,u,m,p,f){let h=pe(e,o,u);return ef(e,o,a,h,m,p,f)}function _q(e,o,a){let u=fn(e,o);return xe(o).filter((p)=>a.includes(p)).reduce((p,f)=>({...p,[f]:GS(u,f,o[f])}),{})}function Lq(e,o,a){let u=fn(e,o);return xe(o).filter((p)=>!a.includes(p)).reduce((p,f)=>({...p,[f]:pe(u,fr([],[]),o[f])}),{})}function Nq(e,o,a){let u=FS(o),m=_q(e,o,u),p=Lq(e,o,u),f={...m,...p};return Tt(f,{},a)}function cp(e,o,a,u){return Nq(e,a,u)}function Dm(e,o={}){return we("NonNullable",[e],o)}function pT(e,o={}){return tf(e,o)}function qq(e){let o=g([Nn(),Ga()]);return sc(e,o,{})}function tf(e,o){return pt([e])?Tt(qq(e),{},o):Dm(e,o)}function lT(e,o,a,u){let m=pe(e,o,a);return tf(m,u)}function Fm(e,o,a={}){return we("Omit",[e,o],a)}function dT(e,o,a={}){let u=$e(o)?Qa(o):o;return rf(e,u,a)}function mp(e){let o=Xa(e);return ze(o)?o.properties:Ur()}function Dq(e,o){return xe(e).reduce((u,m)=>o.includes(m)?u:{...u,[m]:e[m]},{})}function fT(e,o){let a=mp(e),u=Za(o),m=Dq(a,u);return l(m)}function rf(e,o,a){return pt([e,o])?Tt(fT(e,o),{},a):Fm(e,o,a)}function hT(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return rf(p,f,m)}function jm(e,o={}){return we("Parameters",[e],o)}function gT(e,o={}){return nf(e,o)}function Fq(e){let o=Vr(e)?e.parameters:[],a=Mi({},fr([],[]),o);return Br(a)}function nf(e,o){return pt([e])?Tt(Fq(e),{},o):jm(e,o)}function yT(e,o,a,u){let m=pe(e,o,a);return nf(m,u)}function Um(e,o={}){return we("Partial",[e],o)}function xT(e,o={}){return of(e,o)}function IT(e,o){let a=js(e,o),u=Us(a);return Ns(fn(e,{[o]:u}),o)}function ET(e,o,a){let u=ms(e,o,a);return Us(u)}function bT(e){let o=Cr(e);return Us(o)}function ST(e){let o=e.map((a)=>Us(a));return g(o)}function wT(e){let o=xe(e).reduce((u,m)=>({...u,[m]:aa(e[m])}),{});return l(o)}function Us(e){return ar(e)?IT(e.$defs,e.$ref):jr(e)?ET(e.if,e.then,e.else):Ke(e)?bT(e.allOf):ye(e)?ST(e.anyOf):ze(e)?wT(e.properties):l({})}function of(e,o){return pt([e])?Tt(Us(e),{},o):Um(e,o)}function TT(e,o,a,u){let m=pe(e,o,a);return of(m,u)}function Bm(e,o,a={}){return we("Pick",[e,o],a)}function RT(e,o,a={}){let u=$e(o)?Qa(o):o;return sf(e,u,a)}function jq(e,o){return xe(e).reduce((u,m)=>o.includes(m)?fn(u,{[m]:e[m]}):u,{})}function kT(e,o){let a=mp(e),u=Za(o),m=jq(a,u);return l(m)}function sf(e,o,a){return pt([e,o])?Tt(kT(e,o),{},a):Bm(e,o,a)}function AT(e,o,a,u,m){let p=pe(e,o,a),f=pe(e,o,u);return sf(p,f,m)}function Gm(e,o={}){return we("ReadonlyObject",[e],o)}function af(e,o={}){return uf(e,o)}var PT=af;function $T(e){return Fa(F(e))}function CT(e,o){let a=js(e,o),u=Bs(a);return Ns(fn(e,{[o]:u}),o)}function vT(e,o,a){let u=ms(e,o,a);return Bs(u)}function MT(e){let o=Cr(e);return Bs(o)}function OT(e){let o=xe(e).reduce((u,m)=>({...u,[m]:pa(e[m])}),{});return l(o)}function _T(e){return Fa(Br(e))}function LT(e){let o=e.map((a)=>Bs(a));return g(o)}function Bs(e){return At(e)?$T(e.items):ar(e)?CT(e.$defs,e.$ref):jr(e)?vT(e.if,e.then,e.else):Ke(e)?MT(e.allOf):ze(e)?OT(e.properties):dt(e)?_T(e.items):ye(e)?LT(e.anyOf):e}function uf(e,o){return pt([e])?Tt(Bs(e),{},o):Gm(e)}function NT(e,o,a,u){let m=pe(e,o,a);return uf(m,u)}function qT(e,o,a,u){return o.visited.includes(u)?a:(u in e)?pe(e,fr(o.callstack,[...o.visited,u]),e[u]):a}function DT(e,o){let a=js(e,o),u=Gs(a);return Ns(fn(e,{[o]:u}),o)}function FT(e,o,a){let u=ms(e,o,a);return Gs(u)}function jT(e){let o=Cr(e);return Gs(o)}function UT(e){let o=e.map((a)=>Gs(a));return g(o)}function BT(e){let o=xe(e).reduce((u,m)=>({...u,[m]:bm(e[m])}),{});return l(o)}function Gs(e){return ar(e)?DT(e.$defs,e.$ref):jr(e)?FT(e.if,e.then,e.else):Ke(e)?jT(e.allOf):ye(e)?UT(e.anyOf):ze(e)?BT(e.properties):l({})}function Km(e,o={}){return we("Required",[e],o)}function GT(e,o={}){return cf(e,o)}function cf(e,o){return pt([e])?Tt(Gs(e),{},o):Km(e,o)}function KT(e,o,a,u){let m=pe(e,o,a);return cf(m,u)}function Hm(e,o={}){return we("ReturnType",[e],o)}function HT(e,o={}){return mf(e,o)}function Uq(e){return Vr(e)?e.returnType:nr()}function mf(e,o){return pt([e])?Tt(Uq(e),{},o):Hm(e,o)}function WT(e,o,a,u={}){let m=pe(e,o,a);return mf(m,u)}function Wm(e,o){return we("With",[e,o],{})}function pp(e,o){return pf(e,o)}function pf(e,o){return pt([e])?Tt(e,{},o):Wm(e,o)}function zT(e,o,a,u){let m=pe(e,o,a);return pf(m,u)}function Bq(e){return Ai(e)?dt(e.items)?lf(e.items.items):Qr(e.items)?[e]:Xt(e.items)?[e]:[nr()]:[e]}function lf(e){return e.reduce((a,u)=>[...a,...Bq(u)],[])}function fr(e,o){return{callstack:e,visited:o}}function pt(e){return yt(e,(o,a)=>Xt(o)?!1:pt(a),()=>!0)}function Zu(e,o,a){return xe(a).reduce((u,m)=>({...u,[m]:pe(e,o,a[m])}),{})}function Mi(e,o,a){let u=$o(e,o,a);return lf(u)}function $o(e,o,a){return a.map((u)=>pe(e,o,u))}function Gq(e,o){let a=tn(e)?Ou(o,{}):o,u=la(e)?Mu(a,{}):a;return ma(e)?uc(u,{}):u}function Kq(e,o,a,u,m){return v(a,"AddImmutable")?VT(e,o,u[0],m):v(a,"RemoveImmutable")?nw(e,o,u[0],m):v(a,"AddReadonly")?by(e,o,u[0],m):v(a,"RemoveReadonly")?fx(e,o,u[0],m):v(a,"AddOptional")?Sy(e,o,u[0],m):v(a,"RemoveOptional")?yx(e,o,u[0],m):v(a,"Capitalize")?lw(e,o,u[0],m):v(a,"Conditional")?yw(e,o,u[0],u[1],u[2],u[3],m):v(a,"ConstructorParameters")?Iw(e,o,u[0],m):v(a,"Evaluate")?WS(e,o,u[0],m):v(a,"Exclude")?bw(e,o,u[0],u[1],m):v(a,"Extract")?Rw(e,o,u[0],u[1],m):v(a,"Index")?Qw(e,o,u[0],u[1],m):v(a,"InstanceType")?Yw(e,o,u[0],m):v(a,"Interface")?LS(e,o,u[0],u[1],m):v(a,"KeyOf")?iT(e,o,u[0],m):v(a,"Lowercase")?dw(e,o,u[0],m):v(a,"Mapped")?mT(e,o,u[0],u[1],u[2],u[3],m):v(a,"Module")?cp(e,o,u[0],m):v(a,"NonNullable")?lT(e,o,u[0],m):v(a,"Pick")?AT(e,o,u[0],u[1],m):v(a,"Parameters")?yT(e,o,u[0],m):v(a,"Partial")?TT(e,o,u[0],m):v(a,"Omit")?hT(e,o,u[0],u[1],m):v(a,"ReadonlyObject")?NT(e,o,u[0],m):v(a,"Record")?_x(e,o,u[0],u[1],m):v(a,"Required")?KT(e,o,u[0],m):v(a,"ReturnType")?WT(e,o,u[0],m):v(a,"TemplateLiteral")?tS(e,o,u[0],m):v(a,"Uncapitalize")?fw(e,o,u[0],m):v(a,"Uppercase")?hw(e,o,u[0],m):v(a,"With")?zT(e,o,u[0],u[1]):we(a,u,m)}function Hq(e,o,a){let u=Xt(a)?qT(e,o,a,a.$ref):At(a)?F(pe(e,o,a.items),La(a)):Ja(a)?ap(e,o,a.target,a.arguments):zr(a)?Ms($o(e,o,a.parameters),pe(e,o,a.instanceType),wy(a)):Vr(a)?Os($o(e,o,a.parameters),pe(e,o,a.returnType),Ty(a)):jr(a)?ua(pe(e,o,a.if),pe(e,o,a.then),pe(e,o,a.else),Py(a)):Ke(a)?Ln($o(e,o,a.allOf),Oy(a)):ze(a)?l(Zu(e,o,a.properties),Ay(a)):tr(a)?Lx(gn(a),pe(e,o,dr(a))):Ai(a)?ha(pe(e,o,a.items)):dt(a)?Br(Mi(e,o,a.items),dx(a)):ye(a)?g($o(e,o,a.anyOf),nx(a)):a;return Gq(a,u)}function pe(e,o,a){return Ei(a)?Kq(e,o,a.action,a.parameters,a.options):Hq(e,o,a)}function Do(e,o){return pe(e,fr([],[]),o)}function Wq(e){return Tt(e,{"~immutable":!0},{})}function uc(e,o){return Tt(Wq(e),{},o)}function VT(e,o,a,u){let m=pe(e,o,a);return uc(m,u)}function XE(e,o={}){return we("AddImmutable",[e],o)}function Fa(e,o={}){return uc(e,o)}function YE(e,o={}){return we("Evaluate",[e],o)}function Cn(e,o={}){return Fd(e,o)}function ZE(e,o={}){return we("Module",[e],o)}function JT(e,o={}){return cp({},fr([],[]),e,o)}function zq(e,o){let a=Ua(e,o);return v(a,Uu)?1:v(a,nc)?1:0}function QT(e,o,a=[]){return yt(o,(u,m)=>v(zq(e,u),1)?QT(e,m,[...a,u]):[...a,e,...o],()=>[...a,e])}function XT(e,o=[]){return yt(e,(a,u)=>XT(u,QT(a,o)),()=>o)}function YT(e){return XT(e)}function ZT(...e){let[o,a,u]=Pn(e,{2:(f,h)=>ht(f)?[{},f,h]:[f,h,{}],3:(f,h,I)=>[f,h,I],1:(f)=>[{},f,{}]}),m=Qb(a),p=$e(m)&&v(m.length,2)?pe(o,fr([],[]),m[0]):nr();return Tt(p,{},u)}function Vq(e){return{type:"text",text:e.text,...e.textSignature===void 0?{}:{textSignature:e.textSignature}}}function Jq(e){return{type:"thinking",thinking:e.thinking,...e.thinkingSignature===void 0?{}:{thinkingSignature:e.thinkingSignature},...e.redacted===void 0?{}:{redacted:e.redacted}}}function Qq(e){return{type:"toolCall",id:e.id,name:e.name,arguments:structuredClone(e.arguments),...e.thoughtSignature===void 0?{}:{thoughtSignature:e.thoughtSignature},...e.namespace===void 0?{}:{namespace:e.namespace}}}function Xq(e){return{role:"assistant",content:[],api:e.api,provider:e.provider,model:e.model,...e.responseModel===void 0?{}:{responseModel:e.responseModel},...e.responseId===void 0?{}:{responseId:e.responseId},...e.providerThinkingLevel===void 0?{}:{providerThinkingLevel:e.providerThinkingLevel},...e.diagnostics===void 0?{}:{diagnostics:structuredClone(e.diagnostics)},usage:structuredClone(e.usage),stopReason:"pending",timestamp:e.timestamp}}function cc(e){if(!Number.isSafeInteger(e)||e<0)throw Error(`Invalid assistant message frame contentIndex: ${e}`)}function eu(e){cc(e.contentIndex);let o=e.partial.content[e.contentIndex];if(!o)throw Error(`${e.type} event has no content block at index ${e.contentIndex}`);return o}function ff(e){let o=JSON.stringify(e);if(o===void 0)throw Error("Tool-call arguments are not JSON-serializable");return o}var Yq=ff(z(""));function hf(e,o){if(typeof e==="string")return typeof o==="string"&&o.startsWith(e);if(Array.isArray(e))return Array.isArray(o)&&e.length<=o.length&&e.every((u,m)=>hf(u,o[m]));if(typeof e!=="object"||e===null)return Object.is(e,o);if(typeof o!=="object"||o===null||Array.isArray(o))return!1;let a=o;return Object.entries(e).every(([u,m])=>Object.hasOwn(a,u)&&hf(m,a[u]))}class eR{started=!1;terminal=!1;blocks=new Map;encode(e){if(this.terminal)throw Error(`Assistant message event ${e.type} follows a terminal event`);switch(e.type){case"start":if(this.started)throw Error("Assistant message stream contains more than one start event");return this.started=!0,{type:"start",partial:Xq(e.partial)};case"done":if(!this.started)throw Error("Assistant message done event appears before start");this.terminal=!0;return;case"error":this.terminal=!0;return}if(!this.started)throw Error(`Assistant message ${e.type} event appears before start`);switch(e.type){case"text_start":{let o=eu(e);if(o.type!=="text")throw Error(`text_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"text",coveredChars:o.text.length,deltaChars:0}),{type:"text_start",contentIndex:e.contentIndex,content:Vq(o)}}case"text_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"text");case"text_end":{let o=eu(e);if(o.type!=="text")throw Error(`text_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"text"),{type:"text_end",contentIndex:e.contentIndex,content:e.content,...o.textSignature===void 0?{}:{textSignature:o.textSignature}}}case"thinking_start":{let o=eu(e);if(o.type!=="thinking")throw Error(`thinking_start event points to ${o.type} block at index ${e.contentIndex}`);return this.startBlock(e.contentIndex,{kind:"thinking",coveredChars:o.thinking.length,deltaChars:0}),{type:"thinking_start",contentIndex:e.contentIndex,content:Jq(o)}}case"thinking_delta":return this.encodeTextDelta(e.contentIndex,e.delta,"thinking");case"thinking_end":{let o=eu(e);if(o.type!=="thinking")throw Error(`thinking_end event points to ${o.type} block at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"thinking"),{type:"thinking_end",contentIndex:e.contentIndex,content:e.content,...o.thinkingSignature===void 0?{}:{thinkingSignature:o.thinkingSignature},...o.redacted===void 0?{}:{redacted:o.redacted}}}case"toolcall_start":{let o=eu(e);if(o.type!=="toolCall")throw Error(`toolcall_start event points to ${o.type} block at index ${e.contentIndex}`);let a=ff(o.arguments),u=a===Yq;return this.startBlock(e.contentIndex,{kind:"toolCall",caughtUp:u,catchupJson:"",snapshotArguments:u?"":a}),{type:"toolcall_start",contentIndex:e.contentIndex,toolCall:Qq(o)}}case"toolcall_delta":{let o=this.block(e.contentIndex,"toolCall");if(o.kind!=="toolCall")throw Error("Unreachable tool-call encoder state");if(o.caughtUp)return e.delta.length===0?void 0:{type:"toolcall_delta",contentIndex:e.contentIndex,delta:e.delta};o.catchupJson+=e.delta;let a=z(o.catchupJson);if(ff(a)!==o.snapshotArguments){let m=z(o.snapshotArguments);if(!hf(m,a))return}o.caughtUp=!0,o.snapshotArguments="";let u=o.catchupJson;return o.catchupJson="",u.length===0?void 0:{type:"toolcall_checkpoint",contentIndex:e.contentIndex,json:u}}case"toolcall_end":{let o=eu(e);if(o.type!=="toolCall")throw Error(`toolcall_end event points to ${o.type} block at index ${e.contentIndex}`);if(e.toolCall.type!=="toolCall")throw Error(`toolcall_end event has invalid tool call at index ${e.contentIndex}`);return this.endBlock(e.contentIndex,"toolCall"),{type:"toolcall_end",contentIndex:e.contentIndex,id:e.toolCall.id,name:e.toolCall.name,arguments:structuredClone(e.toolCall.arguments),...e.toolCall.thoughtSignature===void 0?{}:{thoughtSignature:e.toolCall.thoughtSignature},...e.toolCall.namespace===void 0?{}:{namespace:e.toolCall.namespace}}}}}startBlock(e,o){if(cc(e),this.blocks.has(e))throw Error(`Assistant message block ${e} starts more than once`);this.blocks.set(e,o)}block(e,o){cc(e);let a=this.blocks.get(e);if(a===void 0)throw Error(`Assistant message ${o} block ${e} has not started`);if(a.kind!==o)throw Error(`Assistant message block ${e} is ${a.kind}, not ${o}`);return a}endBlock(e,o){this.block(e,o),this.blocks.delete(e)}encodeTextDelta(e,o,a){let u=this.block(e,a);if(u.kind==="toolCall")throw Error("Unreachable text encoder state");let m=u.deltaChars;u.deltaChars+=o.length;let p=Math.max(0,u.coveredChars-m);if(p>=o.length)return;let f=p===0?o:o.slice(p);return a==="text"?{type:"text_delta",contentIndex:e,delta:f}:{type:"thinking_delta",contentIndex:e,delta:f}}}function df(e,o,a,u,m){if(cc(a),a!==e.content.length){let p=a<e.content.length?"already exists":"would leave a gap";throw Error(`Cannot start assistant message block at index ${a}: ${p}`)}e.content.push(structuredClone(u)),o.set(a,m)}function Ia(e,o,a,u,m){cc(a);let p=o.get(a),f=e.content[a];if(!p||!f)throw Error(`${m} frame has no started block at index ${a}`);if(p.kind!==u||f.type!==u)throw Error(`${m} frame expected ${u} block at index ${a}, found ${f.type}`);if(p.ended)throw Error(`${m} frame follows the end of block at index ${a}`);return{block:f,state:p}}function Zq(e){let o,a,u=new Map;for(let m of e){if(m.type==="start"){if(o)throw Error("Assistant message frame sequence contains more than one start frame");if(a!==void 0)throw Error(`${a} frame appears before the start frame`);o=structuredClone(m.partial);continue}if(!o){a??=m.type;continue}switch(m.type){case"text_start":if(m.content.type!=="text")throw Error(`text_start frame contains ${m.content.type} content`);df(o,u,m.contentIndex,m.content,{kind:"text",ended:!1});break;case"text_delta":{let{block:p}=Ia(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");p.text+=m.delta;break}case"text_end":{let{block:p,state:f}=Ia(o,u,m.contentIndex,"text",m.type);if(p.type!=="text")throw Error("Unreachable text frame state");if(p.text=m.content,delete p.textSignature,m.textSignature!==void 0)p.textSignature=m.textSignature;f.ended=!0;break}case"thinking_start":if(m.content.type!=="thinking")throw Error(`thinking_start frame contains ${m.content.type} content`);df(o,u,m.contentIndex,m.content,{kind:"thinking",ended:!1});break;case"thinking_delta":{let{block:p}=Ia(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");p.thinking+=m.delta;break}case"thinking_end":{let{block:p,state:f}=Ia(o,u,m.contentIndex,"thinking",m.type);if(p.type!=="thinking")throw Error("Unreachable thinking frame state");if(p.thinking=m.content,delete p.thinkingSignature,delete p.redacted,m.thinkingSignature!==void 0)p.thinkingSignature=m.thinkingSignature;if(m.redacted!==void 0)p.redacted=m.redacted;f.ended=!0;break}case"toolcall_start":if(m.toolCall.type!=="toolCall")throw Error(`toolcall_start frame contains ${m.toolCall.type} content`);df(o,u,m.contentIndex,m.toolCall,{kind:"toolCall",ended:!1,json:""});break;case"toolcall_checkpoint":{let{block:p,state:f}=Ia(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call checkpoint state");f.json=m.json,p.arguments=z(m.json);break}case"toolcall_delta":{let{block:p,state:f}=Ia(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall"||f.kind!=="toolCall")throw Error("Unreachable tool-call frame state");f.json+=m.delta;break}case"toolcall_end":{let{block:p,state:f}=Ia(o,u,m.contentIndex,"toolCall",m.type);if(p.type!=="toolCall")throw Error("Unreachable tool-call frame state");if(p.id=m.id,p.name=m.name,p.arguments=structuredClone(m.arguments),delete p.thoughtSignature,delete p.namespace,m.thoughtSignature!==void 0)p.thoughtSignature=m.thoughtSignature;if(m.namespace!==void 0)p.namespace=m.namespace;f.ended=!0;break}}}if(!o)return;for(let[m,p]of u){if(p.kind!=="toolCall"||p.ended||p.json.length===0)continue;let f=o.content[m];if(f?.type!=="toolCall")throw Error("Unreachable tool-call frame state");f.arguments=z(p.json)}return o}var tR=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],eD=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,tD=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Ea(e,o){if(e.stopReason==="error"&&e.errorMessage){if(!tD.some((u)=>u.test(e.errorMessage))){if(tR.some((u)=>u.test(e.errorMessage)))return!0;if(e.provider==="cerebras"&&eD.test(e.errorMessage))return!0}}if(o&&e.stopReason==="stop"){if(e.usage.input+e.usage.cacheRead>o)return!0}if(o&&e.stopReason==="length"&&e.usage.output===0){if(e.usage.input+e.usage.cacheRead>=o*0.99)return!0}return!1}function rD(e,o){return e.stopReason==="length"&&o>0&&e.usage.output<o}function nD(){return[...tR]}function rR(e){return new RegExp(e.join("|"),"i")}var oD=rR(["GoUsageLimitError","FreeUsageLimitError","Monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing","subscription_sharing_usage_limit_exceeded"]),sD=rR(["overloaded","server_busy","servers are currently busy","currently experiencing high demand","model is at capacity","rate.?limit","too many requests","429","500","502","503","504","520","524","service.?unavailable","server.?error","internal.?error","provider.?returned.?(?:an.?)?error","exceeded request buffer limit while retrying upstream","network.?error","connection.?error","connection.?refused","connection.?lost","other side closed","fetch failed","getaddrinfo","ENOTFOUND","EAI_AGAIN","upstream.?connect","reset before headers","socket hang up","socket connection was closed","timed? out","timeout","terminated","websocket.?closed","websocket.?error","ended without","stream ended before message_stop","stream ended before a terminal response event","http2 request did not get a response","pending stream has been canceled","retry delay","you can retry your request","try your request again","please retry your request","ResourceExhausted","subscription_sharing_usage_unavailable","subscription_sharing_user_unavailable"]),nR=60000;function oR(e,o){let a=e.baseDelayMs*2**Math.max(0,o-1),u=Number.isSafeInteger(a)?a:Number.MAX_SAFE_INTEGER;return Math.min(u,e.maxAgentDelayMs??nR)}class lp extends Error{constructor(){super("Aborted")}}function iD(e,o){return new Promise((a,u)=>{if(o?.aborted){u(new lp);return}let m=setTimeout(a,e);o?.addEventListener("abort",()=>{clearTimeout(m),u(new lp)},{once:!0})})}async function aD(e,o,a,u){let m=o?.enabled?o.maxRetries:0,p=0,f;for(;;){let h=await e();if(h.stopReason==="aborted"){if(f)await u?.onRetryFinished?.(!1,f.attempt);return h}if(h.stopReason!=="error"){if(f)await u?.onRetryFinished?.(!0,f.attempt);return h}if(p>=m||!sR(h)){if(f)await u?.onRetryFinished?.(!1,f.attempt,h.errorMessage);return h}p++,f={attempt:p,errorMessage:h.errorMessage||"Unknown error"};let I=oR(o,p);await u?.onRetryScheduled?.(p,m,I,f.errorMessage);try{await iD(I,a)}catch(E){if(await u?.onRetryFinished?.(!1,p,f.errorMessage),E instanceof lp){let{errorMessage:S,...R}=h;return{...R,stopReason:"aborted"}}throw E}await u?.onRetryAttemptStart?.()}}function sR(e){if(e.stopReason!=="error"||!e.errorMessage)return!1;let o=e.errorMessage;if(oD.test(o))return!1;return sD.test(o)}function uD(e,o){return Sr({type:"string",enum:e,...o?.description&&{description:o.description},...o?.default&&{default:o.default}})}function mc(e){return me(e,"~refine")&&$e(e["~refine"])&&Zr(e["~refine"],0,(o)=>mt(o)&&me(o,"check")&&me(o,"error")&&Ps(o.check)&&Ps(o.error))}function In(e){return mt(e)&&!$e(e)}function Zs(e){return nn(e)}function Ye(e){return In(e)||Zs(e)}function tu(e){return me(e,"additionalItems")&&Ye(e.additionalItems)}function Fo(e){return me(e,"additionalProperties")&&Ye(e.additionalProperties)}function pc(e){return me(e,"allOf")&&$e(e.allOf)&&e.allOf.every((o)=>Ye(o))}function lc(e){return me(e,"$anchor")&&ht(e.$anchor)}function dc(e){return me(e,"anyOf")&&$e(e.anyOf)&&e.anyOf.every((o)=>Ye(o))}function dp(e){return me(e,"const")}function Ks(e){return me(e,"contains")&&Ye(e.contains)}function vo(e){return me(e,"default")}function fc(e){return me(e,"dependencies")&&mt(e.dependencies)&&Object.values(e.dependencies).every((o)=>Ye(o)||$e(o)&&o.every((a)=>ht(a)))}function hc(e){return me(e,"dependentRequired")&&mt(e.dependentRequired)&&Object.values(e.dependentRequired).every((o)=>$e(o)&&o.every((a)=>ht(a)))}function ru(e){return me(e,"dependentSchemas")&&mt(e.dependentSchemas)&&Object.values(e.dependentSchemas).every((o)=>Ye(o))}function ei(e){return me(e,"$dynamicAnchor")&&ht(e.$dynamicAnchor)}function gc(e){return me(e,"$dynamicRef")&&ht(e.$dynamicRef)}function yc(e){return me(e,"else")&&Ye(e.else)}function fp(e){return me(e,"enum")&&$e(e.enum)}function xc(e){return me(e,"exclusiveMaximum")&&(Dt(e.exclusiveMaximum)||Fr(e.exclusiveMaximum))}function fs(e){return me(e,"exclusiveMinimum")&&(Dt(e.exclusiveMinimum)||Fr(e.exclusiveMinimum))}function ba(e){return me(e,"format")&&ht(e.format)}function Mo(e){return me(e,"$id")&&ht(e.$id)}function Ic(e){return me(e,"if")&&Ye(e.if)}function si(e){return me(e,"items")&&(Ye(e.items)||$e(e.items)&&e.items.every((o)=>Ye(o)))}function Ec(e){return si(e)&&$e(e.items)}function bc(e){return me(e,"maximum")&&(Dt(e.maximum)||Fr(e.maximum))}function Sc(e){return me(e,"maxContains")&&Dt(e.maxContains)}function nu(e){return me(e,"maxItems")&&Dt(e.maxItems)}function wc(e){return me(e,"maxLength")&&Dt(e.maxLength)}function Tc(e){return me(e,"maxProperties")&&Dt(e.maxProperties)}function hs(e){return me(e,"minimum")&&(Dt(e.minimum)||Fr(e.minimum))}function ai(e){return me(e,"minContains")&&Dt(e.minContains)}function Oi(e){return me(e,"minItems")&&Dt(e.minItems)}function Sa(e){return me(e,"minLength")&&Dt(e.minLength)}function wa(e){return me(e,"minProperties")&&Dt(e.minProperties)}function Rc(e){return me(e,"multipleOf")&&(Dt(e.multipleOf)||Fr(e.multipleOf))}function kc(e){return me(e,"not")&&Ye(e.not)}function Ac(e){return me(e,"oneOf")&&$e(e.oneOf)&&e.oneOf.every((o)=>Ye(o))}function Ta(e){return me(e,"pattern")&&(ht(e.pattern)||e.pattern instanceof RegExp)}function ui(e){return me(e,"patternProperties")&&mt(e.patternProperties)&&Object.values(e.patternProperties).every((o)=>Ye(o))}function gs(e){return me(e,"prefixItems")&&$e(e.prefixItems)&&e.prefixItems.every((o)=>Ye(o))}function ci(e){return me(e,"properties")&&mt(e.properties)&&Object.values(e.properties).every((o)=>Ye(o))}function ou(e){return me(e,"propertyNames")&&(mt(e.propertyNames)||Ye(e.propertyNames))}function cD(e){return me(e,"$recursiveAnchor")&&nn(e.$recursiveAnchor)}function Pc(e){return cD(e)&&v(e.$recursiveAnchor,!0)}function $c(e){return me(e,"$recursiveRef")&&ht(e.$recursiveRef)}function Cc(e){return me(e,"$ref")&&ht(e.$ref)}function ys(e){return me(e,"required")&&$e(e.required)&&e.required.every((o)=>ht(o))}function vc(e){return me(e,"then")&&Ye(e.then)}function Mc(e){return me(e,"type")&&(ht(e.type)||$e(e.type)&&e.type.every((o)=>ht(o)))}function _i(e){return me(e,"uniqueItems")&&nn(e.uniqueItems)}function Li(e){return me(e,"unevaluatedItems")&&Ye(e.unevaluatedItems)}function ji(e){return me(e,"unevaluatedProperties")&&Ye(e.unevaluatedProperties)}function mD(e){return Li(e)||ji(e)||Ma(xe(e),(o)=>hp(e[o]))}function pD(e){return Ma(e,(o)=>hp(o))}function hp(e){return $e(e)?pD(e):mt(e)?mD(e):!1}function iR(e,o){return hp(o)||Ma(xe(e),(a)=>hp(e[a]))}class gf{constructor(e){this.hasUnevaluated=e}UseUnevaluated(){return this.hasUnevaluated}Push(){return Ir(Et("context","Push"),[])}Pop(){return Ir(Et("context","Pop"),[])}AddIndex(e){return Ir(Et("context","AddIndex"),[e])}AddKey(e){return Ir(Et("context","AddKey"),[e])}Merge(e){return Ir(Et("context","Merge"),[e])}}class Fn{constructor(){let e=new Set,o=new Set;this.stack=[{indices:e,keys:o}]}Push(){let e=new Set,o=new Set;return this.stack.push({indices:e,keys:o}),!0}Pop(){return this.stack.pop(),!0}AddIndex(e){return this.GetIndices().add(e),!0}AddKey(e){return this.GetKeys().add(e),!0}GetIndices(){return this.stack[this.stack.length-1].indices}GetKeys(){return this.stack[this.stack.length-1].keys}Merge(e){for(let o of e)o.GetIndices().forEach((a)=>this.GetIndices().add(a)),o.GetKeys().forEach((a)=>this.GetKeys().add(a));return!0}}class jn extends Fn{constructor(){super();this.errors=[]}AtCapacity(){return this.errors.length>=ts().maxErrors}AddError(e){if(!this.AtCapacity())this.errors.push(e);return!1}GetErrors(){return this.errors}}var gp={identifier:"External",variables:[]};function Uo(e){let o=`External[${gp.variables.length}]`;return gp.variables.push(e),o}function aR(){gp.variables=[]}function uR(){return{...gp}}function cR(e,o,a,u){let m=Uo(a["~refine"].map((p)=>p));return Cs(m,Te(0),["refinement","_"],Ir(Et("refinement","check"),[u]))}function mR(e,o,a,u){return Zr(a["~refine"],0,(m,p)=>m.check(u))}function pR(e,o,a,u,m,p){return Mn(m["~refine"],0,(f,h)=>f.check(p)||o.AddError({keyword:"~refine",schemaPath:a,instancePath:u,params:{index:h,message:f.error(p)}}))}var lD=0;function or(){return`var_${lD++}`}function yf(e){return si(e)&&$e(e.items)}function dD(e,o,a,u){let[m,p]=[or(),or()],f=Vn(e,o,a.additionalItems,m),h=td(p,Te(a.items.length)),I=o.AddIndex(p);return Cs(u,Te(0),[m,p],yr(h,An(f,I)))}function fD(e,o,a,u){let[m,p]=[or(),or()],f=Vn(e,o,a.additionalItems,m),h=td(p,Te(a.items.length));return Cs(u,Te(0),[m,p],yr(h,f))}function lR(e,o,a,u){if(!yf(a))return Te(!0);return o.UseUnevaluated()?dD(e,o,a,u):fD(e,o,a,u)}function dR(e,o,a,u){if(!yf(a))return!0;return Zr(u,0,(p,f)=>Pu(f,a.items.length)||Oo(e,o,a.additionalItems,p)&&o.AddIndex(f))}function fR(e,o,a,u,m,p){if(!yf(m))return!0;return Zr(p,0,(h,I)=>{let E=`${a}/additionalItems`,S=`${u}/${I}`;return Pu(I,m.items.length)||_o(e,o,E,S,m.additionalItems,h)&&o.AddIndex(I)})}function Is(e){return new RegExp(e,"u")}function hD(e,o){return!e.UseUnevaluated()&&(v(o,!0)||mt(o)&&v(xe(o).length,0))}function gD(e){return`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`}function xf(e){let o=[];if(ui(e))o.push(...xe(e.patternProperties));if(ci(e))o.push(...xe(e.properties).map(gD));return v(o.length,0)?"(?!)":`(${o.join("|")})`}function yD(e,o,a){return ys(o)&&ci(o)&&!ui(o)&&v(o.additionalProperties,!1)&&v(xe(o.properties).length,o.required.length)}function xD(e,o,a){return bo(Et(Ir(Et("Object","getOwnPropertyNames"),[a]),"length"),Te(o.required.length))}function ID(e,o,a,u){let[m,p]=[or(),or()],f=Uo(Is(xf(a))),h=Vn(e,o,a.additionalProperties,`${u}[${m}]`),I=Ir(Et(f,"test"),[m]),E=o.AddKey(m),S=o.UseUnevaluated()?yr(I,An(h,E)):yr(I,h);return Cs(oa(u),Te(0),[m,p],S)}function hR(e,o,a,u){if(hD(o,a.additionalProperties))return Te(!0);return yD(o,a,u)?xD(o,a,u):ID(e,o,a,u)}function gR(e,o,a,u){let m=Is(xf(a));return Zr(xe(u),0,(f,h)=>m.test(f)||Oo(e,o,a.additionalProperties,u[f])&&o.AddKey(f))}function yR(e,o,a,u,m,p){let f=Is(xf(m)),h=[];return Mn(xe(p),0,(E,S)=>{let R=`${a}/additionalProperties`,k=`${u}/${E}`,A=f.test(E)||_o(e,o,R,k,m.additionalProperties,p[E])&&o.AddKey(E);if(!A)h.push(E);return A})||o.AddError({keyword:"additionalProperties",schemaPath:a,instancePath:u,params:{additionalProperties:h}})}function Ki(e,o,a,u,m){let p=Qs("results","[]"),f=a.map((S,R)=>Qs(`context_${R}`,rd("CheckContext",[]))),h=a.map((S,R)=>Qs(`condition_${R}`,Ir(xi(["context"],Ut(e,o,S,u)),[`context_${R}`]))),I=a.map((S,R)=>yy(`condition_${R}`,Ir(Et("results","push"),[`context_${R}`]))),E=sm(An(m,o.Merge("results")));return Ir(xi([],om([p,...f,...h,...I,E])),[])}function ED(e,o,a,u){return Ki(e,o,a.allOf,u,bo(Et("results","length"),Te(a.allOf.length)))}function bD(e,o,a,u){return On(a.allOf.map((m)=>Ut(e,o,m,u)))}function xR(e,o,a,u){return o.UseUnevaluated()?ED(e,o,a,u):bD(e,o,a,u)}function IR(e,o,a,u){let m=a.allOf.reduce((p,f)=>{let h=new Fn;return vt(e,h,f,u)?[...p,h]:p},[]);return v(m.length,a.allOf.length)&&o.Merge(m)}function ER(e,o,a,u,m,p){let f=[],h=m.allOf.reduce((E,S,R)=>{let k=`${a}/allOf/${R}`,A=new jn,P=pr(e,A,k,u,S,p);if(!P)f.push(A);return P?[...E,A]:E},[]),I=v(h.length,m.allOf.length)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I}function SD(e,o,a,u){return Ki(e,o,a.anyOf,u,fy(Et("results","length"),Te(0)))}function wD(e,o,a,u){return nd(a.anyOf.map((m)=>Ut(e,o,m,u)))}function bR(e,o,a,u){return o.UseUnevaluated()?SD(e,o,a,u):wD(e,o,a,u)}function SR(e,o,a,u){let m=a.anyOf.reduce((p,f)=>{let h=new Fn;return vt(e,h,f,u)?[...p,h]:p},[]);return ta(m.length,0)&&o.Merge(m)}function wR(e,o,a,u,m,p){let f=[],h=m.anyOf.reduce((E,S,R)=>{let k=new jn,A=`${a}/anyOf/${R}`,P=pr(e,k,A,u,S,p);if(!P)f.push(k);return P?[...E,k]:E},[]),I=ta(h.length,0)&&o.Merge(h);if(!I)f.forEach((E)=>E.GetErrors().forEach((S)=>o.AddError(S)));return I||o.AddError({keyword:"anyOf",schemaPath:a,instancePath:u,params:{}})}function TR(e,o,a,u){return a?Te(!0):Te(!1)}function If(e,o,a,u){return a}function RR(e,o,a,u,m,p){return If(e,o,m,p)||o.AddError({keyword:"boolean",schemaPath:a,instancePath:u,params:{}})}function kR(e,o,a,u){return ra(a.const)?bo(u,Te(a.const)):gy(u,Uo(a.const))}function Ef(e,o,a,u){return ra(a.const)?v(u,a.const):Oa(u,a.const)}function AR(e,o,a,u,m,p){return Ef(e,o,m,p)||o.AddError({keyword:"const",schemaPath:a,instancePath:u,params:{allowedValue:m.const}})}function PR(e){return!(ai(e)&&v(e.minContains,0))}function TD(e,o,a,u){let[m,p]=[or(),or()],f=Bn(bo(Et(u,"length"),Te(0))),h=fM(u,[m,p],An(Ut(e,o,a.contains,m),o.AddIndex(p)));return An(f,h)}function RD(e,o,a,u){let[m]=[or()],p=Bn(bo(Et(u,"length"),Te(0))),f=dM(u,[m,"_"],Ut(e,o,a.contains,m));return An(p,f)}function $R(e,o,a,u){if(!PR(a))return Te(!0);return o.UseUnevaluated()?TD(e,o,a,u):RD(e,o,a,u)}function bf(e,o,a,u){if(!PR(a))return!0;return!v(u.length,0)&&ay(u,(m,p)=>vt(e,o,a.contains,m)&&o.AddIndex(p))}function CR(e,o,a,u,m,p){return bf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:1}})}function vR(e,o,a,u){let m=bo(Et(oa(u),"length"),Te(0)),p=On(on(a.dependencies).map(([f,h])=>{let I=Bn(sa(u,Te(f))),E=Ut(e,o,h,u),S=(R)=>On(R.map((k)=>sa(u,Te(k))));return yr(I,$e(h)?S(h):E)}));return yr(m,p)}function MR(e,o,a,u){let m=v(xe(u).length,0),p=Zr(on(a.dependencies),0,([f,h])=>!me(u,f)||($e(h)?h.every((I)=>me(u,I)):vt(e,o,h,u)));return m||p}function OR(e,o,a,u,m,p){let f=v(xe(p).length,0),h=Mn(on(m.dependencies),0,([I,E])=>{let S=`${a}/dependencies/${I}`;return!me(p,I)||($e(E)?E.every((R)=>me(p,R)||o.AddError({keyword:"dependencies",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})):pr(e,o,S,u,E,p))});return f||h}function _R(e,o,a,u){let m=bo(Et(oa(u),"length"),Te(0)),p=On(on(a.dependentRequired).map(([f,h])=>{let I=Bn(sa(u,Te(f))),E=On(h.map((S)=>sa(u,Te(S))));return yr(I,E)}));return yr(m,p)}function LR(e,o,a,u){let m=v(xe(u).length,0),p=Zr(on(a.dependentRequired),0,([f,h])=>!me(u,f)||h.every((I)=>me(u,I)));return m||p}function NR(e,o,a,u,m,p){let f=v(xe(p).length,0),h=Mn(on(m.dependentRequired),0,([I,E])=>!me(p,I)||Mn(E,0,(S)=>me(p,S)||o.AddError({keyword:"dependentRequired",schemaPath:a,instancePath:u,params:{property:I,dependencies:E}})));return f||h}function qR(e,o,a,u){let m=bo(Et(oa(u),"length"),Te(0)),p=On(on(a.dependentSchemas).map(([f,h])=>{let I=Bn(sa(u,Te(f))),E=Ut(e,o,h,u);return yr(I,E)}));return yr(m,p)}function DR(e,o,a,u){let m=v(xe(u).length,0),p=Zr(on(a.dependentSchemas),0,([f,h])=>!me(u,f)||vt(e,o,h,u));return m||p}function FR(e,o,a,u,m,p){let f=v(xe(p).length,0),h=Mn(on(m.dependentSchemas),0,([I,E])=>{let S=`${a}/dependentSchemas/${I}`;return!me(p,I)||pr(e,o,S,u,E,p)});return f||h}function jR(e,o,a,u){let m=e.DynamicRef(a)??!1;return mi(e,o,m,u)}function UR(e,o,a,u){let m=e.DynamicRef(a)??!1;return Ye(m)&&vt(e,o,m,u)}function BR(e,o,a,u,m,p){let f=e.DynamicRef(m)??!1;return Ye(f)&&pr(e,o,"#",u,f,p)}function GR(e,o,a,u){return nd(a.enum.map((m)=>{if(ra(m))return bo(u,Te(m));let p=Uo(m);return gy(u,p)}))}function wf(e,o,a,u){return Ma(a.enum,(m)=>ra(m)?v(u,m):Oa(u,m))}function KR(e,o,a,u,m,p){return wf(e,o,m,p)||o.AddError({keyword:"enum",schemaPath:a,instancePath:u,params:{allowedValues:m.enum}})}function HR(e,o,a,u){return td(u,Te(a.exclusiveMaximum))}function Tf(e,o,a,u){return Pu(u,a.exclusiveMaximum)}function WR(e,o,a,u,m,p){return Tf(e,o,m,p)||o.AddError({keyword:"exclusiveMaximum",schemaPath:a,instancePath:u,params:{comparison:"<",limit:m.exclusiveMaximum}})}function zR(e,o,a,u){return fy(u,Te(a.exclusiveMinimum))}function Rf(e,o,a,u){return ta(u,a.exclusiveMinimum)}function VR(e,o,a,u,m,p){return Rf(e,o,m,p)||o.AddError({keyword:"exclusiveMinimum",schemaPath:a,instancePath:u,params:{comparison:">",limit:m.exclusiveMinimum}})}var kD=[0,31,28,31,30,31,30,31,31,30,31,30,31],AD=/^(\d\d\d\d)-(\d\d)-(\d\d)$/;function PD(e){return e%4===0&&(e%100!==0||e%400===0)}function iu(e){let o=AD.exec(e);if(!o)return!1;let a=+o[1],u=+o[2],m=+o[3];return u>=1&&u<=12&&m>=1&&m<=(u===2&&PD(a)?29:kD[u])}var $D=/^(\d\d):(\d\d):(\d\d)(?:\.\d+)?(?:([Zz])|([+-])(\d\d):(\d\d))?$/;function au(e,o=!0){let a=$D.exec(e);if(!a)return!1;if(o&&!a[4]&&!a[5])return!1;let u=+a[1],m=+a[2],p=+a[3];if(u>23||m>59||p>60)return!1;if(a[5]){let S=+a[6],R=+a[7];if(S>23||R>59)return!1}if(p<60)return!0;let f=a[5]==="-"?-1:1,h=+(a[6]||0),I=+(a[7]||0);return((u*60+m-f*(h*60+I))%1440+1440)%1440===1439}function yp(e){let o=e.split(/T/i);return o.length===2&&iu(o[0])&&au(o[1])}var CD=/^P((\d+Y(\d+M(\d+D)?)?|\d+M(\d+D)?|\d+D)(T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S))?|T(\d+H(\d+M(\d+S)?)?|\d+M(\d+S)?|\d+S)|\d+W)$/;function xp(e){return CD.test(e)}var vD=/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[^"\\]|\\[\x20-\x7e])*")@(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[(?:IPv6:[a-f0-9:]+|(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?:\.(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3})\])$/i;function Ip(e){return vD.test(e)}var JR=/^(?!-).*(?<!-)$/,QR=/^(?!..--)/,XR=/^[a-zA-Z0-9-]*$/;var uu=/[^\p{ASCII}]/u;var MD=/[0-9]/,YR=/[\u{0660}-\u{0669}]/u,OD=/[\u{06f0}-\u{06f9}]/u,_D=/[\u{002e}\u{002c}\u{003a}\u{002f}]/u,LD=/[\u{002d}\u{002b}]/u,kf=/\p{Mn}/u,ND=/\p{Mc}/u;var ZR=/[\p{Mn}\p{Mc}\p{Me}]/u,Af=/\p{L}/u,qD=/\p{Nd}/u,ek=/\p{Script=Greek}/u,Ep=/\p{Script=Hebrew}/u,tk=/[\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Han}]/u,rk=/[\p{Script=Arabic}\p{Script=Syriac}\p{Script=Thaana}\p{Script=Mandaic}]/u,Pf=/[\u{094d}\u{09cd}\u{0a4d}\u{0acd}\u{0b4d}\u{0bcd}\u{0c4d}\u{0ccd}\u{0d3b}\u{0d3c}\u{0d4d}\u{0dca}\u{1b44}\u{1baa}\u{1bab}\u{a9c0}\u{11046}\u{1107f}\u{110b9}\u{11133}\u{11134}\u{111c0}\u{11235}\u{1134d}\u{11442}\u{114c2}\u{115bf}\u{1163f}\u{116b6}\u{11c3f}\u{11d44}\u{11d45}]/u,nk=/[\u{0640}\u{07fa}\u{302e}\u{302f}\u{3031}\u{3032}\u{3033}\u{3034}\u{3035}\u{303b}]/u,DD=/[\u{00b7}\u{0375}\u{05f3}\u{05f4}\u{200c}\u{200d}\u{30fb}]/u,FD=/[\u{00df}\u{03c2}\u{06fd}\u{06fe}\u{0f0b}\u{3007}]/u,ok=new RegExp([MD,OD].map((e)=>e.source).join("|"),"u"),sk=new RegExp([Af,LD,_D,qD,kf,ND,DD,FD].map((e)=>e.source).join("|"),"u");function ik(e){return JR.test(e)&&QR.test(e)&&XR.test(e)}var Es=36,_c=1,Lc=26,UD=38,BD=700,uk=72,ck=128;function $f(){throw null}function bp(e){return e.toLowerCase().startsWith("xn--")}function mk(e,o,a){e=a?Math.floor(e/BD):e>>1,e+=Math.floor(e/o);let u=0;while(e>(Es-_c)*Lc>>1)e=Math.floor(e/(Es-_c)),u+=Es;return u+Math.floor((Es-_c+1)*e/(e+UD))}function Sp(e){let o=[],a=ck,u=0,m=uk,p=e.lastIndexOf("-");if(p>0)for(let h=0;h<p;h++){let I=e.charCodeAt(h);if(I>=128)$f();o.push(I)}let f=p<0?0:p+1;while(f<e.length){let h=u,I=1,E=Es;while(!0){if(f>=e.length)$f();let R=e.charCodeAt(f++),k;if(R>=97&&R<=122)k=R-97;else if(R>=48&&R<=57)k=R-48+26;else $f();u+=k*I;let A=E<=m?_c:E>=m+Lc?Lc:E-m;if(k<A)break;I*=Es-A,E+=Es}let S=o.length+1;m=mk(u-h,S,h===0),a+=Math.floor(u/S),u%=S,o.splice(u,0,a),u++}return String.fromCodePoint(...o)}function ak(e){return e<26?String.fromCharCode(e+97):String.fromCharCode(e-26+48)}var GD=new RegExp(uu.source,"gu");function pk(e){let o=e.replace(GD,""),a=o.length,u=a>0?[o,"-"]:[],m=Array.from(e,(E)=>E.codePointAt(0)),p=ck,f=0,h=uk,I=a;while(I<m.length){let E=1/0;for(let S of m)if(S>=p&&S<E)E=S;f+=(E-p)*(I+1),p=E;for(let S of m){if(S<p)f++;if(S===p){let R=f;for(let k=Es;;k+=Es){let A=k<=h?_c:k>=h+Lc?Lc:k-h;if(R<A)break;let P=A+(R-A)%(Es-A);u.push(ak(P)),R=Math.floor((R-A)/(Es-A))}u.push(ak(R)),h=mk(f,I+1,I===a),f=0,I++}}f++,p++}return u.join("")}var KD=/^(?:R|AL|AN|EN|ES|CS|ET|ON|BN|NSM)$/,lk=/^(?:L|EN|ES|CS|ET|ON|BN|NSM)$/,HD=/^(?:R|AL|AN)$/;function dk(e){if(bp(e))try{return wp(Sp(e.slice(4).toLowerCase()))}catch{return!1}return wp(e)}function fk(e){let o=String.fromCodePoint(e);return ok.test(o)?"EN":YR.test(o)?"AN":kf.test(o)?"NSM":Ep.test(o)?"R":rk.test(o)?"AL":Af.test(o)?"L":"ON"}function wp(e){for(let o of e)if(HD.test(fk(o.codePointAt(0))))return!0;return!1}function Tp(e){let o=!1,a=lk,u=!1,m=!1,p=!0;for(let f of e){let h=fk(f.codePointAt(0));if(p){if(h!=="L"&&h!=="R"&&h!=="AL")return!1;o=h==="R"||h==="AL",a=o?KD:lk,p=!1}if(!a.test(h))return!1;if(h==="EN")u=!0;else if(h==="AN")m=!0}if(o&&u&&m)return!1;return!0}function WD(e){return uu.test(e)&&pk(e).length+4>63}function zD(e){if(e[0]==="-"||e[e.length-1]==="-")return!0;return e.slice(2).join("").startsWith("--")}function Rp(e){if(WD(e))return!1;if(wp(e)&&!Tp(e))return!1;let o=[...e],a=o.map((p)=>p.codePointAt(0)),u=a.length;if(zD(o))return!1;if(ZR.test(o[0]))return!1;let m=!1;for(let p=0;p<u;p++){let f=a[p],h=o[p];if(nk.test(h))return!1;if(!sk.test(h))return!1;if(tk.test(h))m=!0;let I=a[p-1],E=a[p+1];switch(f){case 183:if(I!==108||E!==108)return!1;break;case 885:if(!E||!ek.test(o[p+1]))return!1;break;case 1523:case 1524:if(!I||!Ep.test(o[p-1]))return!1;break;case 8204:if(!I||I<128&&!Pf.test(o[p-1]))return!1;break;case 8205:if(!I||!Pf.test(o[p-1]))return!1;break;case 12539:break}}if(e.includes("\u30FB")&&!m)return!1;return!0}function kp(e){if(!bp(e))return!1;try{let o=e.slice(4).toLowerCase();if(o.lastIndexOf("-")===0)return!1;let a=Sp(o);if(!uu.test(a))return!1;return Rp(a)}catch{return!1}}function VD(e){return e.length>0&&e.length<=63}function JD(e){return VD(e)&&(kp(e)||ik(e))}function xk(e){if(e.length===0||e.length>253)return!1;if(e.charCodeAt(e.length-1)===46)return!1;return e.split(".").every((o)=>JD(o))}function QD(e){return e.length>0&&e.length<=63}function XD(e){return QD(e)&&(kp(e)||Rp(e))}function YD(e){return e.replace(/[\uff01-\uff5e]/g,(o)=>String.fromCharCode(o.charCodeAt(0)-65248)).normalize("NFC").replace(/[\u00ad\u034f\u180b-\u180d\u200b\ufe00-\ufe0f\u{e0100}-\u{e01ef}]/gu,"").replace(/[\u002E\u3002\uFF0E\uFF61]/g,".")}function Ik(e){if(e.length===0||e.includes(" "))return!1;let o=YD(e);if(o.length>253)return!1;let a=o.split("."),u=a.some((m)=>dk(m));return a.every((m)=>XD(m)&&(!u||Tp(m)))}function Ap(e){return xk(e)}var ZD=/^(?:[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+(?:\.[A-Za-z0-9!#$%&'*+\/=?^_`{|}~\u{0080}-\u{10FFFF}-]+)*|"(?:[^"\\]|\\.)*")@[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-)(?:\.[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,62})(?<!-))*$/iu;function Pp(e){return ZD.test(e.normalize("NFC"))}function $p(e){return Ik(e)}var eF=/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/;function Cp(e){return eF.test(e)}var tF=/^(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:)?[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)$/i;function vp(e){return tF.test(e)}var rF=/[\x00-\x20\x7F\\]|%(?![0-9a-fA-F]{2})/,nF=/^[a-zA-Z][a-zA-Z0-9+\-.]*\/\//;function Mp(e){return!rF.test(e)&&!nF.test(e)&&URL.canParse(e,"http://example.com")}var oF=/\[[vV][0-9a-fA-F]+\.[^\]]+\]/,sF=/[\x00-\x20<>\^`{|}\\]/,iF=/%(?![0-9a-fA-F]{2})/;function aF(e){return e.length<2048?e.replace(oF,"[::1]"):e}function Op(e){if(sF.test(e))return!1;if(iF.test(e))return!1;return URL.canParse(aF(e))}var uF=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;function _p(e){return uF.test(e)}var cF=/^(?:\/(?:[^~/]|~0|~1)*)*$/;function Lp(e){return cF.test(e)}function Np(e){try{return new RegExp(e,"u"),!0}catch{return!1}}var mF=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;function qp(e){return mF.test(e)}var pF=/^(?:[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?)(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function Dp(e){return pF.test(e)}var lF=/^(?:(?:[^\x00-\x20"<>%\\^`{|}\x7f]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?:\.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9]\d{0,3}|\*)?)*\})*$/i;function Fp(e){return lF.test(e)}var dF=/^[a-z][a-z0-9+\-.]*:(?:\/\/(?:(?:[-a-z0-9._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:[\da-f]{1,4}:){6}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|::(?:[\da-f]{1,4}:){5}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:[\da-f]{1,4})?::(?:[\da-f]{1,4}:){4}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,1}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){3}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,2}[\da-f]{1,4})?::(?:[\da-f]{1,4}:){2}(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,3}[\da-f]{1,4})?::[\da-f]{1,4}:(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,4}[\da-f]{1,4})?::(?:[\da-f]{1,4}:[\da-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))|(?:(?:[\da-f]{1,4}:){0,5}[\da-f]{1,4})?::[\da-f]{1,4}|(?:(?:[\da-f]{1,4}:){0,6}[\da-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)|(?:[-a-z0-9._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[-a-z0-9._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[-a-z0-9._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function jp(e){return dF.test(e)}function Up(e){return URL.canParse(e)}var fF=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;function Bp(e){return fF.test(e)}var Tr=new Map;function bk(){Tr.clear()}function hF(){return[...Tr.entries()]}function gF(e,o){Tr.set(e,o)}function yF(e){return Tr.has(e)}function xF(e){return Tr.get(e)}function Sk(e,o){return Tr.get(e)?.(o)??!0}function wk(){bk(),Tr.set("date-time",yp),Tr.set("date",iu),Tr.set("duration",xp),Tr.set("email",Ip),Tr.set("hostname",Ap),Tr.set("idn-email",Pp),Tr.set("idn-hostname",$p),Tr.set("ipv4",Cp),Tr.set("ipv6",vp),Tr.set("iri-reference",Mp),Tr.set("iri",Op),Tr.set("json-pointer-uri-fragment",_p),Tr.set("json-pointer",Lp),Tr.set("regex",Np),Tr.set("relative-json-pointer",qp),Tr.set("time",au),Tr.set("uri-reference",Dp),Tr.set("uri-template",Fp),Tr.set("uri",jp),Tr.set("url",Up),Tr.set("uuid",Bp)}wk();function Tk(e,o,a,u){return Ir(Et("Format","Test"),[Te(a.format),u])}function vf(e,o,a,u){return Sk(a.format,u)}function Rk(e,o,a,u,m,p){return vf(e,o,m,p)||o.AddError({keyword:"format",schemaPath:a,instancePath:u,params:{format:m.format}})}function kk(e,o,a,u){let m=vc(a)?a.then:!0,p=yc(a)?a.else:!0;return gM(Ut(e,o,a.if,u),Ut(e,o,m,u),Ut(e,o,p,u))}function Ak(e,o,a,u){let m=vc(a)?a.then:!0,p=yc(a)?a.else:!0;return vt(e,o,a.if,u)?vt(e,o,m,u):vt(e,o,p,u)}function Pk(e,o,a,u,m,p){let f=vc(m)?m.then:!0,h=yc(m)?m.else:!0,I=new jn,E=pr(e,I,`${a}/if`,u,m.if,p)?pr(e,I,`${a}/then`,u,f,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"then"}}):pr(e,o,`${a}/else`,u,h,p)||o.AddError({keyword:"if",schemaPath:a,instancePath:u,params:{failingKeyword:"else"}});if(E)o.Merge([I]);return E}function IF(e,o,a,u){return On(a.items.map((m,p)=>{let f=na(Et(u,"length"),Te(p)),h=Vn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Te(p));return yr(f,An(h,I))}))}function EF(e,o,a,u){return On(a.items.map((m,p)=>{let f=na(Et(u,"length"),Te(p)),h=Vn(e,o,m,`${u}[${p}]`);return yr(f,h)}))}function bF(e,o,a,u){return o.UseUnevaluated()?IF(e,o,a,u):EF(e,o,a,u)}function SF(e,o,a,u){return Zr(a.items,0,(m,p)=>$s(u.length,p)||Oo(e,o,m,u[p])&&o.AddIndex(p))}function wF(e,o,a,u,m,p){return Mn(m.items,0,(f,h)=>{let I=`${a}/items/${h}`,E=`${u}/${h}`;return $s(p.length,h)||_o(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function TF(e,o,a,u){let m=gs(a)?a.prefixItems.length:0,p=Vn(e,o,a.items,"element"),f=o.AddIndex("index");return Cs(u,Te(m),["element","index"],An(p,f))}function RF(e,o,a,u){let m=gs(a)?a.prefixItems.length:0,p=Vn(e,o,a.items,"element");return Cs(u,Te(m),["element","index"],p)}function kF(e,o,a,u){return o.UseUnevaluated()?TF(e,o,a,u):RF(e,o,a,u)}function AF(e,o,a,u){let m=gs(a)?a.prefixItems.length:0;return Zr(u,m,(p,f)=>Oo(e,o,a.items,p)&&o.AddIndex(f))}function PF(e,o,a,u,m,p){let f=gs(m)?m.prefixItems.length:0;return Mn(p,f,(h,I)=>{let E=`${a}/items`,S=`${u}/${I}`;return _o(e,o,E,S,m.items,h)&&o.AddIndex(I)})}function $k(e,o,a,u){return Ec(a)?bF(e,o,a,u):kF(e,o,a,u)}function Ck(e,o,a,u){return Ec(a)?SF(e,o,a,u):AF(e,o,a,u)}function vk(e,o,a,u,m,p){return Ec(m)?wF(e,o,a,u,m,p):PF(e,o,a,u,m,p)}function Mk(e){return Ks(e)}function Ok(e,o,a,u){if(!Mk(a))return Te(!0);let[m]=[or()],p=nm(u,[m,"_"],Ut(e,o,a.contains,m));return na(p,Te(a.maxContains))}function Mf(e,o,a,u){if(!Mk(a))return!0;let m=Xl(u,(p)=>vt(e,o,a.contains,p));return $s(m,a.maxContains)}function _k(e,o,a,u,m,p){let f=ai(m)?m.minContains:1;return Mf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:f,maxContains:m.maxContains}})}function Lk(e,o,a,u){return na(u,Te(a.maximum))}function Of(e,o,a,u){return $s(u,a.maximum)}function Nk(e,o,a,u,m,p){return Of(e,o,m,p)||o.AddError({keyword:"maximum",schemaPath:a,instancePath:u,params:{comparison:"<=",limit:m.maximum}})}function qk(e,o,a,u){return na(Et(u,"length"),Te(a.maxItems))}function _f(e,o,a,u){return $s(u.length,a.maxItems)}function Dk(e,o,a,u,m,p){return _f(e,o,m,p)||o.AddError({keyword:"maxItems",schemaPath:a,instancePath:u,params:{limit:m.maxItems}})}function Fk(e,o,a,u){return lM(u,Te(a.maxLength))}function Lf(e,o,a,u){return sy(u,a.maxLength)}function jk(e,o,a,u,m,p){return Lf(e,o,m,p)||o.AddError({keyword:"maxLength",schemaPath:a,instancePath:u,params:{limit:m.maxLength}})}function Uk(e,o,a,u){return na(Et(oa(u),"length"),Te(a.maxProperties))}function Nf(e,o,a,u){return $s(xe(u).length,a.maxProperties)}function Bk(e,o,a,u,m,p){return Nf(e,o,m,p)||o.AddError({keyword:"maxProperties",schemaPath:a,instancePath:u,params:{limit:m.maxProperties}})}function Gk(e){return Ks(e)}function $F(e,o,a,u){let[m,p]=[or(),or()],f=nm(u,[m,p],An(Ut(e,o,a.contains,m),o.AddIndex(p)));return Cu(f,Te(a.minContains))}function CF(e,o,a,u){let[m]=[or()],p=nm(u,[m,"_"],Ut(e,o,a.contains,m));return Cu(p,Te(a.minContains))}function Kk(e,o,a,u){if(!Gk(a))return Te(!0);return o.UseUnevaluated()?$F(e,o,a,u):CF(e,o,a,u)}function qf(e,o,a,u){if(!Gk(a))return!0;let m=Xl(u,(p,f)=>vt(e,o,a.contains,p)&&o.AddIndex(f));return va(m,a.minContains)}function Hk(e,o,a,u,m,p){return qf(e,o,m,p)||o.AddError({keyword:"contains",schemaPath:a,instancePath:u,params:{minContains:m.minContains}})}function Wk(e,o,a,u){return Cu(u,Te(a.minimum))}function Df(e,o,a,u){return va(u,a.minimum)}function zk(e,o,a,u,m,p){return Df(e,o,m,p)||o.AddError({keyword:"minimum",schemaPath:a,instancePath:u,params:{comparison:">=",limit:m.minimum}})}function Vk(e,o,a,u){return Cu(Et(u,"length"),Te(a.minItems))}function Ff(e,o,a,u){return va(u.length,a.minItems)}function Jk(e,o,a,u,m,p){return Ff(e,o,m,p)||o.AddError({keyword:"minItems",schemaPath:a,instancePath:u,params:{limit:m.minItems}})}function Qk(e,o,a,u){return pM(u,Te(a.minLength))}function jf(e,o,a,u){return iy(u,a.minLength)}function Xk(e,o,a,u,m,p){return jf(e,o,m,p)||o.AddError({keyword:"minLength",schemaPath:a,instancePath:u,params:{limit:m.minLength}})}function Yk(e,o,a,u){return Cu(Et(oa(u),"length"),Te(a.minProperties))}function Uf(e,o,a,u){return va(xe(u).length,a.minProperties)}function Zk(e,o,a,u,m,p){return Uf(e,o,m,p)||o.AddError({keyword:"minProperties",schemaPath:a,instancePath:u,params:{limit:m.minProperties}})}function eA(e,o,a,u){return yM(u,Te(a.multipleOf))}function Bf(e,o,a,u){return ny(u,a.multipleOf)}function tA(e,o,a,u,m,p){return Bf(e,o,m,p)||o.AddError({keyword:"multipleOf",schemaPath:a,instancePath:u,params:{multipleOf:m.multipleOf}})}function vF(e,o,a,u){return Ki(e,o,[a.not],u,Bn(bo(Et("results","length"),Te(1))))}function MF(e,o,a,u){return Bn(Ut(e,o,a.not,u))}function rA(e,o,a,u){return o.UseUnevaluated()?vF(e,o,a,u):MF(e,o,a,u)}function Gf(e,o,a,u){let m=new Fn;return!vt(e,m,a.not,u)&&o.Merge([m])}function nA(e,o,a,u,m,p){return Gf(e,o,m,p)||o.AddError({keyword:"not",schemaPath:a,instancePath:u,params:{}})}function OF(e,o,a,u){return Ki(e,o,a.oneOf,u,bo(Et("results","length"),Te(1)))}function _F(e,o,a,u){let[m]=[or()],p=hM(a.oneOf.map((h)=>Ut(e,o,h,u))),f=nm(p,[m,"_"],bo(m,Te(!0)));return bo(f,Te(1))}function oA(e,o,a,u){return o.UseUnevaluated()?OF(e,o,a,u):_F(e,o,a,u)}function sA(e,o,a,u){let m=a.oneOf.reduce((p,f)=>{let h=new Fn;return vt(e,h,f,u)?[...p,h]:p},[]);return v(m.length,1)&&o.Merge(m)}function iA(e,o,a,u,m,p){let f=[],h=[],I=m.oneOf.reduce((S,R,k)=>{let A=new jn,P=`${a}/oneOf/${k}`,M=pr(e,A,P,u,R,p);if(M)h.push(k);if(!M)f.push(A);return M?[...S,A]:S},[]),E=v(I.length,1)&&o.Merge(I);if(!E&&v(h.length,0))f.forEach((S)=>S.GetErrors().forEach((R)=>o.AddError(R)));return E||o.AddError({keyword:"oneOf",schemaPath:a,instancePath:u,params:{passingSchemas:h}})}function aA(e,o,a,u){let m=Uo(ht(a.pattern)?Is(a.pattern):a.pattern);return Ir(Et(m,"test"),[u])}function Kf(e,o,a,u){return(ht(a.pattern)?Is(a.pattern):a.pattern).test(u)}function uA(e,o,a,u,m,p){return Kf(e,o,m,p)||o.AddError({keyword:"pattern",schemaPath:a,instancePath:u,params:{pattern:m.pattern}})}function cA(e,o,a,u){return On(on(a.patternProperties).map(([m,p])=>{let[f,h]=[or(),or()],I=Uo(Is(m)),E=Bn(Ir(Et(I,"test"),[f])),S=Vn(e,o,p,h),R=o.AddKey(f),k=o.UseUnevaluated()?yr(E,An(S,R)):yr(E,S);return Cs(hy(u),Te(0),[`[${f}, ${h}]`,"_"],k)}))}function mA(e,o,a,u){return Zr(on(a.patternProperties),0,([m,p])=>{let f=Is(m);return Zr(on(u),0,([h,I])=>!f.test(h)||Oo(e,o,p,I)&&o.AddKey(h))})}function pA(e,o,a,u,m,p){return Mn(on(m.patternProperties),0,([f,h])=>{let I=`${a}/patternProperties/${f}`,E=Is(f);return Mn(on(p),0,([S,R])=>{let k=`${u}/${S}`;return!E.test(S)||_o(e,o,I,k,h,R)&&o.AddKey(S)})})}function lA(e,o,a,u){return On(a.prefixItems.map((m,p)=>{let f=na(Et(u,"length"),Te(p)),h=Vn(e,o,m,`${u}[${p}]`),I=o.AddIndex(Te(p)),E=o.UseUnevaluated()?An(h,I):h;return yr(f,E)}))}function dA(e,o,a,u){return v(u.length,0)||Zr(a.prefixItems,0,(m,p)=>$s(u.length,p)||Oo(e,o,m,u[p])&&o.AddIndex(p))}function fA(e,o,a,u,m,p){return v(p.length,0)||Mn(m.prefixItems,0,(f,h)=>{let I=`${a}/prefixItems/${h}`,E=`${u}/${h}`;return $s(p.length,h)||_o(e,o,I,E,f,p[h])&&o.AddIndex(h)})}function Gp(e,o){return e.includes(o)||ts().exactOptionalPropertyTypes}function hA(e,o){return ed(Et(e,o))}function Hf(e,o){return er(e[o])}function gA(e,o,a,u){let m=ys(a)?a.required:[],p=on(a.properties).map(([f,h])=>{let I=Bn(sa(u,Te(f))),E=Vn(e,o,h,Et(u,f)),S=o.AddKey(Te(f)),R=o.UseUnevaluated()?An(E,S):E,k=m.includes(f)?R:yr(I,R);return Gp(m,f)?k:yr(hA(u,f),k)});return On(p)}function yA(e,o,a,u){let m=ys(a)?a.required:[];return Zr(on(a.properties),0,([f,h])=>{let I=!me(u,f)||Oo(e,o,h,u[f])&&o.AddKey(f);return Gp(m,f)?I:Hf(u,f)||I})}function xA(e,o,a,u,m,p){let f=ys(m)?m.required:[];return Mn(on(m.properties),0,([I,E])=>{let S=`${a}/properties/${I}`,R=`${u}/${I}`,k=()=>!me(p,I)||_o(e,o,S,R,E,p[I])&&o.AddKey(I);return Gp(f,I)?k():Hf(p,I)||k()})}function IA(e,o,a,u){let[m,p]=[or(),or()];return Cs(oa(u),Te(0),[m,p],Ut(e,o,a.propertyNames,m))}function EA(e,o,a,u){return Zr(xe(u),0,(m,p)=>vt(e,o,a.propertyNames,m))}function bA(e,o,a,u,m,p){let f=[];return Mn(xe(p),0,(I,E)=>{let S=`${u}/${I}`,R=`${a}/propertyNames`,k=pr(e,o,R,S,m.propertyNames,I);if(!k)f.push(I);return k})||o.AddError({keyword:"propertyNames",schemaPath:a,instancePath:u,params:{propertyNames:f}})}function SA(e,o,a,u){let m=e.RecursiveRef(a)??!1;return mi(e,o,m,u)}function wA(e,o,a,u){let m=e.RecursiveRef(a)??!1;return Ye(m)&&vt(e,o,m,u)}function TA(e,o,a,u,m,p){let f=e.RecursiveRef(m)??!1;return Ye(f)&&pr(e,o,"#",u,f,p)}function LF(e,o,a,u){let m=xi(["context","value"],mi(e,o,a,"value")),p=xi(["context","value"],om([Qs("nextContext",rd("CheckContext",[])),Qs("result",Ir(m,["nextContext","value"])),yy("result",o.Merge("[nextContext]")),sm("result")]));return Ir(p,["context",u])}function NF(e,o,a,u){return mi(e,o,a,u)}function RA(e,o,a,u){let m=e.Ref(a)??!1;return o.UseUnevaluated()?LF(e,o,m,u):NF(e,o,m,u)}function kA(e,o,a,u){let m=e.Ref(a)??!1,p=new Fn,f=Ye(m)&&vt(e,p,m,u);if(f)o.Merge([p]);return f}function AA(e,o,a,u,m,p){let f=e.Ref(m)??!1,h=new jn,I=Ye(f)&&pr(e,h,"#",u,f,p);if(I)o.Merge([h]);if(!I)h.GetErrors().forEach((E)=>o.AddError(E));return I}function PA(e,o,a,u){return On(a.required.map((m)=>sa(u,Te(m))))}function $A(e,o,a,u){return Zr(a.required,0,(m)=>me(u,m))}function CA(e,o,a,u,m,p){let f=[];return Mn(m.required,0,(I)=>{let E=me(p,I);if(!E)f.push(I);return E})||o.AddError({keyword:"required",schemaPath:a,instancePath:u,params:{requiredProperties:f}})}function vA(e,o,a,u){return v(a,"object")?py(u):v(a,"array")?rm(u):v(a,"boolean")?sM(u):v(a,"integer")?iM(u):v(a,"number")?my(u):v(a,"null")?aM(u):v(a,"string")?dy(u):v(a,"bigint")?cy(u):v(a,"constructor")?mM(u):v(a,"function")?cM(u):v(a,"symbol")?uM(u):v(a,"undefined")?ed(u):v(a,"void")?ed(u):Te(!0)}function Wf(e,o,a,u,m){return v(a,"object")?Jo(m):v(a,"array")?$e(m):v(a,"boolean")?nn(m):v(a,"integer")?tm(m):v(a,"number")?Dt(m):v(a,"null")?Ao(m):v(a,"string")?ht(m):v(a,"bigint")?Fr(m):v(a,"constructor")?Jl(m):v(a,"function")?Ps(m):v(a,"symbol")?Ql(m):v(a,"undefined")?er(m):v(a,"void")?er(m):!0}function qF(e,o,a,u){return nd(a.map((m)=>vA(e,o,m,u)))}function MA(e,o,a,u,m){return Ma(a,(p)=>Wf(e,o,p,u,m))}function OA(e,o,a,u){return $e(a.type)?qF(e,o,a.type,u):vA(e,o,a.type,u)}function _A(e,o,a,u){return $e(a.type)?MA(e,o,a.type,a,u):Wf(e,o,a.type,a,u)}function LA(e,o,a,u,m,p){return($e(m.type)?MA(e,o,m.type,m,p):Wf(e,o,m.type,m,p))||o.AddError({keyword:"type",schemaPath:a,instancePath:u,params:{type:m.type}})}function NA(e,o,a,u){let[m,p]=[or(),or()],f=Ir(Et("context","GetIndices"),[]),h=Ir(Et("indices","has"),[m]),I=Ut(e,o,a.unevaluatedItems,p),E=Ir(Et("context","AddIndex"),[m]),S=Cs(u,Te(0),[p,m],An(yr(h,I),E));return Ir(xi(["context"],om([Qs("indices",f),sm(S)])),["context"])}function qA(e,o,a,u){let m=o.GetIndices();return Zr(u,0,(p,f)=>(m.has(f)||vt(e,o,a.unevaluatedItems,p))&&o.AddIndex(f))}function DA(e,o,a,u,m,p){let f=o.GetIndices(),h=[];return Mn(p,0,(E,S)=>{let R=new jn,k=(f.has(S)||pr(e,R,a,u,m.unevaluatedItems,E))&&o.AddIndex(S);if(!k)h.push(S);return k})||o.AddError({keyword:"unevaluatedItems",schemaPath:a,instancePath:u,params:{unevaluatedItems:h}})}function FA(e,o,a,u){let[m,p]=[or(),or()],f=Ir(Et("context","GetKeys"),[]),h=Ir(Et("keys","has"),[m]),I=Ir(Et("context","AddKey"),[m]),E=Ut(e,o,a.unevaluatedProperties,p),S=Cs(hy(u),Te(0),[`[${m}, ${p}]`,"_"],yr(h,An(E,I)));return Ir(xi(["context"],om([Qs("keys",f),sm(S)])),["context"])}function jA(e,o,a,u){let m=o.GetKeys();return Zr(on(u),0,([p,f])=>m.has(p)||vt(e,o,a.unevaluatedProperties,f)&&o.AddKey(p))}function UA(e,o,a,u,m,p){let f=o.GetKeys(),h=[];return Mn(on(p),0,([E,S])=>{let R=new jn,k=f.has(E)||pr(e,R,a,u,m.unevaluatedProperties,S)&&o.AddKey(E);if(!k)h.push(E);return k})||o.AddError({keyword:"unevaluatedProperties",schemaPath:a,instancePath:u,params:{unevaluatedProperties:h}})}function zf(e){return!v(e.uniqueItems,!1)}function BA(e,o,a,u){if(!zf(a))return Te(!0);let m=Et(rd("Set",[Ir(Et(u,"map"),[Et("Hashing","Hash")])]),"size"),p=Et(u,"length");return bo(m,p)}function GA(e,o,a,u){if(!zf(a))return!0;let m=new Set(u.map(id)).size,p=u.length;return v(m,p)}function KA(e,o,a,u,m,p){if(!zf(m))return!0;let f=new Set,h=p.reduce((E,S,R)=>{let k=id(S);if(f.has(k))return[...E,R];return f.add(k),E},[]);return v(h.length,0)||o.AddError({keyword:"uniqueItems",schemaPath:a,instancePath:u,params:{duplicateItems:h}})}function Nc(e,o){return Mc(e)&&($e(e.type)&&ta(e.type.length,0)&&Zr(e.type,0,(a)=>v(a,o))||v(e.type,o))}function DF(e){return Nc(e,"object")}function FF(e){return In(e)&&(Fo(e)||fc(e)||hc(e)||ru(e)||ci(e)||ui(e)||ou(e)||wa(e)||Tc(e)||ys(e)||ji(e))}function jF(e){return Nc(e,"array")}function UF(e){return In(e)&&(tu(e)||si(e)||Ks(e)||Sc(e)||nu(e)||ai(e)||Oi(e)||gs(e)||Li(e)||_i(e))}function BF(e){return Nc(e,"string")}function GF(e){return In(e)&&(Sa(e)||wc(e)||ba(e)||Ta(e))}function KF(e){return Nc(e,"number")||Nc(e,"bigint")}function HF(e){return In(e)&&(hs(e)||bc(e)||xc(e)||fs(e)||Rc(e))}function Vn(e,o,a,u){return o.UseUnevaluated()?An(An(o.Push(),Ut(e,o,a,u)),o.Pop()):Ut(e,o,a,u)}function Ut(e,o,a,u){e.Push(a);let m=[];if(Zs(a))return TR(e,o,a,u);if(Mc(a))m.push(OA(e,o,a,u));if(FF(a)){let f=[];if(ys(a))f.push(PA(e,o,a,u));if(Fo(a))f.push(hR(e,o,a,u));if(fc(a))f.push(vR(e,o,a,u));if(hc(a))f.push(_R(e,o,a,u));if(ru(a))f.push(qR(e,o,a,u));if(ui(a))f.push(cA(e,o,a,u));if(ci(a))f.push(gA(e,o,a,u));if(ou(a))f.push(IA(e,o,a,u));if(wa(a))f.push(Yk(e,o,a,u));if(Tc(a))f.push(Uk(e,o,a,u));let h=On(f),I=yr(Bn(py(u)),h);m.push(DF(a)?h:I)}if(UF(a)){let f=[];if(tu(a))f.push(lR(e,o,a,u));if(Ks(a))f.push($R(e,o,a,u));if(si(a))f.push($k(e,o,a,u));if(Sc(a))f.push(Ok(e,o,a,u));if(nu(a))f.push(qk(e,o,a,u));if(ai(a))f.push(Kk(e,o,a,u));if(Oi(a))f.push(Vk(e,o,a,u));if(gs(a))f.push(lA(e,o,a,u));if(_i(a))f.push(BA(e,o,a,u));let h=On(f),I=yr(Bn(rm(u)),h);m.push(jF(a)?h:I)}if(GF(a)){let f=[];if(wc(a))f.push(Fk(e,o,a,u));if(Sa(a))f.push(Qk(e,o,a,u));if(ba(a))f.push(Tk(e,o,a,u));if(Ta(a))f.push(aA(e,o,a,u));let h=On(f),I=yr(Bn(dy(u)),h);m.push(BF(a)?h:I)}if(HF(a)){let f=[];if(xc(a))f.push(HR(e,o,a,u));if(fs(a))f.push(zR(e,o,a,u));if(bc(a))f.push(Lk(e,o,a,u));if(hs(a))f.push(Wk(e,o,a,u));if(Rc(a))f.push(eA(e,o,a,u));let h=On(f),I=yr(Bn(yr(my(u),cy(u))),h);m.push(KF(a)?h:I)}if(Cc(a))m.push(RA(e,o,a,u));if($c(a))m.push(SA(e,o,a,u));if(gc(a))m.push(jR(e,o,a,u));if(dp(a))m.push(kR(e,o,a,u));if(fp(a))m.push(GR(e,o,a,u));if(Ic(a))m.push(kk(e,o,a,u));if(kc(a))m.push(rA(e,o,a,u));if(pc(a))m.push(xR(e,o,a,u));if(dc(a))m.push(bR(e,o,a,u));if(Ac(a))m.push(oA(e,o,a,u));if(Li(a))m.push(yr(Bn(rm(u)),NA(e,o,a,u)));if(ji(a))m.push(yr(Bn(ly(u)),FA(e,o,a,u)));if(mc(a))m.push(cR(e,o,a,u));let p=On(m);return e.Pop(a),p}function Oo(e,o,a,u){return o.Push()&&vt(e,o,a,u)&&o.Pop()}function vt(e,o,a,u){e.Push(a);let m=Zs(a)?If(e,o,a,u):(!Mc(a)||_A(e,o,a,u))&&(!(mt(u)&&!$e(u))||(!ys(a)||$A(e,o,a,u))&&(!Fo(a)||gR(e,o,a,u))&&(!fc(a)||MR(e,o,a,u))&&(!hc(a)||LR(e,o,a,u))&&(!ru(a)||DR(e,o,a,u))&&(!ui(a)||mA(e,o,a,u))&&(!ci(a)||yA(e,o,a,u))&&(!ou(a)||EA(e,o,a,u))&&(!wa(a)||Uf(e,o,a,u))&&(!Tc(a)||Nf(e,o,a,u)))&&(!$e(u)||(!tu(a)||dR(e,o,a,u))&&(!Ks(a)||bf(e,o,a,u))&&(!si(a)||Ck(e,o,a,u))&&(!Sc(a)||Mf(e,o,a,u))&&(!nu(a)||_f(e,o,a,u))&&(!ai(a)||qf(e,o,a,u))&&(!Oi(a)||Ff(e,o,a,u))&&(!gs(a)||dA(e,o,a,u))&&(!_i(a)||GA(e,o,a,u)))&&(!ht(u)||(!wc(a)||Lf(e,o,a,u))&&(!Sa(a)||jf(e,o,a,u))&&(!ba(a)||vf(e,o,a,u))&&(!Ta(a)||Kf(e,o,a,u)))&&(!(Dt(u)||Fr(u))||(!xc(a)||Tf(e,o,a,u))&&(!fs(a)||Rf(e,o,a,u))&&(!bc(a)||Of(e,o,a,u))&&(!hs(a)||Df(e,o,a,u))&&(!Rc(a)||Bf(e,o,a,u)))&&(!Cc(a)||kA(e,o,a,u))&&(!$c(a)||wA(e,o,a,u))&&(!gc(a)||UR(e,o,a,u))&&(!dp(a)||Ef(e,o,a,u))&&(!fp(a)||wf(e,o,a,u))&&(!Ic(a)||Ak(e,o,a,u))&&(!kc(a)||Gf(e,o,a,u))&&(!pc(a)||IR(e,o,a,u))&&(!dc(a)||SR(e,o,a,u))&&(!Ac(a)||sA(e,o,a,u))&&(!Li(a)||(!$e(u)||qA(e,o,a,u)))&&(!ji(a)||(!mt(u)||jA(e,o,a,u)))&&(!mc(a)||mR(e,o,a,u));return e.Pop(a),m}function _o(e,o,a,u,m,p){return o.Push()&&pr(e,o,a,u,m,p)&&o.Pop()}function pr(e,o,a,u,m,p){if(o.AtCapacity())return!1;e.Push(m);let f=Zs(m)?RR(e,o,a,u,m,p):!!(+(!Mc(m)||LA(e,o,a,u,m,p))&+(!(mt(p)&&!$e(p))||!!(+(!ys(m)||CA(e,o,a,u,m,p))&+(!Fo(m)||yR(e,o,a,u,m,p))&+(!fc(m)||OR(e,o,a,u,m,p))&+(!hc(m)||NR(e,o,a,u,m,p))&+(!ru(m)||FR(e,o,a,u,m,p))&+(!ui(m)||pA(e,o,a,u,m,p))&+(!ci(m)||xA(e,o,a,u,m,p))&+(!ou(m)||bA(e,o,a,u,m,p))&+(!wa(m)||Zk(e,o,a,u,m,p))&+(!Tc(m)||Bk(e,o,a,u,m,p))))&+(!$e(p)||!!(+(!tu(m)||fR(e,o,a,u,m,p))&+(!Ks(m)||CR(e,o,a,u,m,p))&+(!si(m)||vk(e,o,a,u,m,p))&+(!Sc(m)||_k(e,o,a,u,m,p))&+(!nu(m)||Dk(e,o,a,u,m,p))&+(!ai(m)||Hk(e,o,a,u,m,p))&+(!Oi(m)||Jk(e,o,a,u,m,p))&+(!gs(m)||fA(e,o,a,u,m,p))&+(!_i(m)||KA(e,o,a,u,m,p))))&+(!ht(p)||!!(+(!wc(m)||jk(e,o,a,u,m,p))&+(!Sa(m)||Xk(e,o,a,u,m,p))&+(!ba(m)||Rk(e,o,a,u,m,p))&+(!Ta(m)||uA(e,o,a,u,m,p))))&+(!(Dt(p)||Fr(p))||!!(+(!xc(m)||WR(e,o,a,u,m,p))&+(!fs(m)||VR(e,o,a,u,m,p))&+(!bc(m)||Nk(e,o,a,u,m,p))&+(!hs(m)||zk(e,o,a,u,m,p))&+(!Rc(m)||tA(e,o,a,u,m,p))))&+(!Cc(m)||AA(e,o,a,u,m,p))&+(!$c(m)||TA(e,o,a,u,m,p))&+(!gc(m)||BR(e,o,a,u,m,p))&+(!dp(m)||AR(e,o,a,u,m,p))&+(!fp(m)||KR(e,o,a,u,m,p))&+(!Ic(m)||Pk(e,o,a,u,m,p))&+(!kc(m)||nA(e,o,a,u,m,p))&+(!pc(m)||ER(e,o,a,u,m,p))&+(!dc(m)||wR(e,o,a,u,m,p))&+(!Ac(m)||iA(e,o,a,u,m,p))&+(!Li(m)||(!$e(p)||DA(e,o,a,u,m,p)))&+(!ji(m)||(!mt(p)||UA(e,o,a,u,m,p))))&&(!mc(m)||pR(e,o,a,u,m,p));return e.Pop(m),f}var HA=[0],Kp=new Map,qc=new Map;function WF(){return`${HA[0]++}`}function zF(e,o){if(!Kp.has(e))Kp.set(e,new Map);let a=Kp.get(e);if(a.has(o))return a.get(o);let u=WF();return a.set(o,u),u}function VF(e,o,a,u){return e.UseUnevaluated()?Ir(`check_${a}`,["context",u]):Ir(`check_${a}`,[u])}function JF(e,o,a,u){let m=Ut(e,o,a,"value");return o.UseUnevaluated()?Qs(`check_${u}`,xi(["context","value"],m)):Qs(`check_${u}`,xi(["value"],m))}function WA(){HA[0]=0,Kp.clear(),qc.clear()}function zA(){return[...qc.values()]}function mi(e,o,a,u){let m=zF(a,e.LexicalBaseURL()),p=VF(o,a,m,u);if(qc.has(m))return p;return qc.set(m,""),qc.set(m,JF(e,o,a,m)),p}function QF(e,o){return mt(o)&&!$u(e)?o[e]:void 0}function XF(e,o){return e.reduce((a,u)=>QF(u,a),o)}function YF(e){if(v(e.length,0))return[];let o=e.split("/").map((a)=>a.replace(/~1/g,"/").replace(/~0/g,"~"));return o.length>0&&o[0]===""?o.slice(1):o}function ZF(e,o){let a=YF(o);return XF(a,e)}var Wp="https://json-schema.org";function JA(e,o){if(mt(e)&&ei(e)&&v(e.$dynamicAnchor,o))return e;if(mt(e))for(let a of xe(e)){let u=JA(e[a],o);if(u)return u}return}function Vf(e,o,a){if(v(e,a))return o.href;let u=In(e)&&Mo(e)?new URL(e.$id,o.href):o;if($e(e))for(let m of e){let p=Vf(m,u,a);if(!er(p))return p}else if(mt(e))for(let m of xe(e)){let p=Vf(e[m],u,a);if(!er(p))return p}return}function e1(e,o,a){if(v(e.$id,a.hash))return e;let u=new URL(a.href,o.href);if(v(o.pathname,u.pathname))return a.hash.startsWith("#")?QA(e,a):e;return}function t1(e,o,a){let u=new URL(`#${e.$anchor}`,o.href),m=new URL(a.href,o.href);return v(u.href,m.href)?e:void 0}function r1(e,o,a){let u=new URL(`#${e.$dynamicAnchor}`,o.href),m=new URL(a.href,o.href);return v(u.href,m.href)?e:void 0}function QA(e,o){if(o.href.endsWith("#"))return e;if(!o.hash.startsWith("#"))return;let a=decodeURIComponent(o.hash.slice(1));if(!a.startsWith("/"))return;return ZF(e,a)}function n1(e,o,a){if(Mo(e)){let u=e1(e,o,a);if(!er(u))return u}if(lc(e)){let u=t1(e,o,a);if(!er(u))return u}if(ei(e)){let u=r1(e,o,a);if(!er(u))return u}return QA(e,a)}function o1(e,o,a){return e.reduce((u,m)=>{let p=zp(m,o,a);return!er(p)?p:u},void 0)}function s1(e){return v(e,"const")||v(e,"enum")}function i1(e,o,a){return xe(e).reduce((u,m)=>{if(s1(m))return u;let p=zp(e[m],o,a);return!er(p)?p:u},void 0)}function zp(e,o,a){let u=In(e)&&Mo(e)?new URL(e.$id,o.href):o;if(In(e)){let m=n1(e,u,a);if(!er(m))return m}if($e(e))return o1(e,u,a);if(mt(e))return i1(e,u,a);return}function a1(e,o,a){return Vf(e,new URL(o||".",Wp),a)}function u1(e,o,a,u){let m=Vp(e,o,a,u,!1);return In(m)&&Mo(m)?m:void 0}function VA(e){return e.href.split("#")[0]}function c1(e,o){return me(e,o)?e[o]:void 0}function m1(e,o,a){return zp(e,o,a)}function p1(e,o,a){let u=VA(a);if(v(u,VA(o)))return;if(!me(e,u))return;let m=e[u],p=In(m)&&Mo(m)?new URL(m.$id,u):new URL(u);return v(a.hash,"")?m:zp(m,p,a)}function l1(e,o,a,u,m){if(!u.$ref.startsWith("#"))return;if(me(e,"$schema"))return;let p=a1(o,a,m);if(er(p)||v(p,a))return;return{target:m,base:p,root:o}}function d1(e,o,a){let u=e[o];if(!In(u))return;return{target:a,base:o,root:u}}function f1(e,o,a,u,m){let p=m?d1(e.context,u,a):void 0;if(!er(p))return p;return l1(e.root,e.lexicalSchema,e.referenceBase,o,a)}function h1(e,o,a,u,m,p){if(Mo(m))return;let f=u1(e,o,a,u);if(!f||p.includes(f))return;return{target:m,resource:f}}function Vp(e,o,a,u,m=!0){let p=new URL(a||".",Wp),f=m&&Mo(o)?new URL(o.$id,p):p,h=new URL(u,f.href);return c1(e,u)??m1(o,f,h)??p1(e,f,h)}function g1(e,o,a,u,m,p){let f=new URL(a||".",Wp),h=m.$dynamicRef.startsWith("#")?u:o,I=Vp(e,h,a,m.$dynamicRef,!1);if(er(I)){let R=new URL(m.$dynamicRef,f).hash;if(!R.startsWith("#/")&&R.startsWith("#")){let k=decodeURIComponent(R.slice(1));return p.find((P)=>v(P.$dynamicAnchor,k))??JA(o,k)}return}if(!In(I)||!ei(I))return I;if(new URL(m.$dynamicRef,f).hash.startsWith("#/"))return I;return p.find((R)=>v(R.$dynamicAnchor,I.$dynamicAnchor))??I}function y1(e,o){let a=e.inRetrievedFrame?e.lexicalSchema:e.root,u=o.$ref.startsWith("#")?e.lexicalSchema:a,m=Vp(e.context,u,e.referenceBase,o.$ref,!1);if(!m||!In(m))return{schema:m};let p=new URL(o.$ref,e.referenceBase).href.split("#")[0],f=!v(p,e.resourceBase),h=f1(e,o,m,p,f),I=f?h1(e.context,e.root,e.referenceBase,p,m,e.ids):void 0;return{schema:m,retrievedResource:h,resolvedResource:I}}function x1(e,o){let a=Pc(e.lexicalSchema)?e.recursiveAnchors[0]:e.lexicalSchema;return Vp(e.context,a,e.lexicalBase,o.$recursiveRef,!1)}function I1(e,o){return g1(e.context,e.root,e.lexicalBase,e.lexicalSchema,o,e.dynamicAnchors)}var qr=function(e,o,a,u){if(a==="a"&&!u)throw TypeError("Private accessor was defined without a getter");if(typeof o==="function"?e!==o||!u:!o.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return a==="m"?u:a==="a"?u.call(e):u?u.value:o.get(e)},Rr,Qp,rP,Yf,Jp,XA,YA,ZA,eP,Qf,Xf,Zf,eh,tP,nP;class Wi{constructor(e,o){Rr.add(this),this.context=e,this.schema=o,this.ids=[],this.resourceIds=[],this.anchors=[],this.recursiveAnchors=[],this.dynamicAnchors=[],this.retrievedResources=new Map,this.retrievedFrames=[],this.resolvedResources=new Map,this.pendingResource=!0}LexicalBaseURL(){return qr(this,Rr,"m",Yf).call(this,this.ids)}Push(e){if(!In(e))return;if(Mo(e))qr(this,Rr,"m",Zf).call(this,e);if(lc(e))this.anchors.push(e);if(Pc(e))this.recursiveAnchors.push(e);if(ei(e))this.dynamicAnchors.push(e);let o=this.retrievedResources.get(e);if(o)this.retrievedFrames.push({schema:o.root,base:o.base,idDepth:this.ids.length,resourceDepth:this.resourceIds.length})}Pop(e){if(!In(e))return;if(Mo(e))qr(this,Rr,"m",eh).call(this,e);if(lc(e))this.anchors.pop();if(Pc(e))this.recursiveAnchors.pop();if(ei(e))this.dynamicAnchors.pop();if(this.retrievedResources.has(e))this.retrievedFrames.pop();qr(this,Rr,"m",nP).call(this,e)}Ref(e){let o=y1(qr(this,Rr,"m",Qp).call(this),e);return qr(this,Rr,"m",rP).call(this,o),o.schema}RecursiveRef(e){let o=x1(qr(this,Rr,"m",Qp).call(this),e);if(o)this.pendingResource=!0;return o}DynamicRef(e){let o=I1(qr(this,Rr,"m",Qp).call(this),e);if(o)this.pendingResource=!0;return o}}Rr=new WeakSet,Qp=function(){return{context:this.context,root:this.schema,ids:this.ids,lexicalSchema:qr(this,Rr,"m",YA).call(this),lexicalBase:this.LexicalBaseURL(),referenceBase:qr(this,Rr,"m",XA).call(this),resourceBase:qr(this,Rr,"m",Jp).call(this),recursiveAnchors:this.recursiveAnchors,dynamicAnchors:this.dynamicAnchors,inRetrievedFrame:this.retrievedFrames.length>0}},rP=function(o){if(!er(o.schema))this.pendingResource=!0;if(!er(o.resolvedResource))qr(this,Rr,"m",tP).call(this,o.resolvedResource.target,o.resolvedResource.resource);if(!er(o.retrievedResource))this.retrievedResources.set(o.retrievedResource.target,{base:o.retrievedResource.base,root:o.retrievedResource.root})},Yf=function(o){let a=this.retrievedFrames[this.retrievedFrames.length-1],u=a?new URL(a.base):new URL(Wp);return(a?o.slice(a.idDepth):o).reduce((p,f)=>new URL(f.$id,p),u).href},Jp=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(!o)return qr(this,Rr,"m",Yf).call(this,this.resourceIds);return this.resourceIds.slice(o.resourceDepth).reduce((a,u)=>new URL(u.$id,a),new URL(o.base)).href},XA=function(){if(this.retrievedFrames.length>0)return qr(this,Rr,"m",Jp).call(this);let o=this.ids[this.ids.length-1];if(o&&!/^[A-Za-z][A-Za-z0-9+.-]*:/.test(o.$id))return this.LexicalBaseURL();return qr(this,Rr,"m",Jp).call(this)},YA=function(){let o=this.retrievedFrames[this.retrievedFrames.length-1];if(o)return this.ids.length>o.idDepth?this.ids[this.ids.length-1]:o.schema;return this.ids.length>0?this.ids[this.ids.length-1]:this.schema},ZA=function(o){o.forEach((a)=>qr(this,Rr,"m",Qf).call(this,a,!1))},eP=function(o){o.forEach((a)=>qr(this,Rr,"m",Xf).call(this,a,!1))},Qf=function e(o,a=!0){if(Zs(o))return;if($e(o))return qr(this,Rr,"m",ZA).call(this,o);if(!In(o))return;let u=o;if(!a&&Mo(u))return;if(!a&&ei(u))this.dynamicAnchors.push(u);for(let m of xe(u))qr(this,Rr,"m",e).call(this,u[m],!1)},Xf=function e(o,a=!0){if(Zs(o))return;if($e(o))return qr(this,Rr,"m",eP).call(this,o);if(!In(o))return;let u=o;if(!a&&Mo(u))return;if(!a&&ei(u))this.dynamicAnchors.pop();for(let m of xe(u))qr(this,Rr,"m",e).call(this,u[m],!1)},Zf=function(o){this.ids.push(o);let a=this.pendingResource;if(this.pendingResource=!1,a)this.resourceIds.push(o);qr(this,Rr,"m",Qf).call(this,o,!0)},eh=function(o){if(this.ids.pop(),this.resourceIds.length>0&&v(this.resourceIds[this.resourceIds.length-1],o))this.resourceIds.pop();qr(this,Rr,"m",Xf).call(this,o,!0)},tP=function(o,a){qr(this,Rr,"m",Zf).call(this,a),this.resolvedResources.set(o,a)},nP=function(o){if(!this.resolvedResources.has(o))return;let a=this.resolvedResources.get(o);qr(this,Rr,"m",eh).call(this,a),this.resolvedResources.delete(o)};function E1(e){let o=e.Functions().join(`;
21
+ `),a=e.UseUnevaluated()?["const context = new CheckContext({}, {})",`return ${e.Entry()}`]:[`return ${e.Entry()}`];return`${o}; return (value) => { ${a.join("; ")} }`}function b1(e,o){return Ly("CheckContext","Guard","Format","Hashing",e.External().identifier,o)(Fn,O,cu,ca,e.External().variables)}function S1(e){let o=new Wi(e.Context(),e.Schema()),a=new Fn;return(u)=>vt(o,a,e.Schema(),u)}function w1(e,o){return _y()?b1(e,o):S1(e)}class oP{constructor(e,o,a){this.isAccelerated=e,this.code=o,this.check=a}IsAccelerated(){return this.isAccelerated}Code(){return this.code}Check(e){return this.check(e)}}class sP{constructor(e,o,a,u,m,p){this.context=e,this.schema=o,this.external=a,this.functions=u,this.entry=m,this.useUnevaluated=p}Context(){return this.context}Schema(){return this.schema}UseUnevaluated(){return this.useUnevaluated}External(){return this.external}Functions(){return this.functions}Entry(){return this.entry}Evaluate(){let e=E1(this),o=w1(this,e);return new oP(_y(),e,o)}}function Xp(...e){let[o,a]=Pn(e,{2:(I,E)=>[I,E],1:(I)=>[{},I]});aR(),WA();let u=new Wi(o,a),m=new gf(iR(o,a)),p=mi(u,m,a,"value"),f=zA(),h=uR();return new sP(o,a,h,f,p,m.UseUnevaluated())}function Yp(...e){let[o,a,u]=Pn(e,{3:(S,R,k)=>[S,R,k],2:(S,R)=>[{},S,R]}),m=new Wi(o,a),p=new jn,f=pr(m,p,"#","",a,u),h=p.GetErrors(),I=Ky(),E=h.map((S)=>({...S,message:I(S)}));return[f,E]}function rh(...e){let[o,a,u]=Pn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),m=new Wi(o,a),p=new Fn;return vt(m,p,a,u)}function ur(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return rh(o,a,u)}function Hs(...e){let[o,a,u]=Pn(e,{3:(f,h,I)=>[f,h,I],2:(f,h)=>[{},f,h]}),[m,p]=Yp(o,a,u);return p}class Ra extends Error{constructor(e,o,a){super(e);Object.defineProperty(this,"cause",{value:{source:e,errors:a,value:o},writable:!1,configurable:!1,enumerable:!1})}}function iP(e,o,a){if(!$e(a))return a;return a.map((u)=>En(e,o.items,u))}function aP(e,o,a){return En({...e,...o.$defs},en(o.$ref),a)}function k1(e,o){let a=me(o,"unevaluatedProperties")?{additionalProperties:o.unevaluatedProperties}:{},u=Do(e,o),m=Cn(u);return ze(m)?pp(m,a):m}function uP(e,o,a){let u=k1(e,o);return En(e,u,a)}function Zp(e){return me(e,"additionalProperties")?e.additionalProperties:void 0}function cP(e,o,a){if(!mt(a)||$e(a))return a;let u=Zp(o);for(let m of xe(a)){if(me(o.properties,m)){a[m]=En(e,o.properties[m],a[m]);continue}if(nn(u)&&v(u,!0)||Or(u)&&ur(e,u,a[m])){a[m]=En(e,u,a[m]);continue}delete a[m]}return a}function mP(e,o,a){if(!mt(a))return a;let u=Zp(o),[m,p]=[new RegExp(gn(o)),dr(o)];for(let f of xe(a)){if(m.test(f)){a[f]=En(e,p,a[f]);continue}if(nn(u)&&v(u,!0)||Or(u)&&ur(e,u,a[f])){a[f]=En(e,u,a[f]);continue}delete a[f]}return a}function pP(e,o,a){return me(e,o.$ref)?En(e,e[o.$ref],a):a}function lP(e,o,a){if(!$e(a))return a;let u=Math.min(a.length,o.items.length);for(let m=0;m<u;m++)a[m]=En(e,o.items[m],a[m]);return ta(a.length,u)?a.slice(0,u):a}function Kr(e){return _a(e)}function dP(e,o,a){for(let u of o.anyOf){let m=En(e,u,Kr(a));if(ur(e,u,m))return m}return a}function En(e,o,a){return At(o)?iP(e,o,a):ar(o)?aP(e,o,a):Ke(o)?uP(e,o,a):ze(o)?cP(e,o,a):tr(o)?mP(e,o,a):Xt(o)?pP(e,o,a):dt(o)?lP(e,o,a):ye(o)?dP(e,o,a):a}function A1(e,o){for(let a of xe(e)){if(me(o,a))continue;o[a]=e[a]}return o}function P1(e){let o={};for(let a of xe(e))o[a]=Dc(e[a]);return o}function $1(e){return nh(YT(e))}function nh(e){return e.map((o)=>Dc(o))}function Dc(e){let o=At(e)?F(Dc(e.items),La(e)):Ke(e)?Ln(nh(e.allOf)):ye(e)?g($1(e.anyOf)):ze(e)?l(P1(e.properties)):tr(e)?at(ki(e),Dc(dr(e))):dt(e)?Br(nh(e.items)):e;return A1(e,o)}function mu(e){return Dc(e)}function Bo(...e){let[o,a,u]=Pn(e,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]}),m=ts().unionPrioritySort?mu(a):a;return En(o,m,u)}function ko(e){return mt(e)&&me(e,"value")}function je(e){return{value:e}}function kr(){return}function C1(e){return $e(e)?je(e):je([e])}function v1(e){return v(e,!0)?je(BigInt(1)):je(BigInt(0))}var M1=/^-?(0|[1-9]\d*)n$/,O1=/^-?(0|[1-9]\d*)\.\d+$/,_1=/^-?(0|[1-9]\d*)$/;function L1(e){return M1.test(e)}function N1(e){return O1.test(e)}function q1(e){return _1.test(e)}function D1(e){let o=e.toLowerCase();return L1(e)?je(BigInt(e.slice(0,e.length-1))):N1(e)?je(BigInt(e.split(".")[0])):q1(e)?je(BigInt(e)):v(o,"false")?je(BigInt(0)):v(o,"true")?je(BigInt(1)):kr()}function el(e){return Fr(e)?je(e):nn(e)?v1(e):Dt(e)?je(BigInt(Math.trunc(e))):Ao(e)?je(BigInt(0)):ht(e)?D1(e):er(e)?je(BigInt(0)):kr()}function F1(e){return v(e,BigInt(0))?je(!1):v(e,BigInt(1))?je(!0):kr()}function j1(e){return v(e,0)?je(!1):v(e,1)?je(!0):kr()}function U1(e){return v(e.toLowerCase(),"false")?je(!1):v(e.toLowerCase(),"true")?je(!0):v(e,"0")?je(!1):v(e,"1")?je(!0):kr()}function fP(e){return Fr(e)?F1(e):nn(e)?je(e):Dt(e)?j1(e):Ao(e)?je(!1):ht(e)?U1(e):er(e)?je(!1):kr()}function B1(e){return v(e,BigInt(0))?je(null):kr()}function G1(e){return v(e,!1)?je(null):kr()}function K1(e){return v(e,0)?je(null):kr()}function H1(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?je(null):kr()}function W1(e){return Fr(e)?B1(e):nn(e)?G1(e):Dt(e)?K1(e):Ao(e)?je(null):ht(e)?H1(e):er(e)?je(null):kr()}var hP=BigInt(Number.MAX_SAFE_INTEGER),gP=BigInt(Number.MIN_SAFE_INTEGER);function z1(e){return e<=hP&&e>=gP?je(Number(e)):kr()}function V1(e){return je(e?1:0)}function J1(e){let o=+e;if(Dt(o))return je(o);let a=e.toLowerCase();if(v(a,"false"))return je(0);if(v(a,"true"))return je(1);let u=el(e);if(ko(u))return u.value<=hP&&u.value>=gP?je(Number(u.value)):kr();return kr()}function oh(e){return Fr(e)?z1(e):nn(e)?V1(e):Dt(e)?je(e):Ao(e)?je(0):ht(e)?J1(e):er(e)?je(0):kr()}function yP(e){return Fr(e)?je(e.toString()):nn(e)?je(e.toString()):Dt(e)?je(e.toString()):Ao(e)?je("null"):ht(e)?je(e):er(e)?je(""):kr()}function Q1(e){return v(e,BigInt(0))?je(void 0):kr()}function X1(e){return v(e,!1)?je(void 0):kr()}function Y1(e){return v(e,0)?je(void 0):kr()}function Z1(e){let o=e.toLowerCase();return v(o,"undefined")||v(o,"null")||v(e,"")||v(e,"0")?je(void 0):kr()}function xP(e){return Fr(e)?Q1(e):nn(e)?X1(e):Dt(e)?Y1(e):Ao(e)?je(void 0):ht(e)?Z1(e):er(e)?je(e):kr()}function IP(e,o,a){return C1(a).value.map((m)=>Hr(e,o.items,m))}function EP(e,o,a){let u=el(a);return ko(u)?u.value:a}function bP(e,o,a){let u=fP(a);return ko(u)?u.value:a}function SP(e,o,a){return Hr({...e,...o.$defs},en(o.$ref),a)}function wP(e,o,a){return Hr(e,Cn(o),a)}function TP(e,o,a){let u=oh(a);return ko(u)?Math.trunc(u.value):a}function RP(e,o,a){let u=Do(e,o),m=Cn(u);return Hr(e,m,a)}function ej(e,o,a){let u=el(a);return ko(u)&&v(o.const,u.value)?u.value:a}function tj(e,o,a){let u=fP(a);return ko(u)&&v(o.const,u.value)?u.value:a}function rj(e,o,a){let u=oh(a);return ko(u)&&v(o.const,u.value)?u.value:a}function nj(e,o,a){let u=yP(a);return ko(u)&&v(o.const,u.value)?u.value:a}function kP(e,o,a){if(v(o.const,a))return a;return ex(o)?ej(e,o,a):tx(o)?tj(e,o,a):hm(o)?rj(e,o,a):gm(o)?nj(e,o,a):Ur()}function AP(e,o,a){let u=W1(a);return ko(u)?u.value:a}function PP(e,o,a){let u=oh(a);return ko(u)?u.value:a}function tl(e,o,a,u){let m=xe(u);for(let[p,f]of o)for(let h of m)if(!p.test(h))u[h]=Hr(e,a,u[h]);return u}function Fc(e,o,a){return tn(e)&&er(a[o])}function oj(e,o,a){let u=Yl(o.properties),m=xe(a);for(let[p,f]of u)for(let h of m){if(!p.test(h)||Fc(f,h,a))continue;a[h]=Hr(e,f,a[h])}return me(o,"additionalProperties")&&mt(o.additionalProperties)?tl(e,u,o.additionalProperties,a):a}function $P(e,o,a){return Jo(a)?oj(e,o,a):a}function sj(e,o,a){let u=Yl(o.patternProperties),m=xe(a);for(let[p,f]of u)for(let h of m)if(p.test(h))a[h]=Hr(e,f,a[h]);return me(o,"additionalProperties")&&mt(o.additionalProperties)?tl(e,u,o.additionalProperties,a):a}function CP(e,o,a){return Jo(a)?sj(e,o,a):a}function vP(e,o,a){return me(e,o.$ref)?Hr(e,e[o.$ref],a):a}function MP(e,o,a){let u=yP(a);return ko(u)?u.value:a}function OP(e,o,a){return Hr(e,Cn(o),a)}function _P(e,o,a){if(!$e(a))return a;for(let u=0;u<Math.min(o.items.length,a.length);u++)a[u]=Hr(e,o.items[u],a[u]);return a}function LP(e,o,a){let u=xP(a);return ko(u)?u.value:a}function NP(e,o,a){if(o.anyOf.some((f)=>ur(e,f,a)))return a;let p=o.anyOf.map((f)=>Hr(e,f,Kr(a))).find((f)=>ur(e,o,f));return er(p)?a:p}function qP(e,o,a){let u=xP(a);return ko(u)?void 0:a}function Hr(e,o,a){return At(o)?IP(e,o,a):wo(o)?EP(e,o,a):Wn(o)?bP(e,o,a):ar(o)?SP(e,o,a):Xr(o)?wP(e,o,a):hn(o)?TP(e,o,a):Ke(o)?RP(e,o,a):gt(o)?kP(e,o,a):Ds(o)?AP(e,o,a):$r(o)?PP(e,o,a):ze(o)?$P(e,o,a):tr(o)?CP(e,o,a):Xt(o)?vP(e,o,a):Yr(o)?MP(e,o,a):mr(o)?OP(e,o,a):dt(o)?_P(e,o,a):ps(o)?LP(e,o,a):ye(o)?NP(e,o,a):To(o)?qP(e,o,a):a}function Ts(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Hr(o,a,u)}function DP(e,o,a){if(!$e(a))return a;for(let u=0;u<a.length;u++)a[u]=bn(e,o.items,a[u]);return a}function FP(e,o,a){return bn({...e,...o.$defs},en(o.$ref),a)}function jP(e,o){if(!er(o))return o;return Ps(e.default)?e.default():Kr(e.default)}function UP(e,o,a){let u=Do(e,o),m=Cn(u);return bn(e,m,a)}function BP(e,o,a){if(!mt(a))return a;let u=xe(o.properties);for(let m of u){let p=bn(e,o.properties[m],a[m]);if(er(p)&&(tn(o.properties[m])||!me(o.properties[m],"default")))continue;a[m]=p}if(!Fo(o)||nn(o.additionalProperties))return a;for(let m of xe(a)){if(u.includes(m))continue;a[m]=bn(e,o.additionalProperties,a[m])}return a}function GP(e,o,a){if(!mt(a))return a;let[u,m]=[new RegExp(gn(o)),dr(o)];for(let p of xe(a)){if(!(u.test(p)&&vo(m)))continue;a[p]=bn(e,m,a[p])}if(!Fo(o))return a;for(let p of xe(a)){if(u.test(p))continue;a[p]=bn(e,o.additionalProperties,a[p])}return a}function KP(e,o,a){return me(e,o.$ref)?bn(e,e[o.$ref],a):a}function HP(e,o,a){if(!$e(a))return a;let[u,m]=[o.items,Math.max(o.items.length,a.length)];for(let p=0;p<m;p++)if(p<u.length)a[p]=bn(e,u[p],a[p]);return a}function WP(e,o,a){for(let u of o.anyOf){let m=bn(e,u,Kr(a));if(ur(e,u,m))return m}return a}function bn(e,o,a){let u=vo(o)?jP(o,a):a;return At(o)?DP(e,o,u):ar(o)?FP(e,o,u):Ke(o)?UP(e,o,u):ze(o)?BP(e,o,u):tr(o)?GP(e,o,u):Xt(o)?KP(e,o,u):dt(o)?HP(e,o,u):ye(o)?WP(e,o,u):u}function pi(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return bn(o,a,u)}function pu(e){return(...o)=>{let[a,u,m]=Pn(o,{3:(p,f,h)=>[p,f,h],2:(p,f)=>[{},p,f]});return e.reduce((p,f)=>f(a,u,p),m)}}function ij(e,o,a){return o["~codec"].decode(a)}function aj(e,o,a){return o["~codec"].encode(a)}function Pr(e,o,a,u){if(!Hn(a))return u;return v(e,"Decode")?ij(o,a,u):aj(o,a,u)}function uj(e,o,a,u){if(!$e(u))return u;for(let m=0;m<u.length;m++)u[m]=Mr(e,o,a.items,u[m]);return Pr(e,o,a,u)}function cj(e,o,a,u){let m=Pr(e,o,a,u);if(!$e(m))return m;for(let p=0;p<m.length;p++)m[p]=Mr(e,o,a.items,m[p]);return m}function zP(e,o,a,u){return v(e,"Decode")?uj(e,o,a,u):cj(e,o,a,u)}function VP(e,o,a,u){return u=Mr(e,{...o,...a.$defs},en(a.$ref),u),Pr(e,o,a,u)}function JP(e){return e.reduce((o,a)=>({...o,...a}),{})}function QP(e,o){for(let a of o)if(!Oa(e,a))return a;return e}function mj(e,o,a,u){if(v(a.allOf.length,0))return Pr(e,o,a,u);let m=a.allOf.map((h)=>Mr(e,o,h,Bo(h,Kr(u)))),f=m.every((h)=>mt(h))?JP(m):QP(u,m);return Pr(e,o,a,f)}function pj(e,o,a,u){if(v(a.allOf.length,0))return Pr(e,o,a,u);let m=Pr(e,o,a,u),p=a.allOf.map((h)=>Mr(e,o,h,Bo(h,Kr(m))));if(p.every((h)=>mt(h)))return JP(p);return QP(m,p)}function XP(e,o,a,u){return v(e,"Decode")?mj(e,o,a,u):pj(e,o,a,u)}function lj(e,o,a,u){if(!Jo(u))return u;for(let m of xe(a.properties)){if(!me(u,m)||Fc(a.properties[m],m,u))continue;u[m]=Mr(e,o,a.properties[m],u[m])}return Pr(e,o,a,u)}function dj(e,o,a,u){let m=Pr(e,o,a,u);if(!Jo(m))return m;for(let p of xe(a.properties)){if(!me(m,p)||Fc(a.properties[p],p,m))continue;m[p]=Mr(e,o,a.properties[p],m[p])}return m}function YP(e,o,a,u){return v(e,"Decode")?lj(e,o,a,u):dj(e,o,a,u)}function fj(e,o,a,u){if(!Jo(u))return u;let m=new RegExp(gn(a));for(let p of xe(u)){if(!m.test(p))continue;u[p]=Mr(e,o,dr(a),u[p])}return Pr(e,o,a,u)}function hj(e,o,a,u){let m=Pr(e,o,a,u);if(!Jo(m))return m;let p=new RegExp(gn(a));for(let f of xe(m)){if(!p.test(f))continue;m[f]=Mr(e,o,dr(a),m[f])}return m}function ZP(e,o,a,u){return v(e,"Decode")?fj(e,o,a,u):hj(e,o,a,u)}function e$(e,o,a,u){return me(o,a.$ref)?Mr(e,o,o[a.$ref],u):u}function t$(e,o,a,u){return v(e,"Decode")?Pr(e,o,a,e$(e,o,a,u)):e$(e,o,a,Pr(e,o,a,u))}function gj(e,o,a,u){if(!$e(u))return u;for(let m=0;m<Math.min(a.items.length,u.length);m++)u[m]=Mr(e,o,a.items[m],u[m]);return Pr(e,o,a,u)}function yj(e,o,a,u){let m=Pr(e,o,a,u);if(!$e(m))return u;for(let p=0;p<Math.min(a.items.length,m.length);p++)m[p]=Mr(e,o,a.items[p],m[p]);return m}function r$(e,o,a,u){return v(e,"Decode")?gj(e,o,a,u):yj(e,o,a,u)}function xj(e,o,a,u){for(let m of a.anyOf){if(!ur(o,m,u))continue;let p=Mr(e,o,m,u);return Pr(e,o,a,p)}return u}function Ij(e,o,a,u){let m=Pr(e,o,a,u);for(let p of a.anyOf){let f=Mr(e,o,p,Kr(m));if(!ur(o,p,f))continue;return f}return m}function n$(e,o,a,u){return v(e,"Decode")?xj(e,o,a,u):Ij(e,o,a,u)}function Mr(e,o,a,u){return At(a)?zP(e,o,a,u):ar(a)?VP(e,o,a,u):Ke(a)?XP(e,o,a,u):ze(a)?YP(e,o,a,u):tr(a)?ZP(e,o,a,u):Xt(a)?t$(e,o,a,u):dt(a)?r$(e,o,a,u):ye(a)?n$(e,o,a,u):Pr(e,o,a,u)}class o$ extends Ra{constructor(e,o){super("Decode",e,o)}}function Ej(e,o,a){if(!ur(e,o,a))throw new o$(a,Hs(e,o,a));return a}function bj(e,o,a){let u=ts().unionPrioritySort?mu(o):o;return Mr("Decode",e,u,a)}var Sj=pu([(e,o,a)=>Kr(a),(e,o,a)=>pi(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Bo(e,o,a),(e,o,a)=>Ej(e,o,a),(e,o,a)=>bj(e,o,a)]);function sh(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Sj(o,a,u)}class s$ extends Ra{constructor(e,o){super("Encode",e,o)}}function wj(e,o,a){if(!ur(e,o,a))throw new s$(a,Hs(e,o,a));return a}function Tj(e,o,a){let u=ts().unionPrioritySort?mu(o):o;return Mr("Encode",e,u,a)}var Rj=pu([(e,o,a)=>Kr(a),(e,o,a)=>Tj(e,o,a),(e,o,a)=>pi(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Bo(e,o,a),(e,o,a)=>wj(e,o,a)]);function ih(...e){let[o,a,u]=Pn(e,{3:(m,p,f)=>[m,p,f],2:(m,p)=>[{},m,p]});return Rj(o,a,u)}function kj(e,o){return Hn(o)||Vi(e,o.items)}function Aj(e,o){return Hn(o)||i$({...e,...o.$defs},en(o.$ref))}function Pj(e,o){return Hn(o)||o.allOf.some((a)=>Vi(e,a))}function $j(e,o){return Hn(o)||xe(o.properties).some((a)=>Vi(e,o.properties[a]))}function Cj(e,o){return Hn(o)||Vi(e,dr(o))}function i$(e,o){if(ah.has(o.$ref))return!1;return ah.add(o.$ref),Hn(o)||me(e,o.$ref)&&Vi(e,e[o.$ref])}function vj(e,o){return Hn(o)||o.items.some((a)=>Vi(e,a))}function Mj(e,o){return Hn(o)||o.anyOf.some((a)=>Vi(e,a))}function Vi(e,o){return At(o)?kj(e,o):ar(o)?Aj(e,o):Ke(o)?Pj(e,o):ze(o)?$j(e,o):tr(o)?Cj(e,o):Xt(o)?i$(e,o):dt(o)?vj(e,o):ye(o)?Mj(e,o):Hn(o)}var ah=new Set;function uh(...e){let[o,a]=Pn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return ah.clear(),Vi(o,a)}class Rs extends Error{constructor(e,o){super(o);this.type=e}}function a$(e,o){return Ps(o.default)?o.default(o):mt(o.default)?Kr(o.default):o.default}function u$(e,o){if(_i(o)&&!vo(o))throw new Rs(o,"Arrays with uniqueItems constraints must specify a default annotation");let a=Oi(o)?o.minItems:0;return Array.from({length:a},()=>Wr(e,o.items))}function c$(e,o){return fs(o)?BigInt(o.exclusiveMinimum)+BigInt(1):hs(o)?BigInt(o.minimum):BigInt(0)}function m$(e,o){return!1}function p$(e,o){let a=Wr(e,o.instanceType);return class{constructor(){Object.assign(this,a)}}}function l$(e,o){return Wr({...e,...o.$defs},en(o.$ref))}function d$(e,o){return Wr(e,Cn(o))}function f$(e,o){let a=Wr(e,o.returnType);return()=>a}function h$(e,o){return fs(o)&&Dt(o.exclusiveMinimum)?o.exclusiveMinimum+1:hs(o)?o.minimum:0}function g$(e,o){let a=Do(e,o),u=Cn(a);return Wr(e,u)}function y$(e,o){return o.const}function x$(e,o){throw new Rs(o,"Cannot create TNever types")}function I$(e,o){return null}function E$(e,o){return fs(o)&&Dt(o.exclusiveMinimum)?o.exclusiveMinimum+1:hs(o)?o.minimum:0}function b$(e,o){return(er(o.required)?[]:o.required).reduce((u,m)=>({...u,[m]:Wr(e,o.properties[m])}),{})}function S$(e,o){if(wa(o)&&!vo(o))throw new Rs(o,"Record with the minProperties constraint must have a default annotation");return{}}function w$(e,o){return me(e,o.$ref)?Wr(e,e[o.$ref]):(()=>{throw new Rs(o,"Unable to deref Ref")})()}function T$(e,o){if((Ta(o)||ba(o))&&!vo(o))throw Error("Strings with format or pattern constraints must specify default");let u=Sa(o)?o.minLength:0;return"".padEnd(u)}function R$(e,o){return Symbol()}function k$(e,o){let a=Du(o.pattern);if(Yr(a))throw new Rs(o,"Unable to create TemplateLiteral due to infinite type expansion");return Wr(e,a)}function A$(e,o){return Array.from({length:o.minItems},(a,u)=>Wr(e,o.items[u]))}function P$(e,o){return}function $$(e,o){if(v(o.anyOf.length,0))throw Error("Unable to create Union with no variants");return Wr(e,o.anyOf[0])}function C$(e,o){return}function Wr(e,o){return vo(o)?a$(e,o):At(o)?u$(e,o):wo(o)?c$(e,o):Wn(o)?m$(e,o):zr(o)?p$(e,o):ar(o)?l$(e,o):Xr(o)?d$(e,o):Vr(o)?f$(e,o):hn(o)?h$(e,o):Ke(o)?g$(e,o):gt(o)?y$(e,o):So(o)?x$(e,o):Ds(o)?I$(e,o):$r(o)?E$(e,o):ze(o)?b$(e,o):tr(o)?S$(e,o):Xt(o)?w$(e,o):Yr(o)?T$(e,o):Fs(o)?R$(e,o):mr(o)?k$(e,o):dt(o)?A$(e,o):ps(o)?P$(e,o):ye(o)?$$(e,o):To(o)?C$(e,o):void 0}function Ws(...e){let[o,a]=Pn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return Wr(o,a)}class rl extends Ra{constructor(e,o){super("Parse",e,o)}}function Oj(e,o,a){if(!ur(e,o,a))throw new rl(a,Hs(e,o,a));return a}var v$=pu([(e,o,a)=>Kr(a),(e,o,a)=>pi(e,o,a),(e,o,a)=>Ts(e,o,a),(e,o,a)=>Bo(e,o,a),(e,o,a)=>Oj(e,o,a)]);var Lj=l({type:i("insert"),path:s(),value:Y()}),Nj=Object({type:i("update"),path:s(),value:Y()}),qj=l({type:i("delete"),path:s()}),PMe=g([Lj,Nj,qj]);class nl{constructor(e,o){this.hasCodec=uh(e,o),this.buildResult=Xp(e,o),this.evaluateResult=this.buildResult.Evaluate()}IsAccelerated(){return this.evaluateResult.IsAccelerated()}Context(){return this.buildResult.Context()}Type(){return this.buildResult.Schema()}Code(){return this.evaluateResult.Code()}Check(e){return this.evaluateResult.Check(e)}Parse(e){if(this.Check(e))return e;if(ts().correctiveParse)return v$(this.Context(),this.Type(),e);throw new rl(e,this.Errors(e))}Errors(e){if(this.IsAccelerated()&&this.Check(e))return[];return Hs(this.Context(),this.Type(),e)}Clean(e){return Bo(this.Context(),this.Type(),e)}Convert(e){return Ts(this.Context(),this.Type(),e)}Create(){return Ws(this.Context(),this.Type())}Default(e){return pi(this.Context(),this.Type(),e)}Decode(e){return this.hasCodec?sh(this.Context(),this.Type(),e):this.Parse(e)}Encode(e){return this.hasCodec?ih(this.Context(),this.Type(),e):this.Parse(e)}}function mh(...e){let[o,a]=Pn(e,{2:(u,m)=>[u,m],1:(u)=>[{},u]});return new nl(o,a)}var O$=new WeakMap,jj=Symbol.for("TypeBox.Kind");function Uj(e){if(typeof e.type==="string")return[e.type];if(Array.isArray(e.type))return e.type.filter((o)=>typeof o==="string");return[]}function Bj(e,o){switch(o){case"number":return typeof e==="number";case"integer":return typeof e==="number"&&Number.isInteger(e);case"boolean":return typeof e==="boolean";case"string":return typeof e==="string";case"null":return e===null;case"array":return Array.isArray(e);case"object":return typeof e==="object"&&e!==null&&!Array.isArray(e);default:return!1}}function ph(e){try{return L$(e)}catch{return}}function Gj(e,o){switch(o){case"number":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isFinite(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"integer":{if(e===null)return 0;if(typeof e==="string"&&e.trim()!==""){let a=Number(e);if(Number.isInteger(a))return a}if(typeof e==="boolean")return e?1:0;return e}case"boolean":{if(e===null)return!1;if(typeof e==="string"){if(e==="true")return!0;if(e==="false")return!1}if(typeof e==="number"){if(e===1)return!0;if(e===0)return!1}return e}case"string":{if(e===null)return"";if(typeof e==="number"||typeof e==="boolean")return String(e);return e}case"null":{if(e===""||e===0||e===!1)return null;return e}default:return e}}function Kj(e,o){let a=o.properties,u=new Set(a?Object.keys(a):[]);if(a)for(let[m,p]of Object.entries(a)){if(!(m in e))continue;e[m]=Aa(e[m],p)}if(o.additionalProperties&&typeof o.additionalProperties==="object")for(let[m,p]of Object.entries(e)){if(u.has(m))continue;e[m]=Aa(p,o.additionalProperties)}}function Hj(e,o){if(Array.isArray(o.items)){for(let a=0;a<e.length;a++){let u=o.items[a];if(!u)continue;e[a]=Aa(e[a],u)}return}if(o.items&&typeof o.items==="object")for(let a=0;a<e.length;a++)e[a]=Aa(e[a],o.items)}function _$(e,o){for(let a of o)if(ph(a)?.Check(e))return e;for(let a of o){let u=structuredClone(e),m=Aa(u,a);if(ph(a)?.Check(m))return m}return e}function Aa(e,o){let a=e;if(Array.isArray(o.allOf))for(let p of o.allOf)a=Aa(a,p);if(Array.isArray(o.anyOf))a=_$(a,o.anyOf);if(Array.isArray(o.oneOf))a=_$(a,o.oneOf);let u=Uj(o),m=u.length>1&&u.some((p)=>Bj(a,p));if(u.length>0&&!m)for(let p of u){let f=Gj(a,p);if(f!==a){a=f;break}}if(u.includes("object")&&typeof a==="object"&&a!==null&&!Array.isArray(a))Kj(a,o);if(u.includes("array")&&Array.isArray(a))Hj(a,o);return a}function ol(e,o){if(Array.isArray(e)){if(Array.isArray(o.items))for(let m=0;m<e.length;m++){let p=o.items[m];if(p)ol(e[m],p)}else if(o.items)for(let m of e)ol(m,o.items);return}if(typeof e!=="object"||e===null||!o.properties)return;let a=e,u=new Set(o.required??[]);for(let[m,p]of Object.entries(o.properties)){if(!(m in a))continue;if(a[m]===null&&!u.has(m)&&typeof p.$ref!=="string"&&ph(p)?.Check(null)===!1)delete a[m];else ol(a[m],p)}}function L$(e){let o=e,a=O$.get(o);if(a)return a;let u=mh(e);return O$.set(o,u),u}function Wj(e){if(e.keyword==="required"){let u=e.params.requiredProperties?.[0];if(u){let m=e.instancePath.replace(/^\//,"").replace(/\//g,".");return m?`${m}.${u}`:u}}return e.instancePath.replace(/^\//,"").replace(/\//g,".")||"root"}function zj(e,o){let a=e.find((u)=>u.name===o.name);if(!a)throw Error(`Tool "${o.name}" not found`);return lu(a,o)}function lu(e,o){let a=structuredClone(o.arguments);ol(a,e.parameters),Ts(e.parameters,a);let u=L$(e.parameters);if(!Object.getOwnPropertySymbols(e.parameters).includes(jj)){let f=Aa(a,e.parameters);if(f!==a)if(typeof a==="object"&&a!==null&&typeof f==="object"&&f!==null){for(let h of Object.keys(a))delete a[h];Object.assign(a,f)}else return u.Check(f)?f:a}if(u.Check(a))return a;let m=u.Errors(a).map((f)=>` - ${Wj(f)}: ${f.message}`).join(`
22
+ `)||"Unknown validation error",p=`Validation failed for tool "${o.name}":
23
+ ${m}
24
+
25
+ Received arguments:
26
+ ${JSON.stringify(o.arguments,null,2)}`;throw Error(p)}var N$;function jc(){if(!N$)throw Error("No default stream function configured. Pass streamFn explicitly or call setDefaultStreamFn().");return N$}async function q$(e,o,a,u,m,p){let f=j$(o,e),h=[...f],I={...o,messages:[...o.messages,...f]};await u({type:"agent_start"}),await u({type:"turn_start"});for(let E of f)await u({type:"message_start",message:E}),await u({type:"message_end",message:E});return await F$(I,h,a,m,u,p??jc()),h}async function D$(e,o,a,u,m){if(e.messages.length===0)throw Error("Cannot continue: no messages in context");if(e.messages[e.messages.length-1].role==="assistant")throw Error("Cannot continue from message role: assistant");let p=[],f={...e};return await a({type:"agent_start"}),await a({type:"turn_start"}),await F$(f,p,o,u,a,m??jc()),p}async function F$(e,o,a,u,m,p){let f=e,h=a,I,E=!1,S=await h.getSteeringMessages?.()||[];while(!0){let R=!0;while(R||S.length>0){let A=[];if(I){let j=await h.prepareNextTurn?.(I);if(j)f=j.context??f,A=j.messages??[],h={...h,model:j.model??h.model,reasoning:j.thinkingLevel===void 0?h.reasoning:j.thinkingLevel==="off"?void 0:j.thinkingLevel};if(S.length===0)S=await h.getSteeringMessages?.()||[];await m({type:"turn_start"})}for(let j of j$(f,[...A,...S]))await m({type:"message_start",message:j}),await m({type:"message_end",message:j}),f.messages.push(j),o.push(j);S=[];let P=await h.prepareRequest?.({context:f,model:h.model,thinkingLevel:h.reasoning??"off"},u);if(P)f=P.context??f,h={...h,model:P.model??h.model,reasoning:P.thinkingLevel===void 0?h.reasoning:P.thinkingLevel==="off"?void 0:P.thinkingLevel};let M=await Jj(f,h,u,m,p);if(o.push(M),M.stopReason==="error"||M.stopReason==="aborted"){I={message:M,toolResults:[],context:f,newMessages:o},await h.finishTurn?.(I,u),await m({type:"turn_end",message:M,toolResults:[]}),await m({type:"agent_end",messages:o});return}let V=M.content.filter((j)=>j.type==="toolCall"),_=[];if(R=!1,V.length>0){let j=M.stopReason==="length"?await Qj(V,m):await Xj(f,M,h,u,m);_.push(...j.messages),R=!j.terminate;for(let X of _)f.messages.push(X),o.push(X)}I={message:M,toolResults:_,context:f,newMessages:o};let J=await h.finishTurn?.(I,u);if(await m({type:"turn_end",message:M,toolResults:_}),J?.action==="end"){await m({type:"agent_end",messages:o});return}if(E=J?.action==="continue",S=await h.getSteeringMessages?.()||[],R||S.length>0)E=!1}let k=await h.getFollowUpMessages?.()||[];if(k.length>0){E=!1,S=k;continue}if(E){E=!1;continue}break}await m({type:"agent_end",messages:o})}function j$(e,o){let a=-1;for(let S=o.length-1;S>=0;S--)if(o[S].role==="system"){a=S;break}let u=o[a],m=u?o.map((S,R)=>R===a?lh(u,Vj):S):o,p=ii(ce([...e.messages,...m]),(e.tools??[]).map(ct)),f=p.toolsAdded.length===0&&p.toolsRemoved.length===0;if(u){if(f&&!u.toolsAdded?.length&&!u.toolsRemoved?.length)return o;return m.map((S,R)=>R===a?lh(u,p):S)}if(f)return o;let h=lh({role:"system",content:"",timestamp:Date.now()},p),I=o.findIndex((S)=>S.role!=="system"),E=I===-1?o.length:I;return[...o.slice(0,E),h,...o.slice(E)]}var Vj={toolsAdded:[],toolsRemoved:[]};function lh(e,{toolsAdded:o,toolsRemoved:a}){let{toolsAdded:u,toolsRemoved:m,...p}=e;return{...p,...o.length>0?{toolsAdded:o}:{},...a.length>0?{toolsRemoved:a}:{}}}async function Jj(e,o,a,u,m){let p=e.messages;if(o.transformContext)p=await o.transformContext(p,a);let f=await o.convertToLlm(p),h=xt({messages:f}),I=(o.getApiKey?await o.getApiKey(o.model.provider):void 0)||o.apiKey,E=await m(o.model,h,{...o,apiKey:I,signal:a}),S=async()=>Object.assign(await E.result(),{thinkingLevel:o.reasoning??"off"}),R=null,k=!1;for await(let P of E)switch(P.type){case"start":R=P.partial,e.messages.push(R),k=!0,await u({type:"message_start",message:{...R}});break;case"text_start":case"text_delta":case"text_end":case"thinking_start":case"thinking_delta":case"thinking_end":case"toolcall_start":case"toolcall_delta":case"toolcall_end":if(R)R=P.partial,e.messages[e.messages.length-1]=R,await u({type:"message_update",assistantMessageEvent:P,message:{...R}});break;case"done":case"error":{let M=await S();if(k)e.messages[e.messages.length-1]=M;else e.messages.push(M);if(!k)await u({type:"message_start",message:{...M}});return await u({type:"message_end",message:M}),M}}let A=await S();if(k)e.messages[e.messages.length-1]=A;else e.messages.push(A),await u({type:"message_start",message:{...A}});return await u({type:"message_end",message:A}),A}async function Qj(e,o){let a=[];for(let u of e){await o({type:"tool_execution_start",toolCallId:u.id,toolName:u.name,args:u.arguments});let m={toolCall:u,result:di(`Tool call "${u.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),isError:!0};await Uc(m,o);let p=dh(m);await fh(p,o),a.push(p)}return{messages:a,terminate:!1}}async function Xj(e,o,a,u,m){let p=o.content.filter((h)=>h.type==="toolCall"),f=p.some((h)=>e.tools?.find((I)=>I.name===h.name)?.executionMode==="sequential");if(a.toolExecution==="sequential"||f)return Yj(e,o,p,a,u,m);return Zj(e,o,p,a,u,m)}async function Yj(e,o,a,u,m,p){let f=[],h=[];for(let I of a){await p({type:"tool_execution_start",toolCallId:I.id,toolName:I.name,args:I.arguments});let E=await B$(e,o,I,u,m),S;if(E.kind==="immediate")S={toolCall:I,result:E.result,isError:E.isError};else{let k=await K$(E,m,G$(I,p));S=await H$(e,o,E,k,u,m)}await Uc(S,p);let R=dh(S);if(await fh(R,p),f.push(S),h.push(R),m?.aborted)break}return{messages:h,terminate:U$(f)}}async function Zj(e,o,a,u,m,p){let f=[];for(let E of a){await p({type:"tool_execution_start",toolCallId:E.id,toolName:E.name,args:E.arguments});let S=await B$(e,o,E,u,m);if(S.kind==="immediate"){let R={toolCall:E,result:S.result,isError:S.isError};if(await Uc(R,p),f.push(R),m?.aborted)break;continue}if(f.push(async()=>{if(m?.aborted){let A={toolCall:E,result:di("Operation aborted"),isError:!0};return await Uc(A,p),A}let R=await K$(S,m,G$(E,p)),k=await H$(e,o,S,R,u,m);return await Uc(k,p),k}),m?.aborted)break}let h=await Promise.all(f.map((E)=>typeof E==="function"?E():Promise.resolve(E))),I=[];for(let E of h){let S=dh(E);await fh(S,p),I.push(S)}return{messages:I,terminate:U$(h)}}function U$(e){return e.length>0&&e.every((o)=>o.result.terminate===!0)}function eU(e,o){if(!e.prepareArguments)return o;let a=e.prepareArguments(o.arguments);if(a===o.arguments)return o;return{...o,arguments:a}}async function B$(e,o,a,u,m,p=e.tools??[]){let f=p.find((h)=>h.name===a.name);if(!f)return{kind:"immediate",result:di(`Tool ${a.name} not found`),isError:!0};try{let h=eU(f,a),I=lu(f,h);if(u.beforeToolCall){let E=await u.beforeToolCall({assistantMessage:o,toolCall:a,args:I,context:e},m);if(m?.aborted)return{kind:"immediate",result:di("Operation aborted"),isError:!0};if(E?.block){let S=di(E.reason||"Tool execution was blocked");if(E.terminate===!0)S.terminate=!0;return{kind:"immediate",result:S,isError:!0}}}if(m?.aborted)return{kind:"immediate",result:di("Operation aborted"),isError:!0};return{kind:"prepared",toolCall:a,tool:f,args:I}}catch(h){return{kind:"immediate",result:di(h instanceof Error?h.message:String(h)),isError:!0}}}function G$(e,o){return(a)=>o({type:"tool_execution_update",toolCallId:e.id,toolName:e.name,args:e.arguments,partialResult:a})}async function K$(e,o,a){let u=[],m=!0,p=performance.now(),f=()=>Math.round(performance.now()-p);try{let h=await e.tool.execute(e.toolCall.id,e.args,o,(E)=>{if(!m)return;u.push(Promise.resolve(a(E)))}),I=f();return m=!1,await Promise.all(u),{result:h,isError:h.isError===!0,durationMs:I}}catch(h){let I=f();return m=!1,await Promise.all(u),{result:di(h instanceof Error?h.message:String(h)),isError:!0,durationMs:I}}finally{m=!1}}async function H$(e,o,a,u,m,p){let{result:f,isError:h}=u;if(m.afterToolCall)try{let I=await m.afterToolCall({assistantMessage:o,toolCall:a.toolCall,args:a.args,result:f,isError:h,context:e},p);if(I){let E=I.structuredContent??(I.content?void 0:f.structuredContent);if(f={...f,content:I.content??f.content,details:I.details??f.details,usage:I.usage??f.usage,terminate:I.terminate??f.terminate},E===void 0)delete f.structuredContent;else f.structuredContent=E;h=I.isError??h}}catch(I){f=di(I instanceof Error?I.message:String(I)),h=!0}return{toolCall:a.toolCall,result:f,isError:h,durationMs:u.durationMs}}function di(e){return{content:[{type:"text",text:e}],details:{}}}async function Uc(e,o){await o({type:"tool_execution_end",toolCallId:e.toolCall.id,toolName:e.toolCall.name,result:e.result,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs}})}function dh(e){return{role:"toolResult",toolCallId:e.toolCall.id,toolName:e.toolCall.name,content:e.result.content??[],details:e.result.details,usage:e.result.usage,isError:e.isError,...e.durationMs===void 0?{}:{durationMs:e.durationMs},timestamp:Date.now()}}async function fh(e,o){await o({type:"message_start",message:e}),await o({type:"message_end",message:e})}function tU(e){return e.filter((o)=>o.role==="system"||o.role==="user"||o.role==="assistant"||o.role==="toolResult")}var rU={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},nU={id:"unknown",name:"unknown",api:"unknown",provider:"unknown",baseUrl:"",reasoning:!1,input:[],cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:0,maxTokens:0};function oU(e){let o=e?.tools?.slice()??[],a=e?.messages?.slice()??[],u=uo(e?.systemPrompt,o.map(ct));if(a[0]?.role!=="system"&&u)a.unshift(u);return{get systemPrompt(){return oi(a)},model:e?.model??nU,thinkingLevel:e?.thinkingLevel??"off",get tools(){return o},set tools(m){o=m.slice()},get messages(){return a},set messages(m){a=m.slice()},isStreaming:!1,streamingMessage:void 0,pendingToolCalls:new Set,errorMessage:void 0}}class hh{messages=[];mode;constructor(e){this.mode=e}enqueue(e){this.messages.push(e)}hasItems(){return this.messages.length>0}peek(){if(this.mode==="all")return this.messages.slice();let e=this.messages[0];return e?[e]:[]}drain(){let e=this.peek();return this.messages=this.messages.slice(e.length),e}clear(){this.messages=[]}}class gh{_state;listeners=new Set;steeringQueue;followUpQueue;convertToLlm;transformContext;streamFunction;getApiKey;onPayload;onResponse;onProviderStreamEvent;beforeToolCall;afterToolCall;finishTurn;prepareRequest;prepareNextTurn;prepareNextTurnWithContext;activeRun;sessionId;thinkingBudgets;transport;maxRetryDelayMs;toolExecution;constructor(e){let o=e??{};this._state=oU(o.initialState),this.convertToLlm=o.convertToLlm??tU,this.transformContext=o.transformContext,this.streamFunction=o.streamFn??jc(),this.getApiKey=o.getApiKey,this.onPayload=o.onPayload,this.onResponse=o.onResponse,this.onProviderStreamEvent=o.onProviderStreamEvent,this.beforeToolCall=o.beforeToolCall,this.afterToolCall=o.afterToolCall,this.finishTurn=o.finishTurn,this.prepareRequest=o.prepareRequest,this.prepareNextTurn=o.prepareNextTurn,this.prepareNextTurnWithContext=o.prepareNextTurnWithContext,this.steeringQueue=new hh(o.steeringMode??"one-at-a-time"),this.followUpQueue=new hh(o.followUpMode??"one-at-a-time"),this.sessionId=o.sessionId,this.thinkingBudgets=o.thinkingBudgets,this.transport=o.transport??"auto",this.maxRetryDelayMs=o.maxRetryDelayMs,this.toolExecution=o.toolExecution??"parallel"}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}get state(){return this._state}set steeringMode(e){this.steeringQueue.mode=e}get steeringMode(){return this.steeringQueue.mode}set followUpMode(e){this.followUpQueue.mode=e}get followUpMode(){return this.followUpQueue.mode}steer(e){this.steeringQueue.enqueue(e)}followUp(e){this.followUpQueue.enqueue(e)}clearSteeringQueue(){this.steeringQueue.clear()}clearFollowUpQueue(){this.followUpQueue.clear()}clearAllQueues(){this.clearSteeringQueue(),this.clearFollowUpQueue()}hasQueuedMessages(){return this.steeringQueue.hasItems()||this.followUpQueue.hasItems()}peekQueuedMessages(){let e=this.steeringQueue.peek();return e.length>0?e:this.followUpQueue.peek()}get signal(){return this.activeRun?.abortController.signal}abort(){this.activeRun?.abortController.abort()}waitForIdle(){return this.activeRun?.promise??Promise.resolve()}reset(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before resetting.");let e=vn(this._state.messages);this._state.messages=e?[e]:[],this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this._state.errorMessage=void 0,this.clearFollowUpQueue(),this.clearSteeringQueue()}async prompt(e,o){if(this.activeRun)throw Error("Agent is already processing a prompt. Use steer() or followUp() to queue messages, or wait for completion.");let a=this.normalizePromptInput(e,o);await this.runPromptMessages(a)}async continue(){if(this.activeRun)throw Error("Agent is already processing. Wait for completion before continuing.");let e=this._state.messages[this._state.messages.length-1];if(!e||this._state.messages.every((o)=>o.role==="system"))throw Error("No messages to continue from");if(e.role==="assistant"){let o=this.steeringQueue.drain();if(o.length>0){await this.runPromptMessages(o,{skipInitialSteeringPoll:!0});return}let a=this.followUpQueue.drain();if(a.length>0){await this.runPromptMessages(a);return}throw Error("Cannot continue from message role: assistant")}await this.runContinuation()}normalizePromptInput(e,o){if(Array.isArray(e))return e;if(typeof e!=="string")return[e];let a=[{type:"text",text:e}];if(o&&o.length>0)a.push(...o);return[{role:"user",content:a,timestamp:Date.now()}]}async runPromptMessages(e,o={}){await this.runWithLifecycle(async(a)=>{await q$(e,this.createContextSnapshot(),this.createLoopConfig(o),(u)=>this.processEvents(u),a,this.streamFunction)})}async runContinuation(){await this.runWithLifecycle(async(e)=>{await D$(this.createContextSnapshot(),this.createLoopConfig(),(o)=>this.processEvents(o),e,this.streamFunction)})}createContextSnapshot(){return{messages:this._state.messages.slice(),tools:this._state.tools.slice()}}createLoopConfig(e={}){let o=e.skipInitialSteeringPoll===!0;return{model:this._state.model,reasoning:this._state.thinkingLevel==="off"?void 0:this._state.thinkingLevel,sessionId:this.sessionId,onPayload:this.onPayload,onResponse:this.onResponse,onProviderStreamEvent:this.onProviderStreamEvent,transport:this.transport,thinkingBudgets:this.thinkingBudgets,maxRetryDelayMs:this.maxRetryDelayMs,toolExecution:this.toolExecution,beforeToolCall:this.beforeToolCall,afterToolCall:this.afterToolCall,finishTurn:this.finishTurn,prepareRequest:this.prepareRequest,prepareNextTurn:this.prepareNextTurnWithContext||this.prepareNextTurn?async(a)=>{if(this.prepareNextTurnWithContext)return await this.prepareNextTurnWithContext(a,this.signal);return await this.prepareNextTurn?.(this.signal)}:void 0,convertToLlm:this.convertToLlm,transformContext:this.transformContext,getApiKey:this.getApiKey,getSteeringMessages:async()=>{if(o)return o=!1,[];return this.steeringQueue.drain()},getFollowUpMessages:async()=>this.followUpQueue.drain()}}async runWithLifecycle(e){if(this.activeRun)throw Error("Agent is already processing.");let o=new AbortController,a=()=>{},u=new Promise((m)=>{a=m});this.activeRun={promise:u,resolve:a,abortController:o},this._state.isStreaming=!0,this._state.streamingMessage=void 0,this._state.errorMessage=void 0;try{await e(o.signal)}catch(m){await this.handleRunFailure(m,o.signal.aborted)}finally{this.finishRun()}}async handleRunFailure(e,o){let a={role:"assistant",content:[{type:"text",text:""}],api:this._state.model.api,provider:this._state.model.provider,model:this._state.model.id,usage:rU,stopReason:o?"aborted":"error",errorMessage:e instanceof Error?e.message:String(e),timestamp:Date.now()};await this.processEvents({type:"message_start",message:a}),await this.processEvents({type:"message_end",message:a}),await this.processEvents({type:"turn_end",message:a,toolResults:[]}),await this.processEvents({type:"agent_end",messages:[a]})}finishRun(){this._state.isStreaming=!1,this._state.streamingMessage=void 0,this._state.pendingToolCalls=new Set,this.activeRun?.resolve(),this.activeRun=void 0}async processEvents(e){switch(e.type){case"message_start":this._state.streamingMessage=e.message;break;case"message_update":this._state.streamingMessage=e.message;break;case"message_end":this._state.streamingMessage=void 0,this._state.messages.push(e.message);break;case"tool_execution_start":{let a=new Set(this._state.pendingToolCalls);a.add(e.toolCallId),this._state.pendingToolCalls=a;break}case"tool_execution_end":{let a=new Set(this._state.pendingToolCalls);a.delete(e.toolCallId),this._state.pendingToolCalls=a;break}case"turn_end":if(e.message.role==="assistant"&&e.message.errorMessage)this._state.errorMessage=e.message.errorMessage;break;case"agent_end":this._state.streamingMessage=void 0;break}let o=this.activeRun?.abortController.signal;if(!o)throw Error("Agent listener invoked outside active run");for(let a of this.listeners)await a(e,o)}}var sl=Symbol("basalt.rebind-fetch");function ve(e,...o){return Object.assign(e,{aliases:o})}function Pa(e){return e.replace(/[^a-zA-Z0-9]/g,"").toLowerCase()}function sU(e){let o=[],a="";for(let u of e){if(!/[a-zA-Z0-9]/.test(u)){if(a)o.push(a);a="";continue}if(u>="A"&&u<="Z"&&a&&!/[A-Z]$/.test(a))o.push(a),a="";a+=u}if(a)o.push(a);return o}function W$(e,o){if(e.some((P)=>P.name===o))return o;let a=e.map((P)=>P.name),u=(P)=>a.filter((M)=>Pa(M)===P),m=u(Pa(o));if(m.length===1&&m[0])return m[0];if(m.length>1)return o;let p=o.split(/[.:/]/).pop()??o,f=p===o?[]:u(Pa(p));if(f.length===1&&f[0])return f[0];let h=new Map;for(let P of e)for(let M of P.aliases??[]){let V=Pa(M);h.set(V,(h.get(V)??new Set).add(P.name))}let I=(P)=>[...new Set([...u(P),...h.get(P)??[]])],E=I(Pa(p));if(E.length===1&&E[0])return E[0];if(E.length>1)return o;let S=sU(p),R=new Set;S.forEach((P,M)=>{R.add(Pa(P));let V=S[M+1];if(V)R.add(Pa(P+V))});let k=new Set;for(let P of R)for(let M of I(P))k.add(M);let A=[...k];return A.length===1&&A[0]?A[0]:o}function T(e){return e}function kn(e,o){let a=o.indexOf("/");if(a<=0)return;return e.getModel(o.slice(0,a),o.slice(a+1))}function kt(e){return`${e.provider}/${e.id}`}function V$(e,o,a){let u=async(p,f)=>{try{if(o){let I=p instanceof Request?p:void 0;o({at:Date.now(),method:f?.method??I?.method??"GET",url:typeof p==="string"?p:p instanceof URL?p.toString():p.url,headers:z$(f?.headers??I?.headers),body:iU(f?.body!==void 0?f.body:I?.body??void 0)})}}catch{}let h=await e(p,f);if(a)try{let I=Date.now(),{status:E,statusText:S}=h,R=z$(h.headers);if(!h.body)return a({at:I,status:E,statusText:S,headers:R,body:""}),h;let k="",A=new TextDecoder,P=new TransformStream({transform(_,J){J.enqueue(_),k+=A.decode(_,{stream:!0}),a({at:I,status:E,statusText:S,headers:R,body:k})},flush(){k+=A.decode(),a({at:I,status:E,statusText:S,headers:R,body:k})}}),M=h.body.pipeThrough(P),V=new Response(M,h);try{Object.defineProperty(V,"url",{value:h.url})}catch{}return V}catch{}return h},m=typeof globalThis.fetch.preconnect==="function"?globalThis.fetch.preconnect.bind(globalThis.fetch):()=>{};return Object.assign(u,{preconnect:m,[sl]:(p)=>V$(p,o,a)})}function z$(e){if(!e||typeof e!=="object")return{};let o={};if(e instanceof Headers)return e.forEach((u,m)=>{o[m]=u}),o;let a=Array.isArray(e)?e:Object.entries(e);for(let u of a)if(Array.isArray(u)&&typeof u[0]==="string"&&typeof u[1]==="string")o[u[0]]=u[1];return o}function iU(e){if(e===void 0||e===null)return"";if(typeof e==="string")return e;if(e instanceof URLSearchParams)return e.toString();if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e))return new TextDecoder().decode(new Uint8Array(e.buffer,e.byteOffset,e.byteLength));return`<${typeof e==="object"&&typeof e.constructor==="function"?e.constructor.name:typeof e}: \u975E\u6587\u672C\u8BF7\u6C42\u4F53\uFF0C\u672A\u8BB0\u5F55\u539F\u6587>`}function aU(e,o){return W$(e,o)}function uU(e,o,a){let u=Date.now(),m=new WeakSet,p=(I)=>{if(!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;let E=Date.now(),S=Math.max(10,E-u);I.generationMs=S},f=async(I)=>{if(!a||!I||typeof I!=="object"||!("role"in I)||I.role!=="assistant")return;if(p(I),m.has(I))return;m.add(I),Object.assign(I,await a(I))},h=(I)=>{let E=I?.content;if(!Array.isArray(E))return;for(let S of E)if(S&&S.type==="toolCall"&&typeof S.name==="string")S.name=aU(o(),S.name)};return{async*[Symbol.asyncIterator](){for await(let I of e){let{partial:E,message:S}=I;h(E),await f(S),h(S),yield I}},result:async()=>{let I=await e.result();return p(I),await f(I),h(I),I}}}function Bc(e,o){let a=(o??[]).filter((h)=>h.kind==="path").map((h)=>`<file path=${JSON.stringify(h.data)} />`),u=(o??[]).filter((h)=>h.kind==="text").map((h)=>`<file name=${JSON.stringify(h.name)}>
27
+ ${h.data}
28
+ </file>`),m=(o??[]).filter((h)=>h.kind==="image").map((h)=>({type:"image",data:h.data,mimeType:h.mimeType})),p=(o??[]).filter((h)=>h.kind==="image"&&h.id).map((h)=>`<image id=${JSON.stringify(h.id)} name=${JSON.stringify(h.name)} />`);return{merged:[...a,...u,...p,...e.trim()?[e]:[]].join(`
29
+
30
+ `),images:m}}function yh(e,o){let{merged:a,images:u}=Bc(e,o);return{role:"user",content:u.length>0?[{type:"text",text:a},...u]:a,timestamp:Date.now()}}function J$(e){let o=new Set;for(let h of e.tools){let I=h.name.toLowerCase();if(o.has(I))throw Error(`Tool names collide ignoring case: ${h.name}`);o.add(I)}let a=new gh({initialState:{systemPrompt:e.systemPrompt,model:e.model,tools:e.tools,messages:e.history,thinkingLevel:e.thinkingLevel},streamFn:(h,I,E)=>{let{captureRequest:S,captureResponse:R}=e,k=S||R?{...E,fetch:V$(E?.fetch??globalThis.fetch,S?(P)=>S({...P,model:kt(h)}):void 0,R?(P)=>R({...P,model:kt(h)}):void 0)}:E,A=h.api==="openai-completions"||h.api==="openai-responses"?{...h,compat:{...h.compat,supportsDeveloperRole:!1}}:h;return uU(e.models.streamSimple(A,I,k),()=>a.state.tools,e.hooks.response)},convertToLlm:(h)=>h,sessionId:e.sessionID,onPayload:e.hooks.payload,transformContext:e.hooks.transformContext,finishTurn:async()=>{if(await e.hooks.boundary?.())return{action:"end"};return},prepareRequest:e.hooks.prepare?async({context:h,model:I})=>{let E=h.messages.findIndex((A)=>A.role!=="system"),S=h.messages.slice(0,E===-1?h.messages.length:E),R=e.hooks.prepare,k=e.hooks.tools?.()??h.tools;if(k){a.state.tools=k;let A=S[0];if(A?.role==="system")S[0]={...A,toolsAdded:k.map(ct),toolsRemoved:void 0}}return{context:{...h,tools:k,messages:await R(S,k,I)}}}:void 0}),u=new Map,m=new Map,p=new WeakSet,f;return a.subscribe((h)=>{if(h.type==="message_update"&&h.message.role==="assistant"){m.clear(),e.hooks.draft(Q$(h.message));return}if(h.type==="tool_execution_update"){let E=u.get(h.toolCallId)??Oe(h.toolName,h.args),S=Array.isArray(h.partialResult?.content)?h.partialResult.content.map((R)=>R.type==="text"&&typeof R.text==="string"?R.text:"").join(""):"";m.set(h.toolCallId,{type:"tool_call",id:h.toolCallId,name:E.name,input:E.input,...E.source?{source:E.source}:{},output:S}),e.hooks.draft([...m.values()]);return}if(h.type==="tool_execution_end"){if(m.delete(h.toolCallId))e.hooks.draft(m.size>0?[...m.values()]:null);return}if(h.type!=="message_end")return;if(p.has(h.message)){e.steerConsumed?.(h.message);return}let I=h.message.role==="user"&&f?{type:"user",text:f.text,...f.attachments?.length?{attachments:f.attachments}:{}}:cU(h.message);if(h.message.role==="user")f=void 0;if(I?.type==="assistant"){for(let E of I.parts)if(E.type==="tool_call")u.set(E.id,E)}if(I?.type==="tool_result"){let E=u.get(I.callID);if(E?.source)Object.assign(I,{name:E.name,source:E.source})}if(I)e.hooks.message(I,h.message);if(h.message.role==="assistant")e.hooks.draft(null)}),{agent:a,prompt:(h,I)=>{f={text:h,attachments:I};let{merged:E,images:S}=Bc(h,I);return a.prompt(E,S.length>0?S:void 0)},retry:async()=>{let h=a.state.messages;if(h.at(-1)?.role==="assistant")a.state.messages=h.slice(0,-1);await a.continue()},resume:()=>a.continue(),steer:(h)=>{p.add(h),a.steer(h)},unsteer:(h)=>{let E=a.steeringQueue?.messages;if(!E)return!1;let S=E.indexOf(h);if(S<0){let k=JSON.stringify(h);S=E.findIndex((A)=>JSON.stringify(A)===k)}if(S<0)return!1;let[R]=E.splice(S,1);if(R)p.delete(R);return!0},abort:()=>a.abort()}}function xh(e){if(e?.role!=="assistant")return{reason:"done"};if(e.stopReason==="aborted")return{reason:"aborted"};if(e.stopReason==="error")return{reason:"error",error:e.errorMessage};return{reason:"done"}}function il(e,o="\u670D\u52A1\u91CD\u542F\u524D\u672A\u6301\u4E45\u5316\u8BE5\u8C03\u7528\u7684\u7ED3\u679C\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\uFF1A\u53EF\u80FD\u5C1A\u672A\u6267\u884C\u3001\u90E8\u5206\u6267\u884C\u6216\u5DF2\u7ECF\u5B8C\u6210\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\uFF0C\u4E0D\u8981\u76F2\u76EE\u91CD\u590D\u6709\u526F\u4F5C\u7528\u7684\u64CD\u4F5C\u3002"){let{name:a,source:u}=Oe(e.name,e.arguments);return{body:{type:"tool_result",callID:e.id,name:a,...u?{source:u}:{},output:o,isError:!0},raw:{role:"toolResult",toolCallId:e.id,toolName:e.name,content:[{type:"text",text:o}],isError:!0,timestamp:Date.now()}}}function Q$(e){return e.content.map((o)=>{if(o.type==="text")return{type:"text",text:o.text};if(o.type==="thinking")return{type:"thinking",text:o.thinking};return{type:"tool_call",id:o.id,...Oe(o.name,o.arguments)}})}function cU(e){switch(e.role){case"user":return{type:"user",text:typeof e.content==="string"?e.content:e.content.map((o)=>o.type==="text"?o.text:"").join("")};case"assistant":return{type:"assistant",parts:Q$(e),model:`${e.provider}/${e.model}`,...e.generationMs!==void 0?{generationMs:e.generationMs}:{},...e.stopReason==="error"&&e.errorMessage?{error:e.errorMessage}:{}};case"toolResult":{let o=e.content.filter((a)=>a.type==="image").map((a)=>({mimeType:a.mimeType,data:a.data}));return{type:"tool_result",callID:e.toolCallId,name:e.toolName,output:e.content.map((a)=>a.type==="text"?a.text:"").join(""),...o.length>0?{images:o}:{},isError:e.isError,...e.details===void 0?{}:{meta:e.details}}}default:return}}class Ze extends Error{errors;constructor(e){super(e.map((o)=>o.message).join("; "));this.errors=e;this.name="PluginCheckError"}}function C(e){return e}import{createHash as X$}from"crypto";import{existsSync as mU}from"fs";import{readFile as Y$,realpath as al}from"fs/promises";import{dirname as pU,isAbsolute as Z$,relative as eC,resolve as tC,sep as rC}from"path";var nC=[...Hi];class ul extends Error{errors;constructor(e){super(`Plugin web build failed: ${e.map((o)=>o.message).join("; ")}`);this.errors=e}}class cl{cache=new Map;pending=new Map;async entry(e,o){if(!e){if(o)throw Error("Plugin web entry requires a plugin source path");return}let a=pU(tC(e)),u=tC(a,o??"web.tsx");if(!o&&!mU(u))return;let m=eC(await al(a),await al(u));if(Z$(m)||m===".."||m.startsWith(`..${rC}`))throw Error("Plugin web entry must stay inside its plugin directory");return u}async build(e,o){let a=this.pending.get(e);if(a)return a;let u=this.compile(e,o);this.pending.set(e,u);try{return await u}finally{this.pending.delete(e)}}async compile(e,o){let a=this.cache.get(e);if(a){let E=!0;for(let[S,R]of a.inputs){let k=await Y$(S).catch(()=>{return});if(!k||X$("sha256").update(k).digest("hex")!==R){E=!1;break}}if(E)return a.source;this.cache.delete(e)}let u=await al(o),m=new Map,p=await Bun.build({entrypoints:[e],target:"browser",format:"esm",splitting:!1,minify:!0,throw:!1,external:nC,define:{"process.env.NODE_ENV":JSON.stringify("production")},plugins:[{name:"plugin-web-inputs",setup(E){E.onResolve({filter:/^(react(?:-dom)?(?:\/|$)|@basalt\/(?:plugin|ui)(?:\/|$))/},(S)=>{if(!nC.includes(S.path))throw Error(`Unsupported shared web import: ${S.path}`);return{path:S.path,external:!0}}),E.onLoad({filter:/.*/},async(S)=>{let R=eC(u,await al(S.path));if(Z$(R)||R===".."||R.startsWith(`..${rC}`))throw Error("Plugin web imports must stay inside its plugin directory");let k=await Y$(S.path);m.set(S.path,X$("sha256").update(k).digest("hex"));return})}}]}).catch((E)=>{let R=(E instanceof AggregateError?E.errors:[E]).map((k)=>k instanceof Error?k.message:String(k));throw Error(`Plugin web build failed: ${R.join("; ")}`,{cause:E})});if(!p.success)throw new ul(p.logs.filter((E)=>E.level==="error").map((E)=>({file:E.position?.file??null,line:E.position?.line??null,message:E.message})));let f=p.outputs.find((E)=>E.kind==="entry-point"&&E.path.endsWith(".js")),h=p.outputs.find((E)=>E.path.endsWith(".css"));if(!f||p.outputs.some((E)=>E!==f&&E!==h))throw Error("Plugin web must produce one JavaScript module and optional CSS; separate assets are not supported");let I=await f.text();return this.cache.set(e,{source:I,css:await h?.text(),inputs:m}),I}}function Go(e){try{return JSON.stringify(e)??""}catch{return String(e)}}function zs(e){let o=e;if(typeof o.content==="string")return o.content;return o.content.map((a)=>a.type==="text"?a.text:"[image]").join("")}function ml(e){return e.content.flatMap((a)=>a.type==="text"&&a.text.trim()?[a.text.trim()]:[]).join(`
31
+
32
+ `)}function du(e){return e.content.map((o)=>o.type==="text"?o.text:"[image]").join("")}function fu(e){return e.role==="assistant"&&e.content.length>0}function qe(e){let o=[],a=new Map,u=0;for(let m of e){let p=m.raw;if(p.role==="assistant"){if(fu(p))u++;for(let f of p.content){if(f.type!=="toolCall")continue;let h={call:f,step:u,message:p};o.push(h),a.set(f.id,h)}}else if(p.role==="toolResult"){let f=a.get(p.toolCallId);if(f)f.result=p}}return o}var pl=new Set(["edit","write"]),oC=new Set(["grep","glob"]);function Eo(e,o){let a=Oe(e.name,e.arguments).input?.[o];return typeof a==="string"?a:void 0}function sC(e){return[...new Set(qe(e).flatMap((o)=>pl.has(Oe(o.call.name,o.call.arguments).name)&&o.result&&!o.result.isError&&Eo(o.call,"path")?[Eo(o.call,"path")]:[]))]}function Ih(e){return!e.result?"pending":e.result.isError?"error":"completed"}function ll(e){let o=[{source:"ASSISTANT_TOOL",text:`${Oe(e.call.name,e.call.arguments).name}(${Go(Oe(e.call.name,e.call.arguments).input)}) [${Ih(e)}, call=${e.call.id}]`}];if(e.result)o.push({source:e.result.isError?"TOOL_ERROR":"TOOL_OUTPUT",text:du(e.result)});return o}function W(e){let o=0,a=0,u=0;for(let m of e){let p=m.codePointAt(0);if(p<=127)o++;else if(p>=19968&&p<=40959||p>=12288&&p<=12351||p>=65280&&p<=65519||p>=131072&&p<=173791)a++;else u++}return Math.max(0,Math.ceil(o/4+a+u/2))}var Eh=8192;function G(e){let o=e,a=0,u="";if(o.role==="system")u=typeof o.content==="string"?o.content:JSON.stringify(o.content);else if(o.role==="user")if(typeof o.content==="string")u=o.content;else for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else if(o.role==="assistant")for(let m of o.content)if(m.type==="text")u+=m.text;else if(m.type==="thinking")u+=m.thinking;else u+=`${m.name}${Go(m.arguments)}`;else if(o.role==="toolResult")for(let m of o.content)if(m.type==="text")u+=m.text;else a++;else u=Go(e);return W(u)+16+a*Eh}function Rt(e=[]){return e.reduce((o,a)=>o+W(a.name+a.description+Go(a.parameters))+16,0)}function Un(e,o){let a=e.replace(/\s+/g," ").trim();if(W(a)<=o)return a;let u=Math.min(a.length,o*4);while(u>0&&W(a.slice(0,u))>o-1)u=Math.floor(u*0.8);return`${a.slice(0,u).replace(/[\uD800-\uDBFF]$/,"")}\u2026`}function Lo(e,o,a=Number.POSITIVE_INFINITY){if(W(e)<=o&&e.length<=a)return e;let u=`
33
+ [... omitted; use history tools for the full text ...]
34
+ `,m=Math.floor((o-W(u))/2);if(m<=0)return"";let p=(f)=>{let h=0,I=Math.max(0,Math.min(e.length,m*4,Math.floor((a-u.length)/2)));while(h<I){let E=Math.ceil((h+I)/2),S=f?e.slice(-E):e.slice(0,E);if(W(S)<=m)h=E;else I=E-1}if(!h)return"";return f?e.slice(-h).replace(/^[\uDC00-\uDFFF]/,""):e.slice(0,h).replace(/[\uD800-\uDBFF]$/,"")};return`${p(!1)}${u}${p(!0)}`}function dl(e,o){if(W(e.join(`
35
+ `))<=o)return e;let a=(S)=>`- [... ${S} steps omitted; use history tools for the full text ...]`,u=o-W(a(e.length)),m=[],p=[],f=0,h=0,I=e.length-1;while(h<=I){let S=m.length<=p.length,R=S?e[h]:e[I],k=W(`${R}
36
+ `);if(f+k>u)break;if(f+=k,S)m.push(e[h++]);else p.unshift(e[I--])}let E=I-h+1;return[...m,...E>0?[a(E)]:[],...p]}function bt(e){let o=[],a;for(let u of e){let m=u.entry;if(m.type==="run"&&m.state==="start"){a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);continue}if(m.type==="run"&&m.state==="end"){if(a)a.end=m.seq,a.status=lU(m.reason,a.records);a=void 0;continue}if(m.type==="extension"||!u.raw)continue;if(!a&&m.type==="user"&&m.notices&&o.length){o.at(-1)?.records.push(u);continue}if(!a)a={id:`r${m.seq}`,start:m.seq,status:"open",records:[]},o.push(a);a.records.push(u)}for(let u of o)u.records=Ko(u.records);return o}function Ko(e){if(e.length<=1)return[...e];let o=[],a=[],u=new Set;for(let m=0;m<e.length;m++){let p=e[m];if(!p)continue;let f=p.raw?.role;if(f==="assistant"){let I=p.raw.content?.filter((E)=>E.type==="toolCall")??[];if(I.length>0)for(let E of I)u.add(E.id);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="toolResult"){let h=p.raw;if(h.toolCallId)u.delete(h.toolCallId);if(o.push(p),u.size===0&&a.length>0)o.push(...a),a=[];continue}if(f==="user"){if(o.length===0){o.push(p);continue}let h=e.slice(m+1).some((I)=>I.raw?.role==="assistant");if(u.size>0||h){a.push(p);continue}o.push(p);continue}o.push(p)}if(a.length>0)o.push(...a);return o}function lU(e,o){if(e==="waiting_user")return"waiting_user";if(e==="aborted"||e==="interrupted")return"interrupted";let a=o.findLast((u)=>u.raw?.role==="assistant")?.raw;if(e==="error")return a?.stopReason==="error"&&Ea(a)?"interrupted":"failed";if(!a)return"completed";switch(a.stopReason){case"stop":return"completed";case"length":return"failed";case"error":return Ea(a)?"interrupted":"failed";default:return"interrupted"}}function Ht(e){for(let o=e.length-1;o>=0;o--){let a=e[o]?.entry;if(a?.type==="compaction")return a.through}return 0}function fl(e,o){return e.end!==void 0&&e.end<=o&&e.records.every((a)=>a.entry.seq<=o)}function bh(e,o){return e.find((a)=>a.start<o&&!fl(a,o)&&a.records.some((u)=>u.entry.seq<=o))}function wr(e){let o=Ht(e),u=bt(e).findLast((m)=>m.end!==void 0);if(!u?.end||u.end<=o)return;return u.end}function Qn(e){let o=Ht(e);return bh(bt(e),o)?.end}function sn(e,o){let a=Ht(e),u=bt(e).at(-1);if(!u||u.end!==void 0)return;let m=u.records.filter((S)=>S.entry.seq>a),p=[],f=new Set;for(let S of m){let R=S.raw,k=G(S.raw);if(R.role==="assistant"){for(let A of R.content)if(A.type==="toolCall")f.add(A.id)}else if(R.role==="toolResult")f.delete(R.toolCallId);if(fu(R)||!p.length||R.role==="user"&&p.at(-1)?.assistant)p.push({end:S.entry.seq,tokens:k,assistant:fu(R),pending:f.size});else{let A=p.at(-1);A.end=S.entry.seq,A.tokens+=k,A.pending=f.size}}let h=p.findLastIndex((S)=>S.assistant),I=0,E;for(let S=p.length-1;S>=0;S--){let R=p[S];if(S<h&&R.assistant&&R.pending===0&&(I<=o||E===void 0))E=R.end;if(I+=R.tokens,I>o&&E!==void 0)break}if(I<=o)return;return E}var iC=2000;function Ct(e,o){let a=W(o);if(a<=iC)return o;let u=new TextEncoder().encode(o).length,m=o.split(`
37
+ `).length,p=[`<user-text-reference seq="${e}">`,"The complete original user text is preserved in this session but is too large to include here.",`size: ${u} bytes, ${m} lines, approximately ${a} tokens`,`Use history_list with seq="${e}" to read it by line range.`,`Use history_grep with seq="${e}" to search it.`].join(`
38
+ `),f="</user-text-reference>",h=iC-W(`${p}
39
+
40
+ ${f}`);if(h<=0)return o;let I=`${p}
41
+ ${Lo(o,h,o.length-p.length-f.length-3)}
42
+ ${f}`;return I.length<o.length&&W(I)<a?I:o}function aC(e){let o=e.raw;if(e.entry.type==="user"&&(e.entry.notices?.length??0)>0)return o;if(typeof o.content==="string"){let m=Ct(e.entry.seq,o.content);return m===o.content?o:{...o,content:m}}let a=!1,u=o.content.map((m)=>{if(m.type!=="text")return m;let p=Ct(e.entry.seq,m.text);if(p!==m.text)a=!0;return p===m.text?m:{...m,text:p}});return a?{...o,content:u}:o}function Sh(e,o=!1){let a=e.records.filter((A)=>A.entry.type==="user"&&!A.entry.notices&&A.raw.role==="user"),u=a.flatMap((A)=>{let P=A.raw.content;return typeof P==="string"?[]:P.filter((M)=>M.type==="image")}),m=`Use history_list with chunk_id="${e.id}" or history_grep to recover omitted details.`,p=e.status==="open"?"interrupted":e.status,f="";if(a.length){let A=o?Lo(a.map((P)=>zs(P.raw)).join(`
43
+
44
+ `),600):a.map((P,M)=>`<user-message sequence="${M+1}">
45
+ ${Ct(P.entry.seq,zs(P.raw))}
46
+ </user-message>`).join(`
47
+
48
+ `);f=[`<chunk-input id="${e.id}" status="${p}"${o?' excerpt="true"':""}>`,A,...o?[m]:[],"</chunk-input>"].join(`
49
+ `)}let I=e.records.filter((A)=>A.raw.role==="assistant").at(-1)?.raw,E=I?ml(I):"",S=[];if(p!=="completed"){let A=qe(e.records),P=new Map(A.map((j)=>[j.call,j])),M=A.slice(-3),V=new Set(M.map((j)=>j.message)),_=[],J=[];for(let j of e.records){let X=j.raw;if(X.role!=="assistant")continue;let te=V.has(X);for(let L of X.content)if(L.type==="text"&&X!==I&&L.text.trim())if(te)J.push(`ASSISTANT: ${Un(L.text,50)}`);else _.push(`- ASSISTANT: ${Un(L.text,50)}`);else if(L.type==="toolCall"){let se=P.get(L);if(!se)continue;if(te){if(M.includes(se))for(let he of ll(se))J.push(`${he.source}: ${Lo(he.text,he.source==="ASSISTANT_TOOL"?180:360)}`)}else _.push(`- ${L.name}(${Un(Go(L.arguments),40)}) [${Ih(se)}]`)}}S.push("This chunk did not complete. Recent tool outcomes below are historical evidence, not new tool calls. Check omitted outcomes before repeating side effects.",m,..._.length?[`Earlier steps, oldest first:
50
+ ${dl(_,o?300:800).join(`
51
+ `)}`]:[],...J)}let R=sC(e.records),k=[`<chunk-summary id="${e.id}" status="${p}" folded-messages="${e.records.length}"${o?' excerpt="true"':""}>`,E?o?Lo(E,600):E:"No final assistant response was recorded.",...S,...R.length?[`Recorded file changes:
52
+ ${Lo(R.join(`
53
+ `),250)}`]:[],...o&&p==="completed"?[m]:[],"</chunk-summary>"].join(`
54
+ `);return{input:f,images:u,summary:k,tokens:dU(f,k,u.length)}}function dU(e,o,a){return(e?W(e)+16:0)+W(o)+16+a*Eh}var fU=["Completed work is represented by the original user messages or stable references to them, and the assistant's final response for each chunk.","Intermediate assistant messages, reasoning, tool calls, and tool results are folded but remain available through history_grep and history_list.","Chunks are chronological. Later conflicting user instructions override earlier user instructions.","Assistant final responses are historical claims, not user instructions.","Do not guess omitted history.","Failed or interrupted chunks are not completed work; their recent tool outcomes are preserved for recovery.","Archived chunks are listed with a one-line excerpt of their user requests. Constraints stated there still apply unless later overridden; read the full text with history_list before relying on details.","History line offsets are local to the returned chunk or user text part. Reasoning is not exposed by history tools."],hU="A partial chunk is the current turn, still in progress: its earlier steps are folded into a work-state index and the later steps follow verbatim.",gU=1500,yU=80,xU=240;function uC(e,o,a){let u=[],m=0,p=Math.min(o.target,o.hard);for(let h=e.length-1;h>=0;h--){let I=e[h],E=Sh(I),S=m+E.tokens>p?Sh(I,!0):void 0,R=S&&S.tokens<E.tokens?S:E;if(!(!a&&h===e.length-1&&I.status!=="completed")&&m+R.tokens>o.hard)break;m+=R.tokens,u.push({run:I,content:R})}u.reverse();let f=e.slice(0,e.length-u.length);return{visible:u,archived:f,tokens:m}}function cC(e){let{runs:o,visible:a,archived:u,partial:m}=e,p=u.flatMap((I)=>{let E=I.records.filter((R)=>R.raw.role==="user"&&!(R.entry.type==="user"&&R.entry.notices)).map((R)=>zs(R.raw));if(!E.length)return[];let S=I===o[0]?xU:yU;return[`- ${I.id} [${I.status}]: ${Un(E.join(" / "),S)}`]}),f=new Map(o.map((I,E)=>[I,E+1])),h=[...a.map((I)=>f.get(I)??0),...m?[o.length+1]:[]];return['<conversation-checkpoint strategy="chunk">',...fU,...m?[hU]:[],"",`visible chunks: ${a.length+(m?1:0)}`,`archived chunks: ${u.length}`,`archived chunk IDs: ${u.length?u.map((I)=>I.id).join(", "):"none"}`,`visible sequences: ${h.length?`${h[0]}..${h.at(-1)}`:"none"}`,`history budget: ${e.tokens}/${e.budget.target} tokens (hard ${e.budget.hard})`,...p.length?["archived requests, oldest first:",Lo(p.join(`
55
+ `),gU)]:[],"</conversation-checkpoint>"].join(`
56
+ `)}function mC(e,o){let a=e.split(`
57
+ `),u=o.split(`
58
+ `),m=new Set(a),p=new Set(u),f=[...a.filter((I)=>I.trim()&&!p.has(I)).map((I)=>`- ${Un(I,40)}`),...u.filter((I)=>I.trim()&&!m.has(I)).map((I)=>`+ ${Un(I,40)}`)],h=a.find((I)=>I.trim()&&p.has(I));return[...f.slice(0,6),...f.length>6?[`\u2026 ${f.length-6} more changed lines`]:[],...h&&f.every((I)=>I.startsWith("+"))?[`@ ${Un(h,40)}`]:[]]}function hl(e,o){if(!o)return e;let a=o.endsWith("/")?o:`${o}/`;return e.startsWith(a)?e.slice(a.length):e}function IU(e){let o=e.arguments?.paths;if(!Array.isArray(o))return[];return o.flatMap((a)=>{let u=a&&typeof a==="object"?a.path:void 0;return typeof u==="string"?[u]:[]})}function EU(e,o){let a=Eo(e,"path");if(pl.has(e.name)&&a)return`file:${hl(a,o)}`;let u=Eo(e,"command");if(u)return`command:${u}`;return`${e.name}:${Go(e.arguments)}`}function bU(e,o){let a={steps:0,files:new Map,errors:[],narration:[],reads:new Map,searches:new Map,commands:[],other:new Map},u=new Map;for(let p of qe(e)){let f=u.get(p.step)??[];f.push(p),u.set(p.step,f)}let m=new Map;for(let p of e){let f=p.raw;if(!fu(f))continue;let h=++a.steps,I=ml(f);if(I)a.narration.push({step:h,text:Un(I,60)});for(let{call:E,result:S}of u.get(h)??[]){if(!S)continue;let R=Oe(E.name,E.arguments),k={...E,name:R.name,arguments:R.input},A=EU(k,o),P=du(S);if(S.isError){let X=Eo(k,"command"),te=X?`${k.name} \`${Un(X,40)}\``:`${k.name} ${A.startsWith("file:")?A.slice(5):Un(Go(k.arguments),40)}`,L={step:h,key:A,what:te,detail:Lo(P.trim().split(`
59
+ `).slice(0,8).join(`
60
+ `),200)};a.errors.push(L);let se=m.get(A)??[];se.push(L),m.set(A,se);continue}for(let X of m.get(A)??[])X.resolved=h;m.delete(A);let M=Eo(k,"path");if(pl.has(k.name)&&M){let X=hl(M,o),te=a.files.get(X)??{count:0,first:h,last:h,diffs:[]};if(te.count++,te.last=h,te.diffs.push({step:h,lines:k.name==="edit"?Eo(k,"old_string")!==void 0?mC(Eo(k,"old_string")??"",Eo(k,"new_string")??""):[]:mC("",Eo(k,"content")??"")}),te.diffs.length>3)te.diffs.shift();a.files.set(X,te);continue}let V=k.name==="read"?[...M?[M]:[],...IU(k)]:[];if(V.length){for(let X of V){let te=hl(X,o),L=a.reads.get(te)??[];L.push(h),a.reads.set(te,L)}continue}if(oC.has(k.name)){let X=M?` in ${hl(M,o)}`:"",te=k.name==="grep"&&Eo(k,"glob")?` (${Eo(k,"glob")})`:"",L=`${k.name} ${Eo(k,"pattern")??""}${X}${te}`.replace(/\s+/g," "),se=a.searches.get(L)??{steps:[],head:""};se.steps.push(h),se.head=Un(P.trim().split(`
61
+ `)[0]??"",25),a.searches.set(L,se);continue}let _=Eo(k,"command");if(_){let X=P.trim().split(`
62
+ `);a.commands.push({step:h,command:Un(_,40),exit:"0",lines:X.length,tail:X.slice(-3).map((te)=>Un(te,40))});continue}let J=`${k.name} ${Un(Go(k.arguments),40)}`,j=a.other.get(J)??[];j.push(h),a.other.set(J,j)}}return a}function pC(e){return`step${e.length>1?"s":""} ${e.join(",")}${e.length>1?`; ${e.length} times`:""}`}function Gc(e,o,a){let u=(E,S)=>S===void 0||!E.length?E:dl(E,S),m=[`<work-state chunk="${o.id}" status="partial" folded-steps="1-${e.steps}">`,`This turn is still in progress. Steps 1-${e.steps} were folded to free context: their tool outputs (file contents, search hits, command output) are no longer in your context, only this index is. The messages after it are the later steps, verbatim. Continue the current task from the latest step and do not redo folded steps. Do not answer from memory about folded output: when you need its exact text, call history_grep or history_list with chunk_id="${o.id}", or read in small slices with offset/limit (do NOT re-read large files in full, as it will trigger context compaction).`],p=[...e.files];m.push("",`## Modified files (${p.length})`),p.forEach(([E,S],R)=>{if(m.push(`- ${E}: ${S.count} change${S.count>1?"s":""} (step ${S.first}${S.last!==S.first?`-${S.last}`:""})`),R<p.length-a.diffFiles)return;for(let k of S.diffs)m.push(` step ${k.step}:`,...k.lines.map((A)=>` ${A}`))}),m.push("",`## Errors (${e.errors.length})`,...e.errors.map((E)=>E.resolved?`- step ${E.step} ${E.what} (resolved at step ${E.resolved})${a.lists===void 0?`: ${E.detail.replace(/\n/g,`
63
+ `)}`:""}`:`- step ${E.step} ${E.what} (UNRESOLVED): ${E.detail.replace(/\n/g,`
64
+ `)}`)),m.push("","## Steps",...u(e.narration.map((E)=>`- ${E.step}. ${E.text}`),a.narration));let f=[...e.reads].map(([E,S])=>`- ${E} @ ${S.join(",")}`);m.push("",`## Files read (${f.length}; contents folded into index; do NOT re-read full files, use offset/limit or history_grep)`,...u(f,a.lists));let h=[...e.searches].map(([E,S])=>`- ${E} \u2192 ${S.head||"(no output)"} (${pC(S.steps)})`);m.push("",`## Searches (${h.length})`,...u(h,a.lists));let I=e.commands.map((E)=>[`- ${E.step}. \`${E.command}\` exit=${E.exit}, ${E.lines} output lines, last ${E.tail.length}:`,...E.tail.map((S)=>` ${S}`)].join(`
65
+ `));if(m.push("",`## Commands (${I.length})`,...u(I,a.lists)),e.other.size){let E=[...e.other].map(([S,R])=>`- ${S} (${pC(R)})`);m.push("",`## Other tool calls (${E.length})`,...u(E,a.lists))}return m.push("</work-state>"),m.join(`
66
+ `)}function Xn(e,o,a,u){let m=bU(e,u),p=Gc(m,o,{diffFiles:Number.POSITIVE_INFINITY});if(W(p)<=a)return p;let f={...m,narration:[]};for(let E of[Number.POSITIVE_INFINITY,20,10,5]){let S=W(Gc(f,o,{diffFiles:E}));if(S>a*0.7)continue;return Gc(m,o,{narration:Math.max(500,a-S),diffFiles:E})}let h=Math.max(300,Math.floor(a*0.1)),I=W(Gc(f,o,{diffFiles:0,lists:h}));return Gc(m,o,{narration:Math.max(500,a-I),diffFiles:0,lists:h})}function gl(e){return{role:"user",content:e,timestamp:0}}function wh(e,o){return{role:"assistant",content:[{type:"text",text:e}],api:o.api,provider:o.provider,model:o.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"stop",timestamp:0}}function lC(e){return e.images.length?{role:"user",content:[{type:"text",text:e.input},...e.images],timestamp:0}:gl(e.input)}function hu(e){let o=[];for(let a of e){let u=o.at(-1),m=a;if(u?.role==="user"&&m.role==="user"){let p=(f)=>typeof f.content==="string"?[{type:"text",text:f.content}]:f.content;o[o.length-1]={...m,content:[...p(u),{type:"text",text:`
67
+
68
+ `},...p(m)],timestamp:Math.max(u.timestamp,m.timestamp)};continue}o.push(a)}return o}function dC(e){let o=[],a=new Map;for(let u of e){let m=u;if(m.role==="toolResult"){if(!a.has(m.toolCallId))continue;let p=a.get(m.toolCallId);if(p===void 0)a.set(m.toolCallId,o.length),o.push(u);else o[p]=u;continue}if(m.role==="assistant"){if(m.content.length===0)continue;if(a=new Map,m.stopReason!=="error"&&m.stopReason!=="aborted"){for(let p of m.content)if(p.type==="toolCall")a.set(p.id,void 0)}}else if(m.role==="user")a=new Map;o.push(u)}return o}function SU(e,o){if(typeof o!=="string")return o;if(e==="data"&&o.length>160)return`${o.slice(0,96)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-96).toLocaleString()} \u5B57\u7B26]`;if(o.length>2400)return`${o.slice(0,1600)}\u2026 [\u5DF2\u7701\u7565 ${(o.length-1600).toLocaleString()} \u5B57\u7B26]`;return o}function Ce(e,o,a,u={}){let m=Ht(e),p=bt(e),f=p.filter((Q)=>fl(Q,m)),h=bh(p,m),I=[],E=[],S=0;for(let Q of p){if(fl(Q,m))continue;let ee=[];for(let be of Q.records){if(Q===h&&be.entry.seq<=m)continue;let Xe=be.raw.role==="user"?aC(be):be.raw;S+=G(Xe),I.push(Xe),ee.push(Xe)}if(u.inspect&&ee.length)E.push({id:`recent-${Q.id}`,label:`\u6700\u8FD1\u6D88\u606F \xB7 ${Q.id}`,tokens:ee.reduce((be,Xe)=>be+G(Xe),0),detail:JSON.stringify(ee,SU,2)})}if(!f.length&&!h)return{items:E,messages:hu(I),visible:0,archived:0,open:S,tokens:S,untrimmed:S};let R=uC(f,a,!!h),{visible:k,archived:A}=R,P=R.tokens,M=[],V="",_="";if(h){let Q=h.records.filter((be)=>be.entry.seq<=m),ee=Q.filter((be)=>be.entry.type==="user"&&!be.entry.notices&&be.raw.role==="user");if(ee.length){V=[`<chunk-input id="${h.id}" status="partial">`,...ee.map((Xe,Ge)=>`<user-message sequence="${Ge+1}">
69
+ ${Ct(Xe.entry.seq,zs(Xe.raw))}
70
+ </user-message>`),"</chunk-input>"].join(`
71
+ `);let be=ee.flatMap((Xe)=>{let Ge=Xe.raw.content;return typeof Ge==="string"?[]:Ge.filter((sr)=>sr.type==="image")});M.push(be.length?{role:"user",content:[{type:"text",text:V},...be],timestamp:0}:gl(V))}_=Xn(Q,h,a.index,u.cwd),M.push(wh(_,o))}let J=e.flatMap((Q)=>{let ee=Q.raw;if(Q.entry.seq>m||ee?.role!=="toolResult"||ee.toolName!=="skill")return[];return[gl(ee.content.filter((be)=>be.type==="text").map((be)=>be.text).join(`
72
+ `))]}),j="",X=e.findLast((Q)=>Q.entry.type==="compaction")?.entry.time??0,te=()=>{j=cC({runs:f,visible:k.map((ee)=>ee.run),archived:A,partial:!!h,tokens:P,budget:a});let Q=[gl(j)];for(let{content:ee}of k){if(ee.input)Q.push(lC(ee));Q.push(wh(ee.summary,o))}return[...Q,...J,...M].map((ee)=>({...ee,timestamp:X}))},L=(Q)=>Q.reduce((ee,be)=>ee+G(be),0),se=te(),he=L(se)+S,Me=he,{trim:We}=u;while(We&&We.fixed+he>We.limit){let Q=h||k.at(-1)?.run.status==="completed"?k:k.slice(0,-1);if(!Q.length)break;let ee=0,be=0;for(let Xe of Q)if(be++,ee+=Xe.content.tokens,ee>=We.fixed+he-We.limit)break;A=[...A,...k.slice(0,be).map((Xe)=>Xe.run)],k=k.slice(be),P-=ee,se=te(),he=L(se)+S}return{items:u.inspect?[{id:"index",label:"\u5386\u53F2\u7D22\u5F15",tokens:G(se[0]),detail:j},...k.map(({run:Q,content:ee})=>({id:Q.id,label:`Chunk ${Q.id}`,state:"sealed",tokens:(ee.input?G(lC(ee)):0)+G(wh(ee.summary,o)),detail:[ee.input,ee.summary].filter(Boolean).join(`
73
+
74
+ `)})),...A.map((Q)=>({id:Q.id,label:`Chunk ${Q.id}`,state:"archived",tokens:0,detail:"\u539F\u6587\u5DF2\u79FB\u51FA\u8BF7\u6C42\uFF0C\u53EF\u901A\u8FC7\u5386\u53F2\u5DE5\u5177\u53D6\u56DE\uFF1B\u5F15\u7528\u5305\u542B\u5728\u5386\u53F2\u7D22\u5F15\u4E2D\u3002"})),...h?[{id:h.id,label:`Chunk ${h.id}`,state:"folded",tokens:L(M),detail:[V,_].filter(Boolean).join(`
75
+
76
+ `)}]:[],...E]:[],messages:hu([...se,...I]),visible:k.length,archived:A.length,open:S,tokens:he,untrimmed:Me}}function de(e){return Math.max(1000,(e.contextWindow||128000)-Math.min(e.maxTokens||20000,20000))}var Th=0.97,wU=0.97,fC=0.5,TU=0.05,RU=20000,kU=24000;function an(e){return{target:RU,hard:kU,index:Math.floor(de(e)*TU)}}function Rh(e){let o=e.usage;return o.totalTokens||o.input+o.output+o.cacheRead+o.cacheWrite}class ln{records;fold;cwd;ratio=1;lastEstimate=0;reshapedAfter=-1;lastFoldSeq=-1;consecutivePartialFolds=0;constructor(e,o,a=()=>{return}){this.records=e;this.fold=o;this.cwd=a}budget(e){return an(e)}get calibrationRatio(){return this.ratio}calibrate(e){let o=e.usage.input+e.usage.cacheRead+e.usage.cacheWrite;if(o>0&&this.lastEstimate>0)this.ratio=Math.min(2,Math.max(0.5,o/this.lastEstimate))}previewLimit(e){return Math.floor(de(e)*Th/this.ratio)}prepare(e,o,a,u){let m=de(a),p=an(a),f=e.reduce((L,se)=>L+G(se),0)+Rt(o),h=this.records().at(-1)?.entry.seq??0,I=()=>u?[...u,...this.records().filter((L)=>L.entry.seq>h)]:this.records(),E=()=>Ce(I(),a,p,{cwd:this.cwd(),trim:{fixed:f,limit:Math.floor(m*Th/this.ratio)}}),S=I().findLast((L)=>L.raw?.role==="assistant"),R=S?I().filter((L)=>L.entry.seq>S.entry.seq&&L.raw):[],k=S?.raw,A=()=>S!==void 0&&(S.entry.seq===this.reshapedAfter||I().some((L)=>L.entry.type==="compaction"&&L.entry.seq>S.entry.seq)),P=this.dueSeal(a);if(P!==void 0)this.fold(P,!1),this.reshapedAfter=S?.entry.seq??-1;let M=E(),V=R.reduce((L,se)=>L+G(se.raw),0);if(this.lastEstimate===0&&S&&k&&!A()){let L=k.usage.input+k.usage.cacheRead+k.usage.cacheWrite,se=f+M.untrimmed-G(k)-V;if(L>0&&se>0)this.ratio=Math.min(2,Math.max(0.5,L/se))}let J=((L)=>{let se=f+L.untrimmed,he=f+L.tokens;return((S&&k&&!A()&&Rh(k)>0?Rh(k)+Math.round(this.ratio*V):void 0)??Math.round(se*this.ratio))-Math.round((se-he)*this.ratio)})(M);if(J>m*wU){let L=J-M.open*this.ratio,se=Math.max(1000,Math.floor((m*fC-L-p.index)/this.ratio)),he=S?.entry.seq??-1,Me=I().findLast((be)=>be.entry.type==="compaction"&&be.entry.partial)?.entry.seq??-1,We=Math.max(this.lastFoldSeq,Me),ee=(We>0?I().filter((be)=>be.entry.seq>We&&be.raw?.role==="assistant").length:999)<=1;if(!ee||this.consecutivePartialFolds<2){let be=sn(I(),se);if(be!==void 0)this.fold(be,!0),this.reshapedAfter=he,this.lastFoldSeq=he,this.consecutivePartialFolds=ee?this.consecutivePartialFolds+1:1,M=E()}}else this.consecutivePartialFolds=0;this.lastEstimate=f+M.tokens;let j=M.messages,X=f+M.tokens;if(Math.round(X*this.ratio)>m)j=AU(j,Math.floor((m-f)/this.ratio)),X=f+j.reduce((L,se)=>L+G(se),0);return this.lastEstimate=X,{messages:hu([...e,...j]),estimate:X}}settle(e){let o=this.dueSeal(e);if(o===void 0)return;this.fold(o,!1),this.reshapedAfter=this.records().findLast((a)=>a.raw?.role==="assistant")?.entry.seq??-1}dueSeal(e){let o=this.records();if(Qn(o)===void 0){let a=o.findLast((h)=>h.raw?.role==="assistant"),u=a?.raw,m=a!==void 0&&(a.entry.seq===this.reshapedAfter||o.some((h)=>h.entry.type==="compaction"&&h.entry.seq>a.entry.seq)),f=(a?o.filter((h)=>h.entry.seq>a.entry.seq&&h.raw):[]).reduce((h,I)=>h+G(I.raw),0);if(m||!u||Rh(u)+f<Math.floor(de(e)*Th))return}return wr(o)}recover(e){let o=de(e),a=an(e),u=Ce(this.records(),e,a,{cwd:this.cwd()}),m=Math.floor((o*fC-(o-u.open*this.ratio)-a.index)/this.ratio),p=sn(this.records(),m);if(p===void 0)return!1;return this.fold(p,!0),this.reshapedAfter=this.records().findLast((f)=>f.raw?.role==="assistant")?.entry.seq??-1,!0}}var kh=500;function AU(e,o){let a=[...e],u=a.map((p)=>G(p)),m=u.reduce((p,f)=>p+f,0);while(m>o){let p=-1;for(let[R,k]of a.entries()){if(k.role!=="toolResult"||(u[R]??0)<=kh)continue;if(p<0||(u[R]??0)>(u[p]??0))p=R}if(p<0)break;let f=a[p],h=u[p]??0,I=Math.max(kh,Math.floor(h/2)),E={...f,content:f.content.map((R)=>R.type==="text"?{...R,text:Lo(R.text,I)}:R)},S=G(E);u[p]=S<h?S:kh,a[p]=E,m-=h-S}return a}var PU=2000;function gu(e,o){let a=[];for(let u of o.replace(/\r\n/g,`
77
+ `).split(`
78
+ `))for(let m=0;m<Math.max(u.length,1);){let p=Math.min(u.length,m+PU);if(p<u.length&&/[\uD800-\uDBFF]/.test(u.charAt(p-1)))p--;a.push({source:e,text:u.slice(m,p)}),m=p>m?p:m+1}return a}function xr(e){let o=[],a=qe(e.records),u=new Map(a.map((p)=>[p.call,p])),m=new Set(a.flatMap((p)=>p.result?[p.result]:[]));for(let p of e.records){let f=p.raw;if(f.role==="user")o.push(...gu(p.entry.type==="user"&&p.entry.notices?"NOTICE":"USER",zs(f)));else if(f.role==="assistant"){for(let h of f.content)if(h.type==="text"&&h.text.trim())o.push(...gu("ASSISTANT",h.text));else if(h.type==="toolCall"){let I=u.get(h);if(I)for(let E of ll(I))o.push(...gu(E.source,E.text))}}else if(f.role==="toolResult"&&!m.has(f))o.push(...gu(f.isError?"TOOL_ERROR":"TOOL_OUTPUT",du(f)))}return o.map((p,f)=>({chunk:e.id,line:f,...p}))}function Jn(e,o){let a=e.find((u)=>u.entry.seq===o);if(a?.entry.type!=="user"||a.entry.notices||!a.raw||a.raw.role!=="user")return;return gu("USER",zs(a.raw)).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function Yn(e,o){let a=e.find((u)=>u.entry.seq===o)?.entry;if(a?.type!=="extension"||!a.display)return;return gu("EXTENSION",a.display.text).map((u,m)=>({chunk:`seq ${o}`,line:m,...u}))}function cn(e,o=""){return e.map((a,u)=>{let m=e[u-1],p=m&&m.source===a.source&&m.chunk===a.chunk&&m.line===a.line-1;return`${o}${p?`${a.line}:`:`${a.line} ${a.source}:`} ${a.text}`}).join(`
79
+ `)}import{AsyncLocalStorage as $U}from"async_hooks";import{chmodSync as xC,existsSync as CU,mkdirSync as vU,readFileSync as MU,renameSync as OU,writeFileSync as _U}from"fs";import{dirname as LU,join as NU}from"path";function hC(){let e=Bun.version.split(".").map(Number);if(!((e[0]??0)>1||e[0]===1&&(e[1]??0)>4||e[0]===1&&e[1]===4&&(e[2]??0)>=3))throw Error("\u4EE3\u7406\u4F20\u8F93\u9700\u8981 Bun 1.4.3 \u6216\u66F4\u65B0\u7248\u672C\uFF0C\u8BF7\u5148\u5347\u7EA7 Bun")}function gC(e=process.env){let o={...e};for(let a of["HTTP_PROXY","HTTPS_PROXY","ALL_PROXY","NO_PROXY"])delete o[a],delete o[a.toLowerCase()];return o}function Kc(e){let o=e.hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/)?.[1]??o;return u==="localhost"||u.endsWith(".localhost")||u==="::1"||u==="::"||/^(?:0\.|127\.)/.test(u)}function yC(e,o){let a=async(m,p,f)=>{let h=await e(m,{...p,...o.proxy?{proxy:o.proxy}:{proxy:!1},...o.tls==="insecure"?{tls:{rejectUnauthorized:!1}}:{},redirect:"manual"});if(![301,302,303,307,308].includes(h.status))return h;let I=h.headers.get("location");if(!I)return h;if(f>=10)throw Error("\u4EE3\u7406\u8BF7\u6C42\u91CD\u5B9A\u5411\u6B21\u6570\u8FC7\u591A");let E=m instanceof Request?m:void 0,S=new URL(E?.url??String(m)),R=new URL(I,S);if(R.protocol!=="http:"&&R.protocol!=="https:")throw Error("\u62D2\u7EDD\u91CD\u5B9A\u5411\u5230\u975E HTTP \u5730\u5740");if(Kc(R)&&!Kc(S))throw Error("\u62D2\u7EDD\u4ECE\u516C\u7F51\u91CD\u5B9A\u5411\u5230\u56DE\u73AF\u5730\u5740");let k=new Headers(E?.headers);if(new Headers(p?.headers).forEach((M,V)=>{k.set(V,M)}),S.origin!==R.origin)k.delete("authorization"),k.delete("cookie"),k.delete("proxy-authorization");let A=(p?.method??E?.method??"GET").toUpperCase(),P={...p,method:A,headers:k};if(h.status===303||(h.status===301||h.status===302)&&A==="POST")P.method="GET",delete P.body,k.delete("content-length"),k.delete("content-type");else if(A!=="GET"&&A!=="HEAD"&&p?.body===void 0&&E?.body)throw Error("\u65E0\u6CD5\u5B89\u5168\u91CD\u5B9A\u5411\u5E26\u6D41\u5F0F\u8BF7\u6C42\u4F53\u7684\u8BF7\u6C42");return await h.body?.cancel(),a(R,P,f+1)};return Object.assign((m,p)=>a(m,p,0),{preconnect:e.preconnect})}var Ah=Gi,EC=Ar,IC=new $U;class Di{baseFetch;path;config={version:1,routes:{},profiles:[]};constructor(e,o=fetch){this.baseFetch=o;hC(),this.path=NU(e,"proxy.json");let a=async(u,m)=>{let p=IC.getStore();if(!p)return this.baseFetch(u,m);return this.createFetch(p)(u,m)};globalThis.fetch=Object.assign(a,{preconnect:o.preconnect})}load(){if(!CU(this.path))return;this.config=this.validate(JSON.parse(MU(this.path,"utf8")))}settings(){return{...this.config,defaultProfileID:this.config.defaultProfileID,routes:{...this.config.routes},profiles:this.config.profiles.map((e)=>{let{password:o,...a}=e;return{...a,hasPassword:Boolean(o)}})}}save(e){let o=this.validate(e);for(let a of o.profiles)a.password||=this.config.profiles.find((u)=>u.id===a.id)?.password;try{vU(LU(this.path),{recursive:!0});let a=`${this.path}.tmp-${process.pid}`;_U(a,`${JSON.stringify(o,null,2)}
80
+ `,{mode:384}),xC(a,384),OU(a,this.path),xC(this.path,384)}catch(a){throw Error("\u4FDD\u5B58\u4EE3\u7406\u914D\u7F6E\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u6570\u636E\u76EE\u5F55\u7684\u53EF\u7528\u7A7A\u95F4\u4E0E\u5199\u5165\u6743\u9650\u540E\u91CD\u8BD5",{cause:a})}return this.config=o,this.settings()}createFetch(e,o=this.baseFetch){let a=(m,p="verify")=>yC(o,{proxy:m,tls:p});return Object.assign(async(m,p)=>{let f=m instanceof Request?m.url:String(m),I=this.profileFor(e)?.noProxy?.some((S)=>FU(f,S))??!1;if(Kc(new URL(f))||I)return a()(m,p);let E=this.proxyURL(e);return a(E,this.profileFor(e)?.tls)(m,p)},{preconnect:o.preconnect})}models(e){return new bC(e,this)}providerOptions(e,o,a){let u=Object.assign({},e),m=e?.fetch,f=m?.[sl]?.call(m,this.baseFetch)??m??this.baseFetch;u.fetch=this.createFetch(o,f);let h=gC({...process.env,...e?.env}),I=!1;if(a)try{I=Kc(new URL(a))}catch{}let E=I?void 0:this.proxyURL(o),S=this.profileFor(o);return u.env={...h,...E?{HTTP_PROXY:E,HTTPS_PROXY:E,ALL_PROXY:E}:{},...S?.noProxy?.length?{NO_PROXY:S.noProxy.join(",")}:{}},u}run(e,o){return IC.run(e,o)}wrapProvider(e){let o=qt(e.id),a={...e.auth},u=e.auth.oauth;if(u){let S=e.id==="openai"||e.id===St?Ah:o;a.oauth={...u,login:(R,k)=>this.run(S,()=>u.login(R,k)),refresh:(R,k)=>this.run(S,()=>u.refresh(R,k)),toAuth:(R)=>this.run(S,()=>u.toAuth(R))}}let m={...e,auth:a},p=e.refreshModels;if(p)m.refreshModels=(S)=>this.run(o,()=>p(S));m.stream=(S,R,k)=>this.run(o,()=>e.stream(S,R,this.providerOptions(k,o,S.baseUrl))),m.streamSimple=(S,R,k)=>this.run(o,()=>e.streamSimple(S,R,this.providerOptions(k,o,S.baseUrl)));let f=e.fetchDeferred;if(f)m.fetchDeferred=(S,R,k)=>this.run(o,()=>f(S,R,this.providerOptions(k,o,S.baseUrl)));let h=e.cancelDeferred;if(h)m.cancelDeferred=(S,R,k)=>this.run(o,()=>h(S,R,this.providerOptions(k,o,S.baseUrl)));let I=e.generateImages;if(I)m.generateImages=(S,R,k)=>this.run(o,()=>I(S,R,this.providerOptions(k,o,S.baseUrl)));let E=e.classify;if(E)m.classify=(S,R,k)=>this.run(o,()=>E(S,R,this.providerOptions(k,o,S.baseUrl)));return m}proxyURL(e){let o=this.profileFor(e);if(!o)return;let a=Yo(o.address),u=o.username?`${encodeURIComponent(o.username)}:${encodeURIComponent(o.password??"")}@`:"",m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return`${a.protocol}://${u}${m}:${a.port}`}profileFor(e){let o=e?this.config.routes[e]:this.config.defaultProfileID,a=e&&o!==void 0?o:this.config.defaultProfileID;if(!a)return;let u=this.config.profiles.find((m)=>m.id===a);if(!u)throw Error(`\u4EE3\u7406\u7EBF\u8DEF ${a} \u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u8BBE\u7F6E\u9875\u91CD\u65B0\u9009\u62E9`);return u}validate(e){let o=Ph(e);if(o?.version!==1)throw new t("\u4EE3\u7406\u914D\u7F6E\u7248\u672C\u65E0\u6548");let u=(Array.isArray(o.profiles)?o.profiles:[]).map(qU),m=new Set(u.map((I)=>I.id));if(m.size!==u.length)throw new t("\u4EE3\u7406\u914D\u7F6E ID \u4E0D\u80FD\u91CD\u590D");let p=DU(o.defaultProfileID);if(p&&!m.has(p))throw new t("\u9ED8\u8BA4\u7EBF\u8DEF\u4E0D\u5B58\u5728");let f=Ph(o.routes)??{},h={};for(let[I,E]of Object.entries(f)){if(I!==Ah&&I!==EC&&!zi(I))throw new t(`\u4EE3\u7406\u7528\u9014\u65E0\u6548\uFF1A${I}`);if(E!==null&&(typeof E!=="string"||!m.has(E)))throw new t(`\u7528\u9014 ${I} \u7684\u7EBF\u8DEF\u4E0D\u5B58\u5728`);h[I]=E}return{version:1,defaultProfileID:p,routes:h,profiles:u}}}class bC{source;manager;wrapped=new Map;constructor(e,o){this.source=e;this.manager=o;for(let a of e.getProviders())this.install(a)}getProviders(){return this.source.getProviders().map((e)=>this.wrap(e))}getProvider(e){let o=this.source.getProvider(e);return o?this.wrap(o):void 0}getModels(...e){return this.source.getModels(...e)}getModel(...e){return this.source.getModel(...e)}getModelsOfType(e,o){return this.source.getModelsOfType(e,o)}getModelOfType(e,o,a){return this.source.getModelOfType(e,o,a)}getAllModels(...e){return this.source.getAllModels(...e)}refresh(...e){return this.source.refresh(...e)}checkAuth(...e){return this.source.checkAuth(...e)}getAvailable(...e){return this.source.getAvailable(...e)}getAvailableOfType(e,o,a){return this.source.getAvailableOfType(e,o,a)}getAllAvailable(...e){return this.source.getAllAvailable(...e)}getAuth(e,o){if(typeof e==="string")return this.source.getAuth(e,o);return this.source.getAuth(e,o)}login(...e){return this.source.login(...e)}logout(...e){return this.source.logout(...e)}stream(e,o,a){return this.source.stream(e,o,a)}complete(e,o,a){return this.source.complete(e,o,a)}streamSimple(...e){return this.source.streamSimple(...e)}completeSimple(...e){return this.source.completeSimple(...e)}streamDeferred(...e){return this.source.streamDeferred(...e)}fetchDeferred(...e){return this.source.fetchDeferred(...e)}cancelDeferred(...e){return this.source.cancelDeferred(...e)}generateImages(...e){return this.source.generateImages(...e)}classify(...e){return this.source.classify(...e)}setProvider(e){this.install(e)}deleteProvider(e){this.source.deleteProvider(e),this.wrapped.delete(e)}clearProviders(){this.source.clearProviders(),this.wrapped.clear()}wrap(e){return this.wrapped.get(e.id)??this.install(e)}install(e){if(this.wrapped.get(e.id)===e)return this.source.setProvider(e),e;let o=this.manager.wrapProvider(e);return this.wrapped.set(e.id,o),this.source.setProvider(o),o}}function qt(e){return`${qi}${e}`}function Ss(e){return[{id:Ah,name:"ChatGPT \u8BA2\u9605\u767B\u5F55\u4E0E\u5237\u65B0"},{id:EC,name:"\u7A0B\u5E8F\u66F4\u65B0\uFF08npm registry\uFF09"},...e.map((o)=>({id:qt(o.id),name:`\u6A21\u578B\uFF1A${o.name}`}))]}function qU(e){let o=Ph(e);if(!o)throw new t("\u4EE3\u7406\u914D\u7F6E\u5FC5\u987B\u662F\u5BF9\u8C61");if(typeof o.id!=="string"||!/^[a-zA-Z0-9_-]{1,64}$/.test(o.id))throw new t("\u4EE3\u7406\u914D\u7F6E ID \u65E0\u6548");let a;try{a=Yo(String(o.address??""))}catch(p){throw new t(p instanceof Error?p.message:"\u4EE3\u7406\u5730\u5740\u65E0\u6548")}let u=Array.isArray(o.noProxy)?o.noProxy:[];if(!u.every((p)=>typeof p==="string"&&p.trim()))throw new t("\u76F4\u8FDE\u4F8B\u5916\u5FC5\u987B\u662F\u975E\u7A7A\u4E3B\u673A");let m=a.hostname.includes(":")?`[${a.hostname}]`:a.hostname;return{id:o.id,name:typeof o.name==="string"&&o.name.trim()?o.name.trim():a.hostname,address:`${a.protocol}://${m}:${a.port}`,username:typeof o.username==="string"&&o.username?o.username:void 0,password:typeof o.password==="string"&&o.password?o.password:void 0,tls:o.tls==="insecure"?"insecure":"verify",noProxy:u.map((p)=>String(p).trim())}}function DU(e){if(e===void 0||e===null||e==="")return;if(typeof e!=="string")throw new t("\u4EE3\u7406\u7EBF\u8DEF ID \u65E0\u6548");return e}function Ph(e){if(!e||typeof e!=="object"||Array.isArray(e))return;return e}function FU(e,o){try{let a=new URL(e).hostname.toLowerCase().replace(/^\[|\]$/g,""),u=o.toLowerCase().replace(/^\[|\]$/g,"").replace(/^\./,"");return a===u||a.endsWith(`.${u}`)}catch{return!1}}import{join as xg}from"path";import{existsSync as jC}from"fs";import{realpath as UC}from"fs/promises";import{dirname as BC,isAbsolute as rB,join as GC,relative as nB,resolve as Lh,sep as oB}from"path";import{existsSync as jU,watch as UU}from"fs";import{readdir as BU,stat as GU}from"fs/promises";import{basename as $h,dirname as KU,join as SC,resolve as HU}from"path";class Ch{host;slots;watching;debounceMs;watchers=[];debounceTimers=new Map;revision=0;constructor(e,o,a,u=150){this.host=e;this.slots=o;this.watching=a;this.debounceMs=u}close(){for(let e of this.debounceTimers.values())clearTimeout(e);this.debounceTimers.clear();for(let e of this.watchers)e.close();this.watchers.length=0}async discover(e,o=[]){let a=[],u=[];for(let h of[...new Set(e)]){let I;try{I=await BU(h)}catch(E){if(E instanceof Error&&"code"in E&&E.code==="ENOENT")continue;throw E}for(let E of I.sort()){let S=SC(h,E),R=(await GU(S)).isDirectory()?SC(S,"index.ts"):S;if(!R.endsWith(".ts")||R.endsWith(".d.ts"))continue;try{u.push({definition:await this.read(R),path:R})}catch(k){let A=$h(R)==="index.ts"?$h(KU(R)):$h(R,".ts");if(this.slots.has(A))throw Error(`Duplicate plugin: ${A}`);let P={id:A,version:"unknown",apiVersion:1,setup(){throw Error(`Plugin module failed discovery: ${A}; repair the file and reload`)}};a.push({definition:P,path:R}),this.slots.set(A,{definition:P,path:R,enabled:!0,discoveryFailed:!0,error:k instanceof Error?k.message:String(k)})}}}let m=o.filter((h)=>![...u,...a].some((I)=>I.definition.id===h.definition.id)),p=[...m,...u],f=this.order(p.map(({definition:h})=>h));for(let h of f){let I=p.find((S)=>S.definition===h)?.path,E=m.some((S)=>S.definition===h);try{await this.host.install(h,I,E)}catch(S){this.slots.set(h.id,{definition:h,path:I,builtin:E,enabled:!0,error:S instanceof Error?S.message:String(S)})}}if(this.watching())for(let h of[...p,...a]){if(!jU(h.path))continue;let I=UU(h.path,()=>{let E=h.definition.id,S=this.debounceTimers.get(E);if(S)clearTimeout(S);let R=setTimeout(()=>{this.debounceTimers.delete(E),this.host.reload(E).catch((k)=>{let A=this.slots.get(E);if(A)A.error=k instanceof Error?k.message:String(k)})},this.debounceMs);R.unref?.(),this.debounceTimers.set(E,R)});I.on("error",(E)=>{let S=this.slots.get(h.definition.id);if(S)S.error=E.message,this.host.changed()}),this.watchers.push(I)}}order(e,o=!1){let a=new Map;for(let h of e){if(this.validate(h),a.has(h.id)||!o&&this.slots.has(h.id))throw Error(`Duplicate plugin: ${h.id}`);a.set(h.id,h)}let u=[],m=new Set,p=new Set,f=(h)=>{if(p.has(h.id))return;if(m.has(h.id))throw Error(`Plugin dependency cycle: ${h.id}`);m.add(h.id);for(let I of h.deps??[]){let E=a.get(I);if(E)f(E);else if(!this.slots.has(I))throw Error(`Missing plugin dependency: ${I}`)}m.delete(h.id),p.add(h.id),u.push(h)};for(let h of e)f(h);return u}validate(e){if(!e||typeof e!=="object"||!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(e.id))throw Error("Plugin id must contain only letters, digits, dots, underscores and hyphens");if(e.apiVersion!==1)throw Error(`Unsupported plugin apiVersion: ${e.id}`);if(typeof e.version!=="string"||!e.version||typeof e.setup!=="function")throw Error(`Invalid plugin definition: ${e.id}`);if(e.deps&&(!Array.isArray(e.deps)||e.deps.some((o)=>typeof o!=="string")))throw Error(`Invalid plugin dependencies: ${e.id}`)}async read(e){let o=await import(`${HU(e)}?v=${++this.revision}`);if(!o.default)throw Error("Plugin module must export a default definition");return this.validate(o.default),o.default}}async function wC(e,o,a=!1){if(!Number.isSafeInteger(o)||o<1||o>2147483647)throw Error("Plugin callback timeout must be a positive timer duration");let u=new AbortController,m;try{return await Promise.race([a?Promise.resolve(e(u.signal)):Promise.resolve().then(()=>e(u.signal)),new Promise((p,f)=>{m=setTimeout(()=>{u.abort(),f(Error(`Plugin callback timed out after ${o}ms`))},o)})])}finally{clearTimeout(m)}}import{AsyncLocalStorage as WU}from"async_hooks";import{isDeepStrictEqual as TC}from"util";var $a=new WU;function Vs(){let e=$a.getStore();if(e?.phase!=="before")return;throw e.violated=!0,Error("entry.before_append cannot access SQL or append entries")}function yu(e){let o=structuredClone(e),a=(u)=>{if(!u||typeof u!=="object"||Object.isFrozen(u))return;Object.freeze(u);for(let m of Object.values(u))a(m)};return a(o),o}function RC(e,o){if(!o||typeof o!=="object"||Array.isArray(o))throw Error("Entry replacement must be a body");for(let I of["seq","time","session_id","raw"])if(I in o)throw Error(`Entry replacement contains protected field: ${I}`);let a=JSON.parse(JSON.stringify(o,(I,E)=>{if(typeof E==="function"||typeof E==="symbol"||typeof E==="number"&&!Number.isFinite(E))throw Error("Entry replacement must contain JSON values");return E}));if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Entry replacement must serialize to a body");let u=a,m=[];switch(e.type){case"user":m.push("text","attachments");break;case"assistant":m.push("parts","error");break;case"tool_result":m.push("output","images");break;case"extension":m.push("payload","display");break;case"notice_pending":m.push("notice");break;case"run":if(e.state==="end")m.push("error");break;case"compaction":break}let p={...e};for(let I of new Set([...Object.keys(e),...Object.keys(u)])){if(!m.includes(I)&&!TC(p[I],u[I]))throw Error(`Entry replacement changed protected field: ${I}`);if(["seq","time","session_id","raw"].includes(I))throw Error(`Entry replacement contains protected field: ${I}`)}let f=(I)=>I===void 0||typeof I==="string",h=!0;switch(e.type){case"user":h=typeof u.text==="string"&&(u.attachments===void 0||Array.isArray(u.attachments)&&u.attachments.every((I)=>I&&typeof I.name==="string"&&typeof I.mimeType==="string"&&io.includes(I.kind)&&typeof I.data==="string"));break;case"assistant":h=f(u.error)&&Array.isArray(u.parts)&&u.parts.every((I)=>I&&(["text","thinking"].includes(I.type)&&typeof I.text==="string"||I.type==="tool_call"&&typeof I.id==="string"&&typeof I.name==="string"&&("input"in I)));break;case"tool_result":h=typeof u.output==="string"&&(u.images===void 0||Array.isArray(u.images)&&u.images.every((I)=>I&&typeof I.mimeType==="string"&&typeof I.data==="string"));break;case"extension":{let I=u.display;h="payload"in u&&(I===void 0||I!==null&&typeof I==="object"&&("text"in I)&&typeof I.text==="string"&&(!("title"in I)||f(I.title)));break}case"notice_pending":{let E=["text"],S=p.notice,R=u.notice;if(h=!!R&&typeof R==="object"&&!Array.isArray(R),!h)break;let k=R;for(let A of new Set([...Object.keys(S),...Object.keys(k)]))if(E.includes(A)){if(typeof k[A]!=="string")h=!1}else if(!TC(S[A],k[A]))h=!1;break}case"run":h=f(u.error);break;case"compaction":break}if(!h)throw Error("Invalid entry replacement content");return a}function kC(e,o,a,u,m,p){let f=u;for(let h of a.generations)for(let I of h.hooks.get("entry.before_append")??[]){if(h.disabled)break;let E={phase:"before",violated:!1};try{let S=$a.run(E,()=>{let R=yu(f),k=performance.now(),A=I(R,{sessionID:m,seq:p});if(A&&(typeof A==="object"||typeof A==="function")&&"then"in A&&typeof A.then==="function")throw Promise.resolve(A).catch(()=>{}),Error("entry.before_append must be synchronous");let P=A===void 0?void 0:RC(f,A);if(E.violated)throw Error("entry.before_append attempted a database write");return{validated:P,slow:performance.now()-k>e}});if(S.validated&&JSON.stringify(S.validated)!==JSON.stringify(f))f=S.validated;if(S.slow)throw Error("entry.before_append exceeded budget");h.beforeFailures=0,h.failures=0}catch(S){h.failures=h.beforeFailures++,o(h,S)}}return f}function zU(e,o){if(e.startsWith("session.")||e==="projection.policy"||e==="tools.visible"||e==="tools.configure")return o;if(e==="entry.after_append")return yu(o);return structuredClone(o)}async function AC(e,o,a,u,m,p,f,h,I="end"){let E=p;for(let S of u){if(S.disabled)continue;let R=S.hooks.get(m)??[];for(let k of R){if(S.disabled)break;let A=S.hookOptions.get(k);if(m==="prompt.fragments"&&(A?.promptPosition??"end")!==I)continue;let P=m==="prompt.fragments"?JSON.stringify([f?.id,E]):void 0,M=P===void 0?void 0:S.promptCache.get(k)?.get(P);try{let V=zU(m,E),_=A?.timeoutMs,J=typeof _==="function"?_({runtime:e.runtime,session:f,connection:h}):_,j=await o((X)=>k(V,{runtime:e.runtime,session:f,connection:h,signal:X}),J);if(P!==void 0){let X=j===void 0?E:j;if(!Array.isArray(X)||X.some((L)=>typeof L!=="string"))throw Error("Prompt fragments must be strings");if(M&&JSON.stringify(M)!==JSON.stringify(X))throw Error("Prompt fragments changed for identical input; retaining cached fragments");let te=S.promptCache.get(k)??new Map;te.set(P,[...X]),S.promptCache.set(k,te)}if(S.failures=0,j!==void 0&&m!=="entry.after_append")E=j}catch(V){if(M)E=structuredClone(M);if(a(S,V),A?.errorMode==="propagate")throw V}}}return E}class Hc{host;generations;released=!1;constructor(e,o){this.host=e;this.generations=o}async invoke(e,o,a,u,m="end"){if(this.released)throw Error("Plugin generation lease has been released");return this.host.invoke(this.generations,e,o,a,u,m)}has(e,o){return this.generations.some((a)=>!a.disabled&&(a.hooks.get(e)??[]).some((u)=>o===void 0||(a.hookOptions.get(u)?.promptPosition??"end")===o))}tools(){return this.generations.filter((e)=>!e.disabled).flatMap((e)=>e.tools.map((o)=>({...o,execute:async(...a)=>{if(e.disabled||e.disposed||this.released)throw Error(`Plugin tool is disabled: ${o.name}`);return o.execute(...a)}})))}waiting(e){return this.generations.some((o)=>!o.disabled&&o.gates.some((a)=>a(e)))}resolveHistory(e,o){if(this.released)throw Error("Plugin generation lease has been released");for(let a of this.generations){if(a.disabled)continue;for(let u of a.historyResolvers){let m=u(e,o);if(m)return m}}}policy(e){return this.generations.findLast((o)=>!o.disabled&&o.policies.has(e))?.policies.get(e)}async release(){if(this.released)return;this.released=!0;for(let e of this.generations)e.references--,await this.host.collect(e)}}import{existsSync as VU}from"fs";import{dirname as JU,resolve as PC}from"path";var vh=new WeakMap;function $C(e){return[...e].map((o)=>{let a=Boolean(o.path&&(Boolean(o.definition.webEntry)||VU(PC(JU(PC(o.path)),"web.tsx"))));if(o.current&&!vh.has(o.current))vh.set(o.current,crypto.randomUUID());return{id:o.definition.id,description:o.definition.description,builtin:o.builtin??!1,web:o.enabled&&!o.current?.disabled?o.current?.web??[]:[],webBundle:a,webRevision:o.current?vh.get(o.current):void 0,version:o.definition.version,deps:o.definition.deps??[],status:!o.enabled?"disabled":o.current?.disabled||!o.current?"error":"enabled",error:o.error??o.current?.error,registrations:o.current?[...[...o.current.hooks.keys()].map((u)=>({kind:"hook",name:u})),...o.current.tools.map((u)=>({kind:"tool",name:u.name})),...o.current.routes.map((u)=>({kind:"route",method:u.method,path:u.path})),...o.current.websockets.map((u)=>({kind:"websocket",path:u.path})),...o.current.commands.map((u)=>({kind:"command",id:u.id})),...o.current.web.map((u)=>({kind:"web",id:u.id})),...[...o.current.policies.keys()].map((u)=>({kind:"policy",id:u})),...o.current.historyResolvers.map(()=>({kind:"history-resolver"}))]:[]}})}class Mh{host;deadline;fail;pending=new Set;entryQueues=new Map;constructor(e,o,a){this.host=e;this.deadline=o;this.fail=a}async idle(){while(this.pending.size)await Promise.all(this.pending)}notify(e,o,a){let u=this.host.pin(),m=(async()=>{try{let p=[];for(let f of u.generations){if(f.disabled)continue;for(let h of f.hooks.get(e)??[]){let I=f.hookOptions.get(h)?.timeoutMs,E=typeof I==="function"?I({runtime:this.host.runtime,session:o,connection:a}):I;p.push(this.deadline((S)=>h(o,{runtime:this.host.runtime,session:o,connection:a,signal:S}),E,!0).catch((S)=>this.fail(f,S)))}}await Promise.all(p)}finally{await u.release()}})();this.pending.add(m),m.then(()=>this.pending.delete(m),()=>this.pending.delete(m))}finishEntry(e,o,a){let u=a===void 0?void 0:yu(a),m=(this.entryQueues.get(o)??Promise.resolve()).then(async()=>{try{if(u)await $a.run({phase:"after",violated:!1},()=>e.invoke("entry.after_append",u,this.host.runtime.get(o)))}finally{await e.release()}});this.entryQueues.set(o,m),this.pending.add(m);let p=()=>{if(this.pending.delete(m),this.entryQueues.get(o)===m)this.entryQueues.delete(o)};m.then(p,p)}}function CC(e){return e.replace(/(?:(?:request[- ]?)?headers?)["']?\s*[=:][\s\S]*/gi,"[headers redacted]").replace(/\b(?:api[-_ ]?key|authorization|cookie|password|secret|access[-_ ]?token)\b[^\n]*/gi,"[redacted]").replace(/\bBearer\s+[^\s"',}]+/gi,"[redacted]").replace(/(?:authorization|[\w-]*api[-_]?key|password|secret|cookie|[\w-]*token|key)["']?\s*[=:][^\n]*/gi,"[redacted]").replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi,"[address]").replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g,"[address]").replace(/\blocalhost(?::\d+)?\b/gi,"[address]").replace(/\b(?:sk|key)-[\w-]+/gi,"[redacted]").replace(/[\r\n\t]+/g," ").slice(0,300)}function QU(e){if(typeof e.prompt!=="string"||!e.prompt.trim())throw Error("Completion prompt must not be empty");if(e.system!==void 0&&typeof e.system!=="string")throw Error("Invalid completion system prompt");if(e.sessionID!==void 0&&typeof e.sessionID!=="string")throw Error("Invalid completion sessionID")}async function XU(e,o){let a=o.sessionID?e.get(o.sessionID):void 0;if(o.sessionID&&!a)throw Error("Completion session not found");let u=o.model??a?.model??e.options.defaultModel;if(typeof u!=="string")throw Error("Invalid completion model; use GET /api/models to view models");let m=kn(e.options.models,u);if(!m&&o.model!==void 0)throw Error("Completion model is not configured; use GET /api/models to view available models");if(o.model===void 0||!m){let p=(await e.models()).models.filter((h)=>h.available===!0),f=m?kt(m):u;if(!p.some((h)=>h.id===f)){let h=p[0];if(h)m=kn(e.options.models,h.id)}}if(!m)throw Error("\u6CA1\u6709\u53EF\u7528\u6A21\u578B\uFF0C\u8BF7\u914D\u7F6E provider");return m}async function vC(e,o){QU(o);let a=await XU(e,o),u=o.maxTokens??Math.min(a.maxTokens,4096);if(!Number.isSafeInteger(u)||u<=0||u>a.maxTokens)throw Error("Completion maxTokens must be a positive integer within the model output limit");if(o.signal?.aborted)throw Error("Completion cancelled");let m="",p=!1;try{let f=[...o.system?[{role:"system",content:o.system,timestamp:Date.now()}]:[],{role:"user",content:o.prompt,timestamp:Date.now()}],h=e.options.models.streamSimple(a,{messages:f},{maxTokens:u,signal:o.signal});for await(let I of h){if(o.signal?.aborted)throw Error("cancelled");if(I.type==="error")throw Error(`\u6A21\u578B\u8FD4\u56DE\u9519\u8BEF\uFF1A${CC(I.error.errorMessage??"provider \u672A\u63D0\u4F9B\u539F\u56E0")}`);if(I.type==="text_delta")m+=I.delta;if(I.type==="done"){if(I.reason==="length")throw Error("\u8F93\u51FA\u88AB\u622A\u65AD\uFF08length\uFF09");if(I.reason!=="stop")throw Error(`\u6A21\u578B\u8F93\u51FA\u672A\u5B8C\u6210\uFF08${I.reason}\uFF09`);p=!0}}}catch(f){if(o.signal?.aborted)throw Error("Completion cancelled");throw Error(`\u6A21\u578B\u8C03\u7528\u5931\u8D25\uFF1A${CC(f instanceof Error?f.message:String(f))}`)}if(o.signal?.aborted)throw Error("Completion cancelled");if(!p)throw Error("Model completion ended without a stop response; retry");return{text:m,model:kt(a)}}var YU=["active","archived","all"];function MC(e=2000){if(!Number.isSafeInteger(e)||e<0)throw Error("sessions limit must be a non-negative integer");return Math.min(e,2000)}function ZU(e){let{projectID:o,children:a,archive:u,since:m}=e;if(o!==void 0&&o!==null&&typeof o!=="string")throw Error("sessions projectID must be a string or null");if(a!==void 0&&typeof a!=="boolean")throw Error("sessions children must be a boolean");if(u!==void 0&&!YU.includes(u))throw Error("sessions archive must be active, archived or all");if(m!==void 0&&!Number.isFinite(m))throw Error("sessions since must be a finite timestamp in milliseconds")}function eB(e){return{seq:e.seq,time:e.time,type:e.type,...e.type==="assistant"?{model:e.model}:{}}}function OC(e){function o(a,u={}){let{types:m,bodies:p}=u;if(m!==void 0&&!Array.isArray(m))throw Error("sessions types must be an array");let f=MC(u.limit),h=u.after??0;if(!Number.isSafeInteger(h)||h<0)throw Error("sessions after must be a non-negative integer");let I=(e.get(a)?.entries(h,m,p!==!1)??[]).slice(0,f);return structuredClone(p===!1?I.map(eB):I)}return{list(a={}){ZU(a);let u=a.limit===void 0?void 0:MC(a.limit),m=e.list(a.children??!1,{archive:a.archive}).filter((p)=>a.projectID===void 0||p.projectID===a.projectID).filter((p)=>a.since===void 0||p.created>=a.since);return structuredClone(u===void 0?m:m.slice(0,u))},get(a){return structuredClone(e.get(a)?.info())},entries:o}}async function _C(e,o,a,u,m,p){let f={definition:o,hooks:new Map,hookOptions:new Map,tools:[],routes:[],websockets:[],connections:new Set,commands:[],web:[],gates:[],noticeSources:new Map,services:new Map,policies:new Map,historyResolvers:[],deactivators:[],disposers:[],references:0,retired:!1,disabled:!1,disposed:!1,beforeFailures:0,failures:0,promptCache:new Map},h=e.runtime.store.db,I=new Map,E=!1,S=!0,R=()=>{if(!S||f.disposed)throw Error("Plugin registration scope is closed")},k=(_,J)=>{if(R(),!E){I.set(_,J);return}if(J===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,_);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,_,J)},A={get:(_)=>{R();let J=I.has(_)?I.get(_):h.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(o.id,_)?.value;return J==null?void 0:JSON.parse(J)},set:(_,J)=>{let j=JSON.stringify(J);if(j===void 0)throw Error("Plugin KV values must be JSON serializable");k(_,j)},delete:(_)=>k(_,null)},P=()=>{if(R(),E)throw Error("Register resources during setup only")},M=[...o.migrations??[]].sort((_,J)=>_.version-J.version),V=new Set;try{for(let _ of M){if(!Number.isSafeInteger(_.version)||_.version<1||V.has(_.version))throw Error("Plugin migration versions must be unique positive integers");if(V.add(_.version),h.query("SELECT 1 FROM plugin_migrations WHERE namespace = ? AND version = ?").get(o.id,_.version))continue;h.transaction(()=>{if(_.sql!==void 0)h.run(_.sql);else _.up({...A,db:h});for(let[J,j]of I)if(j===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,J);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,J,j);h.query("INSERT INTO plugin_migrations (namespace, version) VALUES (?, ?)").run(o.id,_.version)})(),e.runtime.store.invalidateEntryCache(),I.clear()}return await u(async()=>o.setup({runtime:e.runtime,sessions:OC(e.runtime),complete:(_)=>vC(e.runtime,_),kv:A,database:h,broadcast:(_)=>{e.runtime.emitEvent(_)},registerInputGate:(_)=>{P(),f.gates.push(_)},registerNoticeSource:(_,J)=>{if(P(),!_||!Number.isSafeInteger(J.textLimit)||J.textLimit<1||!Number.isSafeInteger(J.summaryLimit)||J.summaryLimit<1)throw Error("Notice source limits must be positive integers");f.noticeSources.set(_,{...J})},provide:(_,J)=>{if(P(),_.pluginID!==o.id)throw Error("Service key must belong to the providing plugin");if(f.services.has(_.name))throw Error(`Duplicate plugin service: ${_.name}`);if(!_.validate(J))throw Error(`Invalid plugin service: ${_.name}`);f.services.set(_.name,J)},on:(_,J,j)=>{if(P(),j?.promptPosition&&_!=="prompt.fragments")throw Error("promptPosition only applies to prompt.fragments");let X=f.hooks.get(_)??[];if(X.push(J),f.hooks.set(_,X),j)f.hookOptions.set(J,j)},registerHistoryResolver:(_)=>{P(),f.historyResolvers.push(_)},registerTool:(_,J)=>{if(P(),!_.name||["toolsearch","tool_search","tool_call"].includes(_.name.toLowerCase())||tB(e,m,o.id).has(_.name.toLowerCase())||f.tools.some((X)=>X.name.toLowerCase()===_.name.toLowerCase()))throw Error(`Tool names collide ignoring case: ${_.name}`);let j=a?"always":"defer";if(typeof J?.defer==="boolean")j=J.defer?"defer":"always";else if(J?.defer!==void 0)j=J.defer;f.tools.push({..._,defer:j,source:`plugin:${o.id}`,group:J?.group,aliases:J?.aliases,builtin:a})},registerRoute:(_)=>{if(P(),!(_.path.startsWith(`/api/plugins/${o.id}/`)||(o.routePrefixes??[]).some((J)=>_.path===J||_.path.startsWith(`${J}/`)))||!/^(GET|POST|PUT|PATCH|DELETE)$/.test(_.method))throw Error("Plugin routes must use /api/plugins/<id>/ and an explicit HTTP method");if(f.routes.some((J)=>J.path===_.path&&J.method===_.method))throw Error("Duplicate plugin route");f.routes.push(_)},registerWebSocket:(_)=>{if(P(),!_.path.startsWith(`/api/plugins/${o.id}/`))throw Error("Plugin WebSocket routes must use /api/plugins/<id>/");if(f.websockets.some((J)=>J.path===_.path))throw Error("Duplicate plugin WebSocket route");f.websockets.push(_)},registerCommand:(_)=>{P(),f.commands.push(_)},registerWebContribution:(_)=>{P(),f.web.push(_)},registerToolPolicy:(_,J)=>{P(),f.policies.set(_,J)},appendExtension:(_,J)=>{if(Vs(),R(),!E)throw Error("Append extensions from hooks after setup commits");return e.appendExtension(_,J)},onDeactivate:(_)=>{P(),f.deactivators.push(_)},onDispose:(_)=>{P(),f.disposers.push(_)}})),h.transaction(()=>{for(let[_,J]of I)if(J===null)h.query("DELETE FROM plugin_kv WHERE namespace = ? AND key = ?").run(o.id,_);else h.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(o.id,_,J)})(),I.clear(),E=!0,f}catch(_){throw S=!1,await p(f),_}}function tB(e,o,a){let u=new Set([...e.runtime.builtinToolNames(),...e.runtime.tools.snapshot().map((m)=>m.name)].map((m)=>m.toLowerCase()));for(let[m,p]of o){if(m===a)continue;for(let f of p.current?.tools??[])u.add(f.name.toLowerCase())}return u}class Oh{deadline;retired=new Set;constructor(e){this.deadline=e}async retire(e){e.retired=!0;for(let o of e.connections)o.close(1012,"Plugin changed");this.retired.add(e);for(let o of e.deactivators.splice(0).reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}await this.collect(e)}async collect(e){if(!e.retired||e.references||e.disposed)return;e.disposed=!0;for(let o of e.disposers.reverse())try{await this.deadline(o)}catch(a){e.error=a instanceof Error?a.message:String(a)}this.retired.delete(e)}async collectRetired(){for(let e of this.retired)await this.collect(e)}}function LC(e,o,a,u){for(let m of o){let p=m.current;if(!p||p.disabled||p.retired)continue;let f=p.websockets.find((h)=>h.path===u);if(!f)continue;return{connect:(h)=>{let I=!1;p.references++,p.connections.add(h);let E={send:(R)=>{if(I||p.retired||p.disabled)return;h.send(R)},close:(R,k)=>h.close(R,k)},S=async(R)=>{if(I||p.retired||p.disabled){h.close(1012,"Plugin unavailable");return}try{await a(R),p.failures=0}catch(k){if(p.failures++,p.error=k instanceof Error?k.message:String(k),h.close(1011,"Plugin callback failed"),p.failures>=e.failureThreshold){p.disabled=!0;for(let A of p.connections)A.close(1011,"Plugin disabled")}}};return{open:()=>S(()=>f.open?.(E)),message:(R)=>S(()=>f.message(E,R)),close:async()=>{if(I)return;I=!0,p.connections.delete(h);try{await a(()=>f.close?.(E))}catch(R){p.error=R instanceof Error?R.message:String(R)}finally{p.references--,await e.collect(p)}}}}}}return}function _h(e,o){let a=e.split("/"),u=new URL(o.url).pathname.split("/");if(a.length!==u.length)return;let m={};return a.every((f,h)=>{let I=u[h];if(I===void 0)return!1;if(!f.startsWith(":"))return I===f;try{m[f.slice(1)]=decodeURIComponent(I)}catch{return!1}return I.length>0})?m:void 0}async function NC(e,o,a,u,m){let p=e.pin();try{let f=p.generations.find((h)=>h.definition.id===a)?.commands.find((h)=>h.id===u);if(!f)throw new y("Plugin command is unavailable");return await o(()=>f.execute(m))}finally{await p.release()}}function qC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.method===o.method&&_h(m.path,o)!==void 0))}finally{a.release()}}function DC(e,o){let a=e.pin();try{return a.generations.some((u)=>u.routes.some((m)=>m.public===!0&&m.method===o.method&&_h(m.path,o)!==void 0))}finally{a.release()}}async function FC(e,o,a){let u=e.pin(),m=!0;try{for(let p of u.generations)for(let f of p.routes){if(f.method!==a.method)continue;let h=_h(f.path,a);if(h){let I=await o(()=>f.handler(a,h),f.timeoutMs);if(!I)return;if(I.body&&I.body instanceof ReadableStream){m=!1;let E=!1,S=()=>{if(E)return;E=!0,u.release()},R=I.body.getReader(),k=new ReadableStream({async pull(A){try{let{done:P,value:M}=await R.read();if(P)A.close(),S();else A.enqueue(M)}catch(P){A.error(P),S()}},async cancel(A){try{await R.cancel(A)}finally{S()}}});return new Response(k,{status:I.status,statusText:I.statusText,headers:I.headers})}return I}}return}finally{if(m)await u.release()}}class Nh{runtime;options;slots=new Map;retirement=new Oh(this.deadline.bind(this));observers=new Mh(this,this.deadline.bind(this),this.fail.bind(this));catalog;webBuilder=new cl;directories=new Set;serial=Promise.resolve();closed=!1;timeoutMs;failureThreshold;constructor(e,o={}){this.runtime=e;this.options=o;if(o.beforeAppendBudgetMs!==void 0&&(!Number.isFinite(o.beforeAppendBudgetMs)||o.beforeAppendBudgetMs<=0))throw Error("Entry hook budget must be positive");if(this.catalog=new Ch(this,this.slots,()=>o.watch===!0,o.watchDebounceMs??150),this.timeoutMs=o.timeoutMs??5000,this.failureThreshold=o.failureThreshold??3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>2147483647)throw Error("Plugin timeout must be a positive timer duration");if(!Number.isSafeInteger(this.failureThreshold)||this.failureThreshold<1)throw Error("Plugin failure threshold must be positive")}service(e){let o=this.slots.get(e.pluginID);if(!o?.enabled||!o.current||o.current.disabled||o.current.retired)throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);let a=o.current.services.get(e.name);if(!e.validate(a))throw new y(`Plugin service is unavailable: ${e.pluginID}/${e.name}`);return a}waiting(e){return[...this.slots.values()].some((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.gates.some((a)=>a(e)))}noticeSource(e){return[...this.slots.values()].findLast((a)=>a.enabled&&a.current&&!a.current.disabled&&a.current.noticeSources.has(e))?.current?.noticeSources.get(e)??{textLimit:500,summaryLimit:800}}async invokeIdle(){let e=this.pin();try{await e.invoke("runtime.idle",void 0)}finally{await e.release()}}async invokeProjectDelete(e){let o=this.pin();try{await o.invoke("project.delete",e)}finally{await o.release()}}exclusive(e){let o=this.serial.then(async()=>{let a=JSON.stringify(this.list());try{return await e()}finally{if(JSON.stringify(this.list())!==a)this.changed()}});return this.serial=o.then(()=>{},()=>{}),o}discover(e,o=[]){for(let a of e)this.directories.add(Lh(a));return this.catalog.discover(e,o).finally(()=>this.changed())}async pluginPath(e){let o=await UC(e),a=[...this.directories,GC(this.runtime.options.dataDir,"plugins"),...this.runtime.projects().map((u)=>GC(u.directory,".basalt","plugins"))];for(let u of a){if(!jC(u))continue;let m=nB(await UC(u),o);if(m&&m!==".."&&!m.startsWith(`..${oB}`)&&!rB(m)){if(!o.endsWith(".ts")||o.endsWith(".d.ts"))throw Error("Plugin entry must be a .ts file");return o}}throw Error("Plugin path must be inside a registered plugin directory")}load(e){return this.exclusive(async()=>{if(this.closed)throw Error("Plugin host is closed");let o=await this.pluginPath(e),a=await this.checkEntry(o);if(!a.ok)throw new Ze(a.errors);let u=await this.catalog.read(o);return await this.installDefinition(u,o,!1),u.id})}async check(e){return this.checkEntry(await this.pluginPath(e))}async checkEntry(e){let o=await Bun.build({entrypoints:[e],target:"bun",throw:!1,external:["@basalt/plugin","@earendil-works/pi-ai"]});return{ok:o.success,errors:o.logs.filter((a)=>a.level==="error").map((a)=>({file:a.position?.file??null,line:a.position?.line??null,column:a.position?.column??null,message:a.message}))}}order(e,o=!1){return this.catalog.order(e,o)}install(e,o,a=!1){return this.exclusive(async()=>{await this.installDefinition(e,o,a)})}async installDefinition(e,o,a=!1){if(this.closed)throw Error("Plugin host is closed");this.order([e]);let u=this.runtime.store.db.query("SELECT enabled FROM plugin_settings WHERE id = ?").get(e.id),m={definition:e,path:o,builtin:a,enabled:u?.enabled!==0};if(m.enabled)m.current=await this.stage(e,a);this.slots.set(e.id,m)}reload(e){return this.exclusive(async()=>{let o=this.require(e);if(!o.path)throw Error(`Plugin has no reloadable module: ${e}`);try{if(!o.builtin){let h=await this.checkEntry(o.path);if(!h.ok)throw new Ze(h.errors)}let a=o.builtin&&!jC(o.path)?o.definition:await this.catalog.read(o.path);if(a.id!==e)throw Error("Reload cannot change plugin id");if(!o.enabled)throw Error("Enable the plugin before reloading");let u=this.order([...this.slots.values()].map((h)=>h.definition.id===e?a:h.definition),!0),m=await this.stage(a),p=o.current;o.definition=a,o.current=m,o.error=void 0,o.discoveryFailed=!1;let f=new Map(this.slots);this.slots.clear();for(let h of u){let I=f.get(h.id);if(I)this.slots.set(h.id,I)}if(p)await this.retirement.retire(p)}catch(a){throw o.error=a instanceof Error?a.message:String(a),a}})}setEnabled(e,o){return this.exclusive(async()=>{let a=this.require(e);if(o===a.enabled&&(!o||a.current&&!a.current.disabled))return;if(!o){for(let f of this.slots.values())if(f.enabled&&f.definition.deps?.includes(e))throw Error(`Disable dependent plugin first: ${f.definition.id}`)}let u=o&&a.discoveryFailed&&a.path?await this.catalog.read(a.path):a.definition;if(u.id!==e)throw Error("Enable cannot change plugin id");let m=o?await this.stage(u):void 0;this.runtime.store.db.query("INSERT OR REPLACE INTO plugin_settings (id, enabled) VALUES (?, ?)").run(e,Number(o));let p=a.current;if(a.definition=u,o)a.discoveryFailed=!1;if(a.enabled=o,a.current=m,a.error=void 0,p)await this.retirement.retire(p)})}require(e){if(this.closed)throw Error("Plugin host is closed");let o=this.slots.get(e);if(!o)throw Error(`Plugin not found: ${e}`);return o}async stage(e,o=this.slots.get(e.id)?.builtin===!0){this.catalog.validate(e);for(let a of e.deps??[])if(a===e.id||!this.slots.get(a)?.current||this.slots.get(a)?.current?.disabled)throw Error(`Plugin dependency is unavailable: ${a}`);return _C(this,e,o,this.deadline.bind(this),this.slots,this.retirement.retire.bind(this.retirement))}notify(e,o,a){this.observers.notify(e,o,a)}resolveHistory(e,o){for(let a of this.slots.values()){if(!a.enabled||!a.current||a.current.disabled)continue;for(let u of a.current.historyResolvers){let m=u(e,o);if(m)return m}}}registeredTools(){return[...this.slots.values()].flatMap((e)=>e.enabled&&e.current&&!e.current.disabled?e.current.tools:[])}toolPolicy(e){return[...this.slots.values()].findLast((o)=>o.enabled&&o.current&&!o.current.disabled&&o.current.policies.has(e))?.current?.policies.get(e)}idle(){return this.observers.idle()}pin(){let e=[...this.slots.values()].flatMap((o)=>o.enabled&&o.current&&!o.current.disabled?[o.current]:[]);for(let o of e)o.references++;return new Hc(this,e)}async invoke(e,o,a,u,m,p="end"){return AC(this,this.deadline.bind(this),this.fail.bind(this),e,o,a,u,m,p)}pinEntry(e){if($a.getStore()?.phase==="after")return;let o;for(let a of this.slots.values()){let u=a.current;if(!a.enabled||!u||u.disabled||e.type==="extension"&&e.namespace===u.definition.id)continue;if(!u.hooks.has("entry.before_append")&&!u.hooks.has("entry.after_append"))continue;o??=[],o.push(u),u.references++}if(!o)return;return new Hc(this,o)}beforeEntry(e,o,a,u){return kC(this.options.beforeAppendBudgetMs??5,this.fail.bind(this),e,o,a,u)}changed(){this.runtime.emitEvent({type:"plugins_changed"})}fail(e,o){if(e.failures++,e.error=o instanceof Error?o.message:String(o),e.failures>=this.failureThreshold){e.disabled=!0;for(let a of e.connections)a.close(1011,"Plugin disabled")}this.changed()}finishEntry(e,o,a){this.observers.finishEntry(e,o,a)}deadline(e,o=this.timeoutMs,a=!1){return wC(e,o,a)}appendExtension(e,o){return Vs(),new Promise((a)=>{let u=this.runtime.get(e);if(!u)throw Error("Extension target session does not exist");if(!o.namespace||!o.kind||!Number.isSafeInteger(o.schemaVersion)||o.schemaVersion<1)throw Error("Extension requires namespace, kind and a positive schemaVersion");let m=this.runtime.store.appendEntry(e,void 0,{type:"extension",...o});u.refreshEntries(),a(m)})}list(){return $C(this.slots.values())}sourceEntry(e){return this.require(e).path}async buildWeb(e){try{let o=this.require(e),a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(a&&o.path)await this.webBuilder.build(a,BC(Lh(o.path)));return{ok:!0}}catch(o){if(o instanceof ul)return{ok:!1,errors:o.errors};return{ok:!1,errors:[{file:null,line:null,message:o instanceof Error?o.message:String(o)}]}}}async webBundle(e){let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);if(!a)return;return this.webBuilder.build(a,BC(Lh(o.path)))}async webCSS(e){await this.webBundle(e);let o=this.slots.get(e);if(!o?.enabled||!o.path||o.current?.disabled)return;let a=await this.webBuilder.entry(o.path,o.definition.webEntry);return a?this.webBuilder.cache.get(a)?.css:void 0}command(e,o,a){return NC(this,this.deadline.bind(this),e,o,a)}hasRoute(e){return qC(this,e)}isPublicRoute(e){return DC(this,e)}route(e){return FC(this,this.deadline.bind(this),e)}websocket(e){return LC(this,this.slots.values(),this.deadline.bind(this),e)}collect(e){return this.retirement.collect(e)}async close(){this.catalog.close(),await this.serial,await this.idle(),this.closed=!0;for(let e of this.slots.values())if(e.current)await this.retirement.retire(e.current);await this.retirement.collectRetired()}}import{statSync as KC}from"fs";import{join as sB}from"path";var iB=500,aB=1000,uB=3600000,cB=5000,mB=2000,pB=3,lB=1073741824;class qh{options;indexPath;features;enabledFlag;worker;flags=new Int32Array(new SharedArrayBuffer(8));engineStatus;failure;restarts=0;reader;flushID=0;flushes=new Map;stopping;stopped;pruned=0;lastPrune=0;pruneTimer;clearTimer;statusTimer;lastPushed;lastPush=Number.NEGATIVE_INFINITY;nudged=!1;closed=!1;constructor(e){this.options=e;if(this.indexPath=sB(e.dataDir,os),this.features={...is(),...e.features},this.enabledFlag=e.enabled,this.usable)this.start();else this.idleMaintenance()}get enabled(){return this.enabledFlag}get running(){return this.worker!==void 0}get usable(){return this.enabledFlag&&this.features.fts5&&!this.closed}status(){let e={lag:0,bytes:this.bytes(),budget:this.budget(),indexed:0,total:0};if(!this.enabledFlag)return{...e,state:"disabled"};if(!this.features.fts5||this.failure)return{...e,state:"degraded"};let o=this.engineStatus,a=o?.backfill;if(!o||!a)return{...e,state:"backfilling"};if(a.state==="done"){let u=o.entries;return{...e,state:"ready",lag:o.lag,total:u,indexed:Math.max(0,u-o.lag)}}return{...e,lag:o.lag,total:Math.max(a.total,a.done),indexed:a.done,state:a.reason==="rebuild"?"rebuilding":"backfilling",...o.etaSec!==void 0?{etaSec:o.etaSec}:{}}}engine(){return this.engineStatus}bytes(){let e=0;for(let o of["","-wal"])try{e+=KC(this.indexPath+o).size}catch{}return e}budget(){let e=0;try{e=KC(this.options.store.path).size}catch{}return Math.max(lB,Math.round(e*0.6))}async setEnabled(e){if(this.closed||e===this.enabledFlag)return;if(this.enabledFlag=e,this.failure=void 0,this.restarts=0,e){if(this.clearTimer)clearInterval(this.clearTimer);if(this.clearTimer=void 0,this.usable)this.start();else this.idleMaintenance()}else await this.stopWorker(),this.idleMaintenance();this.pushStatus()}async rebuild(){if(!this.usable)return;await this.stopWorker(),ho(this.indexPath),this.failure=void 0,this.restarts=0,this.start()}nudge(){if(!this.worker||this.nudged)return;this.nudged=!0,queueMicrotask(()=>{this.nudged=!1,this.post({type:"dirty"})})}idle(){if(!this.worker)return Promise.resolve(this.status());let e=++this.flushID;return new Promise((o)=>{this.flushes.set(e,()=>o(this.status())),this.post({type:"flush",id:e})})}pause(e){let o=this.worker;if(!o)return e();Atomics.store(this.flags,Qe,1),o.postMessage({type:"pause"}),Atomics.wait(this.flags,It,0,cB);try{return e()}finally{Atomics.store(this.flags,Qe,0),Atomics.notify(this.flags,Qe)}}withIndex(e){if(!this.worker||!this.engineStatus)return;if(this.reader??=as(this.indexPath,this.options.store.path),!this.reader)return;return e(this.reader)}async close(){if(this.closed)return;if(this.closed=!0,this.clearTimer)clearInterval(this.clearTimer);if(this.statusTimer)clearTimeout(this.statusTimer);if(await this.stopWorker(),this.pruneTimer)clearTimeout(this.pruneTimer)}start(){if(this.worker||this.closed)return;Atomics.store(this.flags,Qe,0),Atomics.store(this.flags,It,0),this.engineStatus=void 0;let e=new Worker(new URL("./worker.js",import.meta.url));this.worker=e,e.unref?.(),e.onmessage=(o)=>this.receive(e,o.data),e.onerror=(o)=>this.crashed(e,o.message||"search worker crashed"),e.addEventListener("close",()=>this.crashed(e,"search worker exited")),e.postMessage({type:"init",flags:this.flags.buffer,options:{storePath:this.options.store.path,indexPath:this.indexPath,features:this.features,...this.options.engine}})}post(e){this.worker?.postMessage(e)}receive(e,o){if(e!==this.worker){if(o.type==="stopped")this.stopped?.();return}switch(o.type){case"status":this.update(o.status);break;case"flushed":{this.update(o.status),this.flushes.get(o.id)?.(),this.flushes.delete(o.id);break}case"error":if(o.fatal)this.crashed(e,o.message,!1);break;case"stopped":this.stopped?.();break}}update(e){if(this.engineStatus=e,e.queueDone>this.pruned)this.schedulePrune();this.pushStatus()}crashed(e,o,a=!0){if(e!==this.worker)return;if(this.worker=void 0,e.terminate(),this.closeReader(),this.resolveFlushes(),a&&this.restarts<pB&&this.usable)this.restarts++,this.start();else this.failure=o,console.error("search index unavailable:",o),this.idleMaintenance();this.pushStatus()}async stopWorker(){if(this.stopping)return this.stopping;let e=this.worker;if(!e)return;this.stopping=(async()=>{Atomics.store(this.flags,Qe,0),Atomics.notify(this.flags,Qe);let o=new Promise((a)=>{this.stopped=a});e.postMessage({type:"stop"}),await Promise.race([o,Bun.sleep(mB)]),e.terminate(),this.worker=void 0,this.stopped=void 0,this.closeReader(),this.resolveFlushes(),this.prune()})();try{await this.stopping}finally{this.stopping=void 0}}resolveFlushes(){for(let e of this.flushes.values())e();this.flushes.clear()}closeReader(){this.reader?.close(),this.reader=void 0}schedulePrune(){if(this.pruneTimer)return;let e=Math.max(0,iB-(performance.now()-this.lastPrune));this.pruneTimer=setTimeout(()=>{this.pruneTimer=void 0,this.prune()},e),this.pruneTimer.unref?.()}prune(){let e=this.engineStatus?.queueDone??0;if(e<=this.pruned)return;this.lastPrune=performance.now();try{this.options.store.db.query("DELETE FROM search_queue WHERE id <= ?").run(e),this.pruned=e}catch{}}idleMaintenance(){if(this.engineStatus=void 0,!this.enabledFlag)ho(this.indexPath);if(this.clearQueue(),!this.clearTimer&&!this.closed)this.clearTimer=setInterval(()=>this.clearQueue(),uB),this.clearTimer.unref?.()}clearQueue(){try{this.options.store.db.run("DELETE FROM search_queue")}catch{}}pushStatus(){let e=this.options.onStatus;if(!e||this.closed||this.statusTimer)return;let o=Math.max(0,aB-(performance.now()-this.lastPush)),a=()=>{if(this.statusTimer=void 0,this.closed)return;let u=this.status(),m=JSON.stringify({...u,bytes:0,budget:0,etaSec:0});if(m===this.lastPushed)return;this.lastPushed=m,this.lastPush=performance.now(),e(u)};if(o===0)a();else this.statusTimer=setTimeout(a,o),this.statusTimer.unref?.()}}import{existsSync as Eu,mkdirSync as IB,readdirSync as QC,readFileSync as WC,realpathSync as Dh,statSync as El,writeFileSync as Fh}from"fs";import{dirname as Il,isAbsolute as jh,relative as XC,resolve as EB}from"path";import{existsSync as Wc}from"fs";import{dirname as yB,join as Iu}from"path";import{mkdirSync as dB,writeFileSync as fB}from"fs";import{tmpdir as hB}from"os";import{join as HC}from"path";var yl=2000,Pe=30000;function c(e){return{content:[{type:"text",text:e}],details:void 0}}function xu(e,o){return e.map((a,u)=>{let m=a.length>yl?`${a.slice(0,yl)}\u2026 [line truncated]`:a;return`${String(o+u).padStart(6)} ${m}`}).join(`
81
+ `)}function le(e,o){if(e.length<=o)return e;let a=Math.floor(o*0.4),u=o-a,m=e.length-a-u,p=e.slice(a,e.length-u).split(`
82
+ `).length-1;return`${e.slice(0,a)}
83
+
84
+ \u2026 [${m} characters, ~${p} lines omitted] \u2026
85
+
86
+ ${e.slice(-u)}`}var gB=0;function et(e,o,a){if(e.length<=o)return e;let u=le(e,o);try{let m=a?Xo(a):HC(hB(),"basalt-output");dB(m,{recursive:!0});let p=HC(m,`${process.pid}-${Date.now().toString(36)}-${gB++}.txt`);return fB(p,e),`${u}
87
+ [Full output saved to ${p}; use read with offset/limit or grep on it instead of running the command again.]`}catch{return u}}var Ui=120000,Bi=600000,Ca;function xB(e){let o=e.replaceAll("\\","/").toLowerCase();return/\/windows\/(system32|sysnative|syswow64)\/bash\.exe$/.test(o)||o.includes("/windowsapps/")}function Gt(){if(Ca!==void 0)return Ca||void 0;let o=(process.env.PATH??"").split(";").map((u)=>u.trim()).filter(Boolean);for(let u of o){let m=Iu(u,"bash.exe");if(xB(m))continue;if(Wc(m))return Ca=m,m}for(let u of o){let m=Iu(u,"git.exe");if(Wc(m)){let p=yB(u),f=Iu(p,"bin","bash.exe");if(Wc(f))return Ca=f,f;let h=Iu(p,"usr","bin","bash.exe");if(Wc(h))return Ca=h,h}}let a=["C:\\Program Files\\Git\\bin\\bash.exe","C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe",process.env.LOCALAPPDATA?Iu(process.env.LOCALAPPDATA,"Programs","Git","bin","bash.exe"):"",process.env.LOCALAPPDATA?Iu(process.env.LOCALAPPDATA,"Programs","Git","usr","bin","bash.exe"):"","C:\\msys64\\usr\\bin\\bash.exe"].filter(Boolean);for(let u of a)if(Wc(u))return Ca=u,u;Ca="";return}class Zn{isWindows;utf8=new TextDecoder("utf-8",{fatal:!0});gbk=new TextDecoder("gbk");fallbackUtf8=new TextDecoder("utf-8");isGbk=!1;utf16=new TextDecoder("utf-16le");sniffPending=new Uint8Array(0);isUtf16=!1;gbkPending=new Uint8Array(0);constructor(e){this.isWindows=e??process.platform==="win32"}decodeGbk(e){let o=new Uint8Array(this.gbkPending.length+e.length);o.set(this.gbkPending),o.set(e,this.gbkPending.length);let a=0;while(a<o.length){if(o[a]<128){a+=1;continue}let m=o[a+1];if(m===void 0)break;let p=m>=48&&m<=57?4:2;if(a+p>o.length)break;a+=p}return this.gbkPending=o.slice(a),this.gbk.decode(o.subarray(0,a))}decode(e){if(e.length===0)return"";if(!this.isWindows)return this.fallbackUtf8.decode(e,{stream:!0});let o=e;if(this.sniffPending){let a=new Uint8Array(this.sniffPending.length+e.length);if(a.set(this.sniffPending),a.set(e,this.sniffPending.length),a.length<2)return this.sniffPending=a,"";this.sniffPending=void 0;let u=a[0]===255&&a[1]===254,m=!1;for(let p=1;p<a.length;p+=2)if(a[p]===0){m=!0;break}this.isUtf16=u||m,o=a}if(this.isUtf16)return this.utf16.decode(o,{stream:!0});if(this.isGbk)return this.decodeGbk(o);try{return this.utf8.decode(o,{stream:!0})}catch{return this.isGbk=!0,this.decodeGbk(o)}}flush(){if(!this.isWindows)return this.fallbackUtf8.decode();if(this.isUtf16)return this.utf16.decode();let e=this.sniffPending;if(e&&e.length>0)return this.sniffPending=void 0,this.fallbackUtf8.decode(e);if(!this.isGbk)return this.utf8.decode();let o=this.gbkPending;return this.gbkPending=new Uint8Array(0),o.length>0?this.gbk.decode(o):""}}function zt(e,o){let a=process.platform==="win32",u=o??"auto";if(!a)return{argv:["bash","-c",e],shellName:"bash",isWindows:!1};if(u==="cmd")return{argv:["cmd.exe","/c",e],shellName:"cmd",isWindows:!0};if(u==="bash")return{argv:[Gt()??"bash","-c",e],shellName:"bash",isWindows:!0};if(u==="powershell")return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0};let m=Gt();if(m)return{argv:[m,"-c",e],shellName:"bash",isWindows:!0};return{argv:["powershell","-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",e],shellName:"powershell",isWindows:!0}}async function jt(e,o){let a=await He(e,o.signal);if(a)return{output:a,code:126,timedOut:!1};let{argv:u,isWindows:m}=zt(e,o.shell),p=Bun.spawn(u,{cwd:o.cwd,stdin:"ignore",stdout:"pipe",stderr:"pipe",detached:!m,windowsHide:!0,env:{...process.env,...dn(o.cwd),PAGER:"cat",GIT_PAGER:"cat",GIT_TERMINAL_PROMPT:"0",GIT_EDITOR:"true",EDITOR:"true",...m?{PYTHONIOENCODING:"utf-8",LANG:process.env.LANG??"zh_CN.UTF-8"}:{},...o.extraPath?{[Object.keys(process.env).find((X)=>X.toLowerCase()==="path")??"PATH"]:o.extraPath}:{}}}),f=!1,h=()=>{try{if(m)p.kill();else process.kill(-p.pid,"SIGKILL")}catch{}},I=setTimeout(()=>{f=!0,h()},o.timeout);o.signal?.addEventListener("abort",h,{once:!0});let E=Pe*2,S="",R="",k=0,A=0,P="",M=(X=!1)=>{let te=k-S.length-R.length,L=te>0?`${S}
88
+ \u2026 [${te} characters omitted] \u2026
89
+ ${R}`:S+R;if(!X)return le(L,Pe);return et(P.length===k?P:L,Pe,o.cwd)},V=()=>{let X=new Zn;return async(te)=>{for await(let se of te){let he=X.decode(se);if(k+=he.length,P.length<4000000)P+=he;if(S.length<E)S+=he;else R=(R+he).slice(-E);if(o.onOutput){let Me=performance.now();if(Me-A>=80)A=Me,o.onOutput(M())}}let L=X.flush();if(L){if(k+=L.length,P.length<4000000)P+=L;if(S.length<E)S+=L;else R=(R+L).slice(-E)}}},_=Promise.all([V()(p.stdout),V()(p.stderr)]),J=await p.exited;if(clearTimeout(I),o.signal?.removeEventListener("abort",h),await Promise.race([_.then(()=>!1),Bun.sleep(2000).then(()=>!0)]))R+=`
90
+ [background processes are still running; their later output is not captured]`;return{output:M(!0),code:f?null:J,timedOut:f}}class Uh{seen=new Map;mark(e,o=El(e).mtimeMs){this.seen.set(e,o)}check(e){let o=this.seen.get(e);if(o===void 0)return"unread";return El(e).mtimeMs!==o?"changed":void 0}}var zC=2000,bB=500,SB=10485760,xl=20,wB=6,TB=40000,RB=80000;function kB(e){if(e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71&&e[4]===13&&e[5]===10&&e[6]===26&&e[7]===10)return"image/png";if(e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255)return"image/jpeg";if(e.length>=6&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56)return"image/gif";if(e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80)return"image/webp";return}function YC(e,o,a=[],u){let m=(P)=>jh(P)?P:EB(e,P),p=(P)=>{let M=XC(e,P);return M&&!M.startsWith("..")&&!jh(M)?M:P},f=(P)=>{let M=P;while(!Eu(M)&&Il(M)!==M)M=Il(M);let V=Dh(M);if(a.some((_)=>Eu(_)&&JC(Dh(_),V))&&!JC(Dh(e),V))throw Error("External directories are read-only")},h=(P,M,V)=>{let _=m(P);if(!Eu(_))throw Error(`No such file or directory: ${_}${CB(_)}`);let J=El(_);if(J.isDirectory()){let ee=QC(_,{withFileTypes:!0}).map((Ge)=>Ge.isDirectory()?`${Ge.name}/`:Ge.name).sort(),be=ee.slice(0,bB),Xe=ee.length-be.length;return c(`${be.join(`
91
+ `)}${Xe>0?`
92
+ \u2026 and ${Xe} more entries`:""}`||"(empty directory)").content}let j=WC(_),X=kB(j);if(X){if(J.size>SB)throw Error(`${_} exceeds the 10 MB image limit (${J.size} bytes)`);return o.mark(_),[{type:"text",text:`Read image ${p(_)} (${X}, ${J.size} bytes)`},{type:"image",data:j.toString("base64"),mimeType:X}]}if(j.subarray(0,8192).includes(0))throw Error(`${_} looks like a binary file (${J.size} bytes)`);o.mark(_);let te=j.toString("utf8");if(!te)return c("(empty file)").content;let L=te.replace(/\r?\n$/,"").split(/\r?\n/),se=(M??1)-1;if(se>=L.length)throw Error(`offset ${M} is past the end of the file (${L.length} lines)`);let he=Math.min(L.length,se+(V??zC)),Me=0,We=se;while(We<he){let ee=L[We]?.length??0;if(We>se&&Me+ee>TB)break;Me+=ee,We++}let Q=xu(L.slice(se,We),se+1);if(We<he)Q+=`
93
+
94
+ (Showing lines ${se+1}-${We} of ${L.length} (truncated at line ${We} due to safety budget). Use offset/limit to read specific windows.)`;else if(se>0||We<L.length)Q+=`
95
+
96
+ (Showing lines ${se+1}-${We} of ${L.length}. Use offset/limit to read other parts.)`;return c(Q).content},I=T({name:"read",label:"Read file",description:`Read files or directories from the local filesystem. Returns lines prefixed with line numbers (cat -n style); the number and tab are not part of the file.
97
+ - path may be absolute or relative to the working directory.
98
+ - By default reads up to ${zC} lines from the start. For large files, pass offset (1-based line) and limit to read a window.
99
+ - Lines longer than ${yl} characters are truncated.
100
+ - Reading a directory lists its entries (directories end with /).
101
+ - Image files (PNG/JPEG/GIF/WebP) are returned as images you can view, e.g. screenshots taken by other tools.
102
+ - To read several files at once, give paths instead of path (up to ${xl}, each with its own optional offset/limit); each one's output starts with a "==> path <==" line, and one that fails does not stop the others. Put everything you already know you need (the task file, the code, its tests, a directory listing) into one call.
103
+ - Always read a file before editing or overwriting it.`,parameters:l({path:n(s({description:"File or directory path"})),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"})),paths:n(F(l({path:s({description:"File or directory path"}),offset:n(x({minimum:1,description:"1-based line number to start from"})),limit:n(x({minimum:1,description:"Maximum number of lines to return"}))}),{maxItems:xl,description:"Several files or directories to read in one call, instead of path"}))}),async execute(P,M){let V=[...M.path!==void 0?[{path:M.path,offset:M.offset,limit:M.limit}]:[],...M.paths??[]];if(V.length===0)throw Error("Give path, or paths to read several files");if(V.length===1){let te=V[0];return{content:h(te.path,te.offset,te.limit),details:void 0}}if(V.length>xl)throw Error(`Read at most ${xl} paths per call`);let _=[],J=[],j=0,X=(te)=>{let L=_.at(-1);if(te.type==="text"&&L?.type==="text")L.text+=`
104
+
105
+ ${te.text}`;else _.push(te)};for(let te of V){let L=`==> ${p(m(te.path))} <==`;if(j>=RB){X({type:"text",text:`${L}
106
+ (Skipped due to total read safety budget; read in separate calls)`});continue}try{let se=h(te.path,te.offset,te.limit);for(let he=0;he<se.length;he++){let Me=se[he];if(!Me)continue;if(Me.type==="text")j+=Me.text.length,X(he===0?{...Me,text:`${L}
107
+ ${Me.text}`}:Me);else X(Me)}}catch(se){let he=se instanceof Error?se.message:String(se);J.push(he),X({type:"text",text:`${L}
108
+ Error: ${he}`})}}if(J.length===V.length)throw Error(J.join(`
109
+ `));return{content:_,details:void 0}}}),E=async(P,M,V,_)=>{let J=_?.update,j=await jt(P,{cwd:e,timeout:120000,signal:V,extraPath:u?.extraPath,shell:typeof u?.shell==="function"?u.shell():u?.shell,onOutput:J?(he)=>J(c(`${_.prefix}
110
+
111
+ $ ${P}
112
+ ${he.trimEnd()}`)):void 0}),X=j.output.trimEnd()||"(no output)",te=j.timedOut?"killed after 120s timeout":j.code===0?"exit code 0":`exit code ${j.code}`,L=j.timedOut||j.code!==0,se=L?`
113
+ ${M}; only the command failed. Fix forward with edit; do not repeat the change.`:"";return{out:`
114
+
115
+ $ ${P}
116
+ ${X}
117
+ [${te}]${se}`,failed:L}},S=(P,M=!1)=>{let V=o.check(P);if(V==="changed")return`Note: ${p(P)} changed since you last read it (edited by the user or another process); this was applied to its current content.`;if(V==="unread"&&M)return`Note: ${p(P)} existed and had not been read; it was replaced whole.`;return},R=T({name:"write",label:"Write file",executionMode:"sequential",description:`Create a new file or completely overwrite an existing one. Parent directories are created as needed.
118
+ - An existing file is replaced whole, including changes made since you last read it.
119
+ - Prefer the edit tool for changing existing files; use write for new files or full rewrites.
120
+ - then_run runs a command (the tests, a build, the new script itself) right after the file is written and returns its output, saving a step. If the command fails, the file is still written: fix it with edit, do not write it again.
121
+ - Do not create documentation or README files unless asked.`,parameters:l({path:s({description:"File path"}),content:s({description:"The full file content"}),then_run:n(s({description:"A command to run right after writing, such as the tests, a build or the script itself"}))}),async execute(P,M,V,_){let J=m(M.path);f(J);let j=Eu(J),X;if(j){if(El(J).isDirectory())throw Error(`${J} is a directory`);X=S(J,!0)}IB(Il(J),{recursive:!0}),Fh(J,M.content),o.mark(J);let te=M.content?M.content.split(`
122
+ `).length:0,L=`${j?"Overwrote":"Created"} ${p(J)} (${te} lines)${X?`
123
+ ${X}`:""}`;if(M.then_run){let se=await E(M.then_run,`${p(J)} was written as given`,V,{prefix:L,update:_});if(L+=se.out,se.failed)return{...c(L),isError:!0}}return c(L)}}),k=(P,M,V,_)=>{let J=m(P);if(!Eu(J))throw Error(`File not found: ${J} (use write to create it)`);f(J);let j=S(J),X=WC(J,"utf8"),te=X,L=te.includes(`\r
124
+ `),se=[],he=[],Me=0,We=0;return M.forEach((Q,ee)=>{let be=_?`edits[${V+ee}]: `:"";try{if(Q.old_string===Q.new_string)throw Error(`${be}old_string and new_string are identical`);if(!Q.old_string)throw Error(`${be}old_string is empty (use write to create or replace a whole file)`);let Xe=L&&!Q.old_string.includes(`\r
125
+ `),Ge=Xe?Q.old_string.replace(/\n/g,`\r
126
+ `):Q.old_string,sr=Xe?Q.new_string.replace(/\n/g,`\r
127
+ `):Q.new_string,Re=AB(te,Ge).map((Ot)=>[Ot,Ot+Ge.length]);if(Re.length===0)Re=PB(te,Ge);if(Re.length===0)throw Error(`${be}old_string not found in ${p(J)}; read the relevant lines and copy the exact text.${$B(te,Ge)}`);if(Re.length>1&&!Q.replace_all){let Ot=Re.map(([it])=>VC(te,it)).join(", ");throw Error(`${be}old_string occurs ${Re.length} times (lines ${Ot}); add surrounding lines to make it unique, or set replace_all.`)}let ke=VC(te,Re[0][0]),Wt=Q.replace_all?Re:[Re[0]],ft="",Nt=0;for(let[Ot,it]of Wt)ft+=te.slice(Nt,Ot)+sr,Nt=it;te=ft+te.slice(Nt),Me++,We+=Wt.length;let gr=te.split(/\r?\n/),lr=ke+sr.split(/\r?\n/).length-1,Zt=Math.max(1,ke-1),ot=Math.min(gr.length,lr+1);if(ot-Zt+1<=wB+2)se.push(xu(gr.slice(Zt-1,ot),Zt));else se.push(`${xu(gr.slice(Zt-1,ke+1),Zt)}
128
+ \u2026 (${lr-ke-3} lines as given)
129
+ ${xu(gr.slice(lr-2,ot),lr-1)}`)}catch(Xe){he.push(Xe instanceof Error?Xe.message:String(Xe))}}),{path:J,original:X,content:te,echoes:se,applied:Me,total:We,count:M.length,note:j,failed:he}},A=T({name:"edit",label:"Edit file",executionMode:"sequential",description:`Replace an exact snippet of an existing file. old_string must match the file text exactly (copy it from read output, without the line-number prefix) and be unique, unless replace_all is set.
130
+ - No need to read the file again after your own edits. Include enough surrounding lines to make old_string unique.
131
+ - For several changes give edits instead of old_string/new_string: they apply in order, each to the result of the previous one in its file. An item may name its own path, so one call can change several files.
132
+ - Replacements that fail to match do not block the batch: the rest are applied and saved, and the failures are listed at the end of the result, which is flagged as an error. Fix and retry only the failed ones. A call where nothing applies fails as a whole with nothing saved.
133
+ - Put every replacement of one logical change (an import, a helper and its call sites, the matching test) into one call's edits, not one call per spot.
134
+ - To create a file use write; to delete or move files use bash.
135
+ - then_run runs a command (tests, build, linter) right after a successful change and returns its output, saving a step. If the command fails, the change is still applied.
136
+ - Returns each edited region with line numbers and one line of context around it; a long new_string is shown by its first and last lines.`,parameters:l({path:n(s({description:"File path (the default for edits items without their own path)"})),old_string:n(s({description:"The exact text to replace (only when edits is absent)"})),new_string:n(s({description:"The replacement text (only when edits is absent)"})),replace_all:n(N({description:"Replace every occurrence (default false)"})),edits:n(F(l({path:n(s({description:"The file of this replacement, when it is not path"})),old_string:s({description:"The exact text to replace"}),new_string:s({description:"The replacement text"}),replace_all:n(N({description:"Replace every occurrence (default false)"}))}),{description:"Several replacements, instead of old_string / new_string"})),then_run:n(s({description:"A command to run right after the change, such as the tests, a build or a linter"}))}),async execute(P,M,V,_){let J=M.edits&&M.edits.length>0?M.edits.map((Q)=>({path:Q.path??M.path,step:Q})):M.old_string!==void 0&&M.new_string!==void 0?[{path:M.path,step:{old_string:M.old_string,new_string:M.new_string,replace_all:M.replace_all}}]:[];if(J.length===0)throw Error("Give old_string and new_string, or edits");let j=J.length>1,X=new Map;J.forEach((Q,ee)=>{if(!Q.path)throw Error(`${j?`edits[${ee}]: `:""}path is required`);let be=m(Q.path),Xe=X.get(be)??{raw:Q.path,steps:[],offset:ee};Xe.steps.push(Q.step),X.set(be,Xe)});let te=[],L=[];for(let Q of X.values())try{let ee=k(Q.raw,Q.steps,Q.offset,j);if(ee.applied>0)te.push(ee);L.push(...ee.failed)}catch(ee){let be=ee instanceof Error?ee.message:String(ee);L.push(`${j?`edits[${Q.offset}]: `:""}${be}`)}if(te.length===0)throw Error(L.join(`
137
+ `));let se=[];try{for(let Q of te)Fh(Q.path,Q.content),se.push(Q)}catch(Q){for(let ee of se)Fh(ee.path,ee.original);throw Q}for(let Q of te)o.mark(Q.path);let Me=te.map((Q)=>{let ee=Q.total===1?"1 occurrence":`${Q.total} occurrences`,be=Q.note?`
138
+ ${Q.note}`:"";if(!j)return`Edited ${p(Q.path)} (${ee}).${be}
139
+ ${Q.echoes[0]}`;let Xe=Q.failed.length>0?`, ${Q.failed.length} failed`:"";return`Edited ${p(Q.path)} (${Q.applied} edits${Xe}, ${ee}). Regions are shown as they were right after each edit; later edits may shift line numbers.${be}
140
+ ${Q.echoes.map((Ge,sr)=>`--- edit ${sr+1}
141
+ ${Ge}`).join(`
142
+ `)}`}).join(`
143
+
144
+ `),We=!1;if(M.then_run){let Q=await E(M.then_run,"The edits above were applied",V,{prefix:Me,update:_});if(Me+=Q.out,Q.failed)We=!0}if(L.length>0)Me+=`
145
+
146
+ ${L.length===1?"1 edit":`${L.length} edits`} failed; the other edits were applied and saved. Fix and retry only the failed edits:
147
+ - ${L.join(`
148
+ - `)}`,We=!0;return We?{...c(Me),isError:!0}:c(Me)}});return[ve(I,"cat","view","read_file","view_file","open_file","open"),ve(R,"write_file","create_file","new_file","save_file"),ve(A,"edit_file","str_replace","str_replace_editor","replace","replace_in_file","modify_file","multiedit")]}function AB(e,o){let a=[];for(let u=e.indexOf(o);u!==-1;u=e.indexOf(o,u+o.length))a.push(u);return a}function VC(e,o){let a=1;for(let u=0;u<o;u++)if(e.charCodeAt(u)===10)a++;return a}function PB(e,o){let a=o.replace(/\r?\n$/,"").split(/\r?\n/).map((I)=>I.trimEnd()),u=[],m=e.split(`
149
+ `),p=0;for(let I of m)u.push(p),p+=I.length+1;let f=m.map((I)=>I.replace(/\r$/,"").trimEnd()),h=[];for(let I=0;I+a.length<=f.length;I++)if(a.every((E,S)=>f[I+S]===E)){let E=I+a.length-1,S=u[E]+m[E].replace(/\r$/,"").length,R=o.endsWith(`
150
+ `)&&S<e.length?e[S]==="\r"?2:1:0;h.push([u[I],S+R]),I+=a.length-1}return h}function $B(e,o){let a=(h)=>h.replace(/\s+/g," ").trim(),u=a(o);if(!u)return"";let m=e.split(/\r?\n/),p=o.split(/\r?\n/).length;for(let h=0;h+p<=m.length;h++)if(a(m.slice(h,h+p).join(`
151
+ `))===u)return` A match ignoring whitespace exists at line ${h+1}; copy the exact indentation and line breaks from the read output:
152
+ ${le(xu(m.slice(h,h+p),h+1),4000)}`;let f=o.split(/\r?\n/).find((h)=>h.trim())?.trim();if(f){let h=m.findIndex((I)=>I.includes(f));if(h!==-1)return` Its first line appears at line ${h+1}, but the following lines differ. Read the file again and copy the exact text.`}return" Read the file again to get its current content."}function CB(e){let o=Il(e);if(!Eu(o))return"";let u=e.slice(o.length+1).toLowerCase().replace(/\.[^.]*$/,"");if(!u)return"";let m=QC(o).filter((p)=>{let f=p.toLowerCase().replace(/\.[^.]*$/,"");return f&&(f.includes(u)||u.includes(f))}).slice(0,5);return m.length?`. Did you mean: ${m.join(", ")}?`:""}function JC(e,o){let a=XC(e,o);return a===""||!a.startsWith(`..${process.platform==="win32"?"\\":"/"}`)&&a!==".."&&!jh(a)}var Bh=20,Gh=80,vB=5,MB=(e)=>e!==void 0&&e>0?e:void 0;function ZC(e,o){let a=Jn(e,o)??Yn(e,o);if(!a)throw Error(`No user message with seq ${o}`);return a}function bl(e,o){let a=(f)=>{if(o)return o(f);if(f.source&&f.source!=="self"||f.session_id)throw Error("History source is unavailable");return{sessionID:"self",records:e()}},u=(f)=>{let h=a(f),I=MB(f.seq);return{scope:h,seq:I,runs:()=>bt(h.records),reference:`session_id=${h.sessionID}`,both:I!==void 0&&f.chunk_id?`(seq and chunk_id both given; seq takes precedence, chunk_id ignored)
153
+ `:""}},m=T({name:"history_grep",label:"Search history",description:`Search authorized conversation history (source=self by default; references are scoped to that session), including parts folded out of your context (tool outputs, intermediate messages). Fixed-string match, not a regex; "also" adds more strings that must be on the same line.
154
+ - Scope with chunk_id (e.g. "r12") from a chunk-summary or work-state, or with seq for a long user message reference \u2014 normally just one (if both are given, seq wins).
155
+ - Returns matching lines with 2 lines of context and their line offsets; page further matches with offset, read more with history_list.`,parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),pattern:s({minLength:1,description:"Text to search for"}),also:n(F(s({minLength:1}),{maxItems:vB,description:"More texts that must appear on the same line as pattern (AND), to narrow a common pattern"})),chunk_id:n(s({description:"Only search this chunk"})),seq:n(x({description:"Only search this user message (from a user-text-reference)"})),case_sensitive:n(N({description:"Default false"})),head_limit:n(x({minimum:1,maximum:Bh,description:`Hits to return (default ${Bh})`})),offset:n(x({minimum:0,description:"Matches to skip, to page past the first head_limit (default 0)"}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),A;if(E!==void 0)A=[ZC(I.records,E)];else{let se=S(),he=h.chunk_id?se.filter((Me)=>Me.id===h.chunk_id):se;if(h.chunk_id&&!he.length)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);A=he.map(xr)}let P=(se)=>h.case_sensitive?se:se.toLowerCase(),M=[h.pattern,...(h.also??[]).filter(Boolean)].map(P),V=h.head_limit??Bh,_=h.offset??0,J=[],j=new Map,X=0;for(let se of A)se.forEach((he,Me)=>{let We=P(he.text);if(!M.every((ee)=>We.includes(ee)))return;if(j.set(he.chunk,(j.get(he.chunk)??0)+1),X++,X<=_||J.length>=V)return;let Q=se.slice(Math.max(0,Me-2),Me+3);J.push(`${R} chunk ${he.chunk} line ${he.line}:
156
+ ${cn(Q," ")}`)});if(!X)return c(`${k}No matches`);if(!J.length)return c(`${k}No matches at offset ${_} (total ${X})`);let te=X-_-J.length,L=j.size>1?` (all matches by chunk: ${[...j].map(([se,he])=>`${se} ${he}`).join(", ")})`:"";return c(`${k}${J.join(`
157
+
158
+ `)}${te>0?`
159
+
160
+ \u2026 ${te} more matches${L}; continue with offset=${_+J.length}, or narrow with chunk_id or a longer pattern`:""}`)}}),p=T({name:"history_list",label:"Read history",description:'Read authorized conversation history (source=self by default; never reuse a reference in a different session) by line range, including parts folded out of your context. Pass chunk_id (e.g. "r12") to read a chunk, or seq to read a long user message \u2014 normally just one of them (if both are given, seq wins). Line offsets are local to the chunk or message.',parameters:l({source:n(s()),session_id:n(s({description:"Source session ID from the reference"})),chunk_id:n(s({description:"Chunk to read"})),seq:n(x({description:"User message to read (from a user-text-reference)"})),offset:n(x({minimum:0,description:"First line (default 0)"})),limit:n(x({minimum:1,maximum:Gh,description:`Lines to return (default ${Gh})`}))}),async execute(f,h){let{scope:I,seq:E,runs:S,reference:R,both:k}=u(h),A;if(E!==void 0)A=ZC(I.records,E);else if(h.chunk_id){let _=S().find((J)=>J.id===h.chunk_id);if(!_)throw Error(`No chunk ${h.chunk_id}. Chunk IDs look like r12.`);A=xr(_)}else{let _=S().map((J)=>`${R} ${J.id} (${J.status}, ${xr(J).length} lines)`);return c(_.length?`Pass chunk_id or seq. Chunks in this session:
161
+ ${_.join(`
162
+ `)}`:"This session has no history yet")}let P=h.offset??0,M=A.slice(P,P+(h.limit??Gh));if(!M.length)return c(`No lines at offset ${P} (total ${A.length})`);let V=A.length-P-M.length;return c(`${k}${R} ${E!==void 0?`seq=${E}`:h.chunk_id}
163
+ ${cn(M)}${V>0?`
164
+
165
+ \u2026 ${V} more lines; continue with offset=${P+M.length}`:""}`)}});return[m,p]}import{existsSync as OB,statSync as e0}from"fs";import{isAbsolute as t0,relative as _B,resolve as r0}from"path";var Sl=200,LB=30000,wl=Bun.which("rg");async function Kh(e,o,a){let u=Bun.spawn(e,{cwd:o,stdout:"pipe",stderr:"pipe",stdin:"ignore",signal:a,windowsHide:!0}),[m,p,f]=await Promise.all([new Response(u.stdout).text(),new Response(u.stderr).text(),u.exited]);if(f>1)throw Error(p.trim()||`${e[0]} exited with ${f}`);return m}function n0(e){let o=(p)=>p?t0(p)?p:r0(e,p):e,a=(p)=>{let f=_B(e,p);return f&&!f.startsWith("..")&&!t0(f)?f:p},u=T({name:"glob",label:"Find files",description:`Find files by name pattern, e.g. "**/*.ts" or "src/**/test_*.py". Returns paths sorted by modification time (newest first).
166
+ - Respects .gitignore and skips .git. Use it instead of find or ls -R.
167
+ - To search file contents, use grep.`,parameters:l({pattern:s({description:"Glob pattern, matched relative to path"}),path:n(s({description:"Directory to search (default: working directory)"}))}),async execute(p,f,h){let I=o(f.path),E=!1;try{E=e0(I).isDirectory()}catch{}if(!E)throw Error(`Directory not found: ${a(I)}`);let S;if(wl)S=(await Kh([wl,"--files","--hidden","--no-ignore-parent","--glob","!.git","--glob",f.pattern],I,h)).split(`
168
+ `).filter(Boolean);else{S=[];for await(let P of new Bun.Glob(f.pattern).scan({cwd:I,dot:!0}))if(!/(^|\/)(\.git|node_modules)\//.test(P))S.push(P)}if(!S.length)return c("No files found");let R=S.map((P)=>{let M=r0(I,P);try{return{path:M,time:e0(M).mtimeMs}}catch{return{path:M,time:0}}});R.sort((P,M)=>M.time-P.time);let k=R.slice(0,Sl).map((P)=>a(P.path)),A=S.length-k.length;return c(`${k.join(`
169
+ `)}${A>0?`
170
+ \u2026 ${A} more files; narrow the pattern`:""}`)}}),m=T({name:"grep",label:"Search file contents",description:`Search file contents with a regular expression (ripgrep syntax). Respects .gitignore.
171
+ - output "files" (default) lists matching files; "content" shows matching lines as path:line:text; "count" shows matches per file.
172
+ - Narrow with glob (e.g. "*.ts", "src/**/*.go") and path. Use context to see lines around matches in content mode.
173
+ - Escape regex metacharacters for literal search (e.g. "foo\\(" to find "foo(").
174
+ - Use this instead of running grep or rg through bash.`,parameters:l({pattern:s({description:"Regular expression"}),path:n(s({description:"File or directory to search (default: working directory)"})),glob:n(s({description:"Only search files matching this glob"})),output:n(g([i("files"),i("content"),i("count")],{description:"Output mode (default files)"})),ignore_case:n(N()),context:n(x({minimum:0,maximum:20,description:"Lines of context (content mode)"}))}),async execute(p,f,h){let I=o(f.path);if(!OB(I))throw Error(`Path not found: ${a(I)}`);let E=f.output??"files",S;if(wl){let A=[wl,"--hidden","--no-ignore-parent","--glob","!.git","--max-columns","400","--max-columns-preview"];if(f.ignore_case)A.push("-i");if(f.glob)A.push("--glob",f.glob);if(E==="files")A.push("-l");else if(E==="count")A.push("-c");else if(A.push("-n","--no-heading"),f.context)A.push("-C",String(f.context));A.push("--",f.pattern,I),S=await Kh(A,e,h)}else{let A=["grep","-rE","--exclude-dir=.git","--exclude-dir=node_modules"];if(f.ignore_case)A.push("-i");if(f.glob)A.push(`--include=${f.glob}`);if(E==="files")A.push("-l");else if(E==="count")A.push("-c");else if(A.push("-n"),f.context)A.push(`-C${f.context}`);A.push("--",f.pattern,I),S=await Kh(A,e,h)}let R=`${e}/`,k=S.split(`
175
+ `).filter(Boolean).map((A)=>A.startsWith(R)?A.slice(R.length):A).filter((A)=>E!=="count"||!A.endsWith(":0"));if(!k.length)return c("No matches");if(E==="files"&&k.length>Sl)return c(`${k.slice(0,Sl).join(`
176
+ `)}
177
+ \u2026 ${k.length-Sl} more files; narrow the search`);return c(et(k.join(`
178
+ `),LB,e))}});return[ve(u,"find","find_files","list_files","file_search","ls","list","list_dir"),ve(m,"rg","ripgrep","search_files","search_code","code_search","grep_search","text_search")]}function o0(e){return ve(T({name:"todo",label:"Manage todos",description:`Maintain a task list for the current work, visible to the user. Each call replaces the whole list.
179
+ Do not use it for a single deliverable, even a complex one (a feature, a bug fix, a module with its tests): work through that directly and give a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later.
180
+ - Items are short outcomes of a few words. Reading files, checking the environment and the final summary are not items.
181
+ - Keep exactly one item in_progress. Update the list only when an item's status really changes, together with your next action in the same response, not as a turn of its own; several items can be marked completed in one call.
182
+ - Only mark completed when it is really done (tests pass, nothing left half-finished). If blocked, keep it in_progress and add an item for the blocker.`,parameters:l({todos:F(l({content:s({minLength:1,description:"What to do, in imperative form"}),status:g(Yi.map((o)=>i(o)))}))}),async execute(o,a){let u=a.todos.map((f)=>({content:f.content,status:f.status}));e(u);let m=u.filter((f)=>f.status==="completed").length,p=u.find((f)=>f.status==="in_progress");return c(`Todo list updated (${m}/${u.length} completed${p?`; in progress: ${p.content}`:""})`)}}),"todo_write","update_plan","update_todos")}function s0(e){let o=de(e);return{target:o,hard:o,index:o}}class Tl{records;cwd;policy;defaultPolicy;recoveryRatio=1;lastMessageCount=0;constructor(e,o=()=>{return},a){this.records=e;this.cwd=o;if(a)this.defaultPolicy=new ln(e,a,o)}use(e){this.policy=e,this.recoveryRatio=1}get activePolicy(){return this.policy??this.defaultPolicy}budget(e){return this.activePolicy?.budget?.(e)??s0(e)}get calibrationRatio(){return this.activePolicy?.calibrationRatio??1}calibrate(e){this.activePolicy?.calibrate(e)}previewLimit(e){return this.activePolicy?.previewLimit(e)??de(e)}prepare(e,o,a,u,m=!1){if(this.activePolicy)return this.activePolicy.prepare(e,o,a,u);let p=e.reduce((E,S)=>E+G(S),0)+Rt(o),f=Math.max(0,de(a)*this.recoveryRatio-p),h=Ce(u??this.records(),a,s0(a),{cwd:this.cwd()}).messages,I=h.reduce((E,S)=>E+G(S),0);if(m&&I>f)throw Error("\u4E0A\u4E0B\u6587\u4E0D\u8DB3\uFF1A\u5DF2\u6709\u53D1\u73B0\u4FDD\u7559\u5728\u5B50\u4F1A\u8BDD\u5386\u53F2\u4E2D");while(I>f&&h.length>1){let E=h.shift();if(E)I-=G(E);while(h[0]?.role==="toolResult"){let S=h.shift();if(S)I-=G(S)}}if(I>f){let E=h.at(-1),S=E&&"content"in E&&typeof E.content==="string"?E.content:"[Context omitted: use history tools to retrieve earlier messages.]";h.length=0;let R=S;while(R&&G({role:"user",content:R,timestamp:0})>f)R=R.slice(Math.ceil(R.length/2));if(R)h.push({role:"user",content:R,timestamp:0});I=h.reduce((k,A)=>k+G(A),0)}return this.lastMessageCount=h.length,{messages:[...e,...h],estimate:p+I}}settle(e){this.activePolicy?.settle?.(e)}recover(e){if(this.activePolicy)return this.activePolicy.recover(e);if(this.lastMessageCount<=1)return!1;return this.recoveryRatio*=0.5,!0}}import{existsSync as Wh,readFileSync as NB}from"fs";import{homedir as qB}from"os";import{dirname as i0,join as zh,resolve as DB}from"path";var FB=`You are Basalt, an autonomous software engineering agent. You work directly in the user's project on their machine: you read and edit files and run commands to get real work done, not just give advice.
183
+
184
+ # How to work
185
+
186
+ - Complete the task end to end. Keep going until the user's request is fully resolved before ending your turn: investigate, make the change, verify it. Do not stop halfway to report a plan or ask "should I continue?" when the next step is clear.
187
+ - Ask the user only when you are genuinely blocked: the request is ambiguous in a way that changes the outcome, or the action is destructive or irreversible. Otherwise make a reasonable choice, state the assumption briefly, and proceed.
188
+ - If the user only asks a question or asks for a plan or review, answer it; do not start changing files. For a review, lead with findings: bugs, risks, behavior regressions and missing tests, ordered by severity with file:line. Keep any summary short and after the findings.
189
+ - Do not use the todo tool for a single deliverable, even a complex one (implementing a feature, fixing a bug, writing a module and its tests): work through it directly with a short progress note now and then. Use it only when the user asks for a checklist, when there are several independent deliverables, or when the work spans phases you may need to resume later. Never make reading, environment checks or the final summary into items, and update it only together with your next action, never as a turn of its own.
190
+
191
+ # Making changes
192
+
193
+ - Investigate before changing anything. Find the relevant code with grep/glob, read it, and understand how it is used. Edit from what you have actually seen: a read, or grep output with enough context to copy the text exactly.
194
+ - Verify unfamiliar technical entities instead of recalling them. When a task involves a library, API, tool or version you do not confidently recognize, check the project first: package manifests and lockfiles, \`--version\`, or the installed sources. A fluent answer built on an outdated memory looks right and is wrong. Never guess URLs; use only ones the user or the project gave you.
195
+ - Follow the conventions of the existing code: style, naming, structure, libraries, error handling, comment density, test layout. Before using a library, confirm the project already depends on it.
196
+ - Fix the root cause, not the symptom. Keep changes minimal and focused on the task; do not refactor, rename or "clean up" unrelated code, and do not add features that were not requested. Between two correct approaches, prefer the smaller one. Do not add backward-compatibility code unless something concrete needs it (persisted data, shipped behavior, external consumers, an explicit requirement).
197
+ - Prefer editing an existing file to creating a new one. Do not create documentation or markdown files nobody asked for.
198
+ - Do not add comments that narrate the change ("added this", "fixed bug"). Comment only where the code is not self-explanatory, in the style of the surrounding code.
199
+
200
+ # Verifying
201
+
202
+ - Verify behaviour the way the user would see it. When asked to test a feature, or after a change with user-visible effects, run the real thing first: start the app or server with bash background=true, exercise the changed path (curl an endpoint, run the CLI with real input, or drive a web UI with the browser tools: open, act, then browser_screenshot and look at the image), and confirm the result matches the requirement. Unit tests complement this; they do not replace it, and "the tests pass" is not evidence the feature works.
203
+ - For code with no runnable surface (a library, a refactor, types, build config), or when the app cannot be started here, run the most specific tests, type checker, linter or build instead \u2014 find how in the project's README, package scripts, Makefile or CI config \u2014 and say what you could not exercise.
204
+ - Once the change is verified, stop: re-verify only after new changes, failures or a concrete unresolved concern. Do not re-run a check that already passed when nothing it covers has changed. Kill servers and close pages you started.
205
+ - Do not re-read a file after your own edit or re-check mkdir/delete/move results: an edit result already shows the new content, and a failing call reports an error. Re-read only if someone else changed the file.
206
+ - When a step fails, read the error and diagnose why before retrying. Do not loop on the same failing approach; after two failed attempts, step back and reconsider. If a tool call is blocked, do not retry it unchanged; follow the stated reason or ask the user.
207
+
208
+ # Tools
209
+
210
+ - Tool calls are the only way to act; describing an action does not perform it.
211
+ - Use the dedicated tools for files: read to view (paths reads several files in one call), edit for replacements (give edits for several changes, even across files), write to create or rewrite a file, grep to search contents, glob to find files. A quick read-only look (ls, cat, sed -n) may share a bash command with other work, such as listing a directory while checking tool versions; to only view or edit a file, use read and edit.
212
+ - Create files you will keep or edit later with write, passing then_run to run them or their tests in the same step. A file written by a bash heredoc has not been read through the tools, so a later edit of it costs an extra step; a heredoc is fine for a throwaway script that the same command runs.
213
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
214
+ - In bash, search with rg / rg --files when it exists (much faster than grep/find). Do not join commands with echo or printf separators such as an echo '====' line; the output gets noisy. Do not use python or other scripts just to print or edit file contents when read, edit will do. Backticks and $() inside a command still execute, so escape text carefully.
215
+ - Put every tool call you already know into one response. Independent reads and searches run in parallel; calls that change things (edit, write, bash) run one after another in the order you give them, so you can edit a file and run its tests in the same response. Put all replacements of one logical change (for example an import, a helper and its call sites, plus the matching test) into one edit call's edits and pass then_run with the test command, instead of one edit per spot followed by a separate test run. Pass then_run to write as well. When probing behaviour, batch the checks into one script instead of one command each.
216
+ - Use bash for builds, tests, git, package managers and running programs. Each bash call starts in the project directory; use absolute or project-relative paths and chain dependent steps with &&.
217
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished, including dev servers you start to verify a change. Do not busy-wait or poll repeatedly.
218
+
219
+ # Honesty
220
+
221
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
222
+ - Report only what tool results show. Never present output, test results or file contents no tool returned, and never claim something works without evidence.
223
+ - When the user asks you to run something, run it, even when you can predict the result.
224
+ - If a step failed, was skipped or could not be verified, say which one and why.
225
+
226
+ # Safety
227
+
228
+ - Do not run destructive or irreversible commands (rm -rf on broad paths, git reset --hard, git push --force, dropping databases, killing unrelated processes) unless the user explicitly asked for exactly that.
229
+ - Never commit, push, create branches or rewrite git history unless the user asks. If asked to commit, write a concise message that explains why, matching the repository's existing style.
230
+ - Do not revert or overwrite changes you did not make; the user may be editing files at the same time. If a file changed unexpectedly, read it again and work with the new content.
231
+ - Never print, log or commit secrets such as API keys, tokens or passwords.
232
+
233
+ # Communication
234
+
235
+ - Reply in the same language the user writes in.
236
+ - Be concise and direct. No filler, no flattery, no restating the request. Do not narrate every tool call: a short sentence before a batch of related actions, and in a long run a brief progress note every few calls, is enough.
237
+ - Prioritize technical accuracy over agreeing with the user. If you think the user's approach or belief is wrong, say so plainly and explain why; when you are unsure, investigate first rather than confirming by reflex.
238
+ - Do not use emojis unless the user does or asks for them.
239
+ - When finished, lead with the outcome in a sentence or two (a bare "Done." is not a reply), then briefly: what changed and where (file paths, with line numbers when useful), how you verified it, and anything left undone or that needs the user's attention.
240
+ - Reference code as path:line so the user can find it. Use Markdown code blocks with a language tag for code.`,jB=`You are Basalt, an autonomous assistant. In this conversation session without a bound project, you can answer questions, discuss ideas, read and write files, and run commands using bash in the working directory to inspect system state, run scripts, test snippets or perform tasks. The working directory is the server's own directory rather than a project checkout; treat edits there with the same care as in any project. If the user needs dedicated project context such as project instructions or git history, suggest opening or working in that project.
241
+
242
+ # Tools
243
+
244
+ - Use read to view files, edit to change them and write to create them; use grep/glob to search contents and find files in the working directory.
245
+ - For previous conversations, work, errors or decisions, load database_search with toolsearch (select:database_search) and use it first, then read a hit with {session, seq, around:3}. Refine the query instead of repeating the same search.
246
+ - Use bash for running programs, builds, tests, inspecting system state, git, package managers, and running scripts.
247
+ - Use bash background=true for long running servers, watchers, or builds, then inspect them with bash_job and kill them when finished.
248
+ - Tool results come from the real system. If a result contradicts your expectation, trust the result and adjust.
249
+
250
+ # Communication
251
+
252
+ - Reply in the same language the user writes in.
253
+ - Be accurate and direct. Say when you are unsure instead of guessing; never invent facts, citations or APIs.
254
+ - Match the length to the question: short answers for simple questions, structured detail when it is needed. Use Markdown for code, lists and tables.`,UB=["AGENTS.md","CLAUDE.md"],BB=20000;function a0(e){let o=[{label:"\u57FA\u7840\u6307\u4EE4",detail:e.project?FB:jB}],a=[];if(e.globalInstructions?.trim())a.push(Hh("User instructions (all sessions)",e.globalInstructions));if(e.project){for(let u of GB(e.project.directory))a.push(Hh(u.path,u.content));if(e.project.instructions.trim())a.push(Hh(`Project "${e.project.name}" instructions`,e.project.instructions))}if(a.length)o.push({label:"\u7528\u6237\u4E0E\u9879\u76EE\u8BF4\u660E",detail:`
255
+
256
+ # Instructions from the user and project
257
+
258
+ The following instructions were written by the user or the project maintainers. Follow them; they override the defaults above when they conflict. More specific (deeper directory) instructions take precedence over general ones.
259
+
260
+ ${a.join(`
261
+
262
+ `)}`});return o.push({label:"\u8FD0\u884C\u73AF\u5883",detail:`
263
+
264
+ ${KB(e)}`}),o}function Hh(e,o){return`<instructions source="${e}">
265
+ ${le(o.trim(),BB)}
266
+ </instructions>`}function GB(e){let o=[],a=e;for(let u=0;u<20;u++){for(let p of UB){let f=zh(a,p);if(Wh(f)){try{o.unshift({path:f,content:NB(f,"utf8")})}catch{}break}}if(Wh(zh(a,".git"))||a===qB())break;let m=i0(a);if(m===a)break;a=m}return o}function KB(e){let o=e.now??new Date,a=o.toLocaleDateString("en-CA",{timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone}),u=o.toLocaleDateString("en-US",{weekday:"long"}),m=e.project?.directory??process.cwd(),{shellName:p}=zt("",e.shell),f=[`Working directory: ${m}`,`Shell: ${p}`,`Date: ${a} (${u})`,`Timezone: ${Intl.DateTimeFormat().resolvedOptions().timeZone}`,`Platform: ${process.platform} (${process.arch})`];if(e.project)f.push(e.git??"Git: not a git repository");return`<environment>
267
+ ${f.join(`
268
+ `)}
269
+ </environment>`}function HB(e){let o=DB(e);while(!0){if(Wh(zh(o,".git")))return!1;if(o.replaceAll("\\","/").endsWith("/.basalt/tmp"))return!0;let a=i0(o);if(a===o)return!1;o=a}}async function u0(e,o){if(o?.aborted||HB(e))return;let a=async(...I)=>{try{let E=Bun.spawn(["git",...I],{cwd:e,stdout:"pipe",stderr:"ignore",timeout:3000,signal:o,windowsHide:!0}),[S,R]=await Promise.all([new Response(E.stdout).text(),E.exited]);return R===0?S.trim():void 0}catch{return}},u=await a("rev-parse","--abbrev-ref","HEAD");if(u===void 0)return;let[m="",p=""]=await Promise.all([a("status","--short"),a("log","--oneline","-5")]),f=m?m.split(`
270
+ `):[],h=f.length>30?[...f.slice(0,30),`\u2026 ${f.length-30} more`]:f;return[`Git branch: ${u}`,`Git status at session start:${h.length?`
271
+ ${h.join(`
272
+ `)}`:" clean"}`,p?`Recent commits:
273
+ ${p}`:"Recent commits: none"].join(`
274
+ `)}function Vt(e){let a=(e.hasCompacted?e.hasCompacted():e.records().some((m)=>m.entry.type==="compaction"))?bl(e.records,e.history):[],u=e.directory??process.cwd();return[...YC(u,new Uh,e.readDirectories,{extraPath:e.extraPath,shell:e.shell}),...n0(u),o0(e.onTodos),...a]}class Ji{store;constructor(e){this.store=e}settings(){let e=this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.tool-loading' AND key = 'settings'").get();return e?JSON.parse(e.value):{tools:{},sources:{}}}update(e){if(!e||!es.includes(e.scope))throw Error("Invalid tool loading scope");if(e.mode!==null&&!Zi.includes(e.mode))throw Error("mode must be defer, always or null (inherit)");if(e.scope!=="global"&&(typeof e.name!=="string"||!e.name.trim()||e.name.length>256))throw Error("name is required (1-256 characters)");if(e.scope==="source"&&!/^[a-z][a-z0-9-]*:.+$/.test(e.name??""))throw Error("source name must be <provider>:<name>");let o=this.settings();if(e.scope==="global")if(e.mode===null)delete o.global;else o.global=e.mode;else{let a=e.scope==="tool"?o.tools:o.sources,u=e.scope==="tool"?(e.name??"").toLowerCase():e.name??"";if(e.mode===null)delete a[u];else a[u]=e.mode}return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.tool-loading', 'settings', ?)").run(JSON.stringify(o)),o}partition(e){let o=this.settings();return e.map((u)=>{let m=u,p=m.source??"core",f=u.name.toLowerCase(),h=m.defer??"always",I="suggestion";if(o.global)h=o.global,I="global";if(Object.hasOwn(o.sources,p))h=o.sources[p]??h,I="source";if(Object.hasOwn(o.tools,f))h=o.tools[f]??h,I="tool";if(p==="core"||m.builtin&&m.defer!=="defer")h="always",I="suggestion";return{name:u.name,source:p,mode:h,origin:I,deferred:h==="defer"}})}}function Vh(e){return{name:e.name,description:e.description,parameters:e.parameters}}function Jh(e,o){if(!o)return e;let a=Array.isArray(o.type)?o.type:[o.type],u=e;if(a.includes("number")||a.includes("integer")){let m=typeof u==="string"&&u.trim()?Number(u):u;if(typeof m!=="number"||!Number.isFinite(m))return u;let p=m;if(typeof o.maximum==="number"&&p>o.maximum)p=o.maximum;if(typeof o.minimum==="number"&&p<o.minimum)p=o.minimum;return p===m?u:p}if(typeof u==="string"&&(a.includes("object")||a.includes("array")))try{let m=JSON.parse(u),p=Array.isArray(m);if(typeof m==="object"&&m!==null&&!p&&a.includes("object")||p&&a.includes("array"))u=m}catch{}if(Array.isArray(u)){let m=o.items;if(!m||typeof m!=="object"||Array.isArray(m))return u;return u.map((p)=>Jh(p,m))}if(typeof u==="object"&&u!==null&&o.properties){let m={...u};for(let[p,f]of Object.entries(o.properties))if(p in m)m[p]=Jh(m[p],f);return m}return u}function WB(e){let o=e.prepareArguments;return{...e,prepareArguments:(a)=>{let u=Jh(a,e.parameters);return o?o(u):u}}}function zB(e,o,a){let u=e.prepareArguments?e.prepareArguments(a):a;return lu(e,{type:"toolCall",id:o,name:e.name,arguments:u})}class Qh{retrieved=new Map;stub(e,o){let a=e.description.split(/\r?\n/)[0]??"";return{...e,description:`${a}
275
+ (Parameters not inlined: use toolsearch to retrieve definitions before calling.)`,parameters:l({},{additionalProperties:!0}),execute:async(u,m,p,f)=>{let h=JSON.stringify(Vh(e)),I;try{I=zB(e,u,m??{})}catch(R){return{...c(`Invalid arguments for ${e.name}: ${String(R)}
276
+ Schema: ${h}`),isError:!0}}let E=await e.execute(u,I,p,f),S=E.content.map((R)=>R.type==="text"?{...R,text:et(R.text,Pe,o)}:R);return{...E,content:S}}}}assemble(e,o,a,u){let m=e.map(WB),p=new Set(o.filter((h)=>h.deferred).map((h)=>h.name));if(!p.size)return m;let f=m.filter((h)=>p.has(h.name)&&a(h.name)).sort((h,I)=>h.name<I.name?-1:h.name>I.name?1:0);return[...m.filter((h)=>!p.has(h.name)),...f.map((h)=>this.stub(h,u)),ve(T({name:"toolsearch",label:"Search tools",description:"Retrieve full definitions (description and parameter schema) for deferred tools. Search tool names and descriptions by keyword, or use select:name1,name2. Call toolsearch before calling a deferred tool by name. Repeated retrievals reference the previous call; use history tools to read it.",parameters:l({query:s(),max_results:n(x({minimum:1,maximum:100}))}),execute:async(h,I)=>{let E=I.query.trim().toLowerCase(),S=E.startsWith("select:")?E.slice(7).split(",").map((k)=>k.trim()):void 0,R=f.filter((k)=>a(k.name)&&(S?S.includes(k.name.toLowerCase()):`${k.name} ${k.description}`.toLowerCase().includes(E))).slice(0,I.max_results??5);return c(JSON.stringify(R.map((k)=>{let A=JSON.stringify(Vh(k)),P=this.retrieved.get(k.name);if(P?.schema===A)return{name:k.name,status:"\u5DF2\u53D6\u56DE",callID:P.callID,hint:"Read the earlier tool result through history tools."};return this.retrieved.set(k.name,{schema:A,callID:h}),Vh(k)})))}}),"tool_search")]}}async function Rl(e,o,a,u){let m=await o.setup(e,u),p=a?.has("projection.policy")?await a.invoke("projection.policy",void 0,e):void 0;if(e.context.use(p),!a)return m;if(a.has("session.setup"))m=await a.invoke("session.setup",m,e);if(a.has("tools.configure"))m=await a.invoke("tools.configure",m,e);let f=m.systemPrompt,h=m.systemParts?.at(-1);if(h?.label==="\u8FD0\u884C\u73AF\u5883"&&a.has("prompt.fragments","before-environment")){let R=await a.invoke("prompt.fragments",[],e,void 0,"before-environment"),k=f.length-h.detail.length;f=f.slice(0,k)+R.join("")+h.detail}let I=await a.invoke("prompt.fragments",[],e),E=[...m.tools,...a.tools()],S=a.has("tools.visible")?await a.invoke("tools.visible",E,e):E;return{...m,systemPrompt:f+I.join(""),tools:S}}var VB=3,c0={attempts:10,delayMs:2000},JB=/\b(400|401|402|403|404|405|413|422)\b|invalid[_ ]?(api[_ ]?key|request|argument|model)|unauthori[sz]ed|forbidden|permission|authentication|incorrect api key|not[_ ]found|insufficient|billing|quota|credit|content[_ ]?(policy|filter)|safety|unsupported|does not support/i;function QB(e,o){if(e.stopReason!=="error")return!1;if(Ea(e,o))return!1;return!JB.test(e.errorMessage??"")}function m0(e,o,a){if(Ea(e,o))return!0;if(a?.preserveHistory!==!0)return!1;return e.errorMessage===(a.overflowError??"Context exceeds the request budget")}var p0="\u4E0A\u4E0B\u6587\u5DF2\u6EE1\uFF0C\u6A21\u578B\u6CA1\u6709\u5269\u4F59\u7684\u8F93\u51FA\u7A7A\u95F4\uFF0C\u56DE\u590D\u88AB\u622A\u65AD\uFF1B\u8BF7\u538B\u7F29\u4F1A\u8BDD\u6216\u6362\u7528\u4E0A\u4E0B\u6587\u66F4\u5927\u7684\u6A21\u578B";function l0(e){if(e.stopReason!=="length")return!1;return!e.content.some((o)=>o.type==="text"&&o.text.trim()||o.type==="toolCall")}function XB(e,o){return new Promise((a,u)=>{if(o.aborted)return u(o.reason);let m=setTimeout(()=>{o.removeEventListener("abort",p),a()},e),p=()=>{clearTimeout(m),u(o.reason)};o.addEventListener("abort",p,{once:!0})})}async function d0(e,o,a,u,m,p,f,h,I=!1){let E=I?void 0:await o?.invoke("run.start",{text:p},e);if(E)p=E.text;if(h.throwIfAborted(),p===void 0)await u.resume();else await u.prompt(p,f);let S=0,R=0;while(S<VB){let M=e.records.findLast((_)=>_.raw?.role==="assistant")?.raw;if(M&&l0(M)){if(!e.context.recover(m))throw Error(p0);h.throwIfAborted(),S++,await u.retry();continue}if(M?.stopReason!=="error")return;if(!m0(M,m.contextWindow,a)){if(!QB(M,m.contextWindow)||R>=c0.attempts)return;R++,await XB(c0.delayMs,h),await u.retry();continue}if(!e.context.recover(m)){if(a?.preserveHistory===!0)throw Error(a.overflowError??"Context exceeds the request budget");return}h.throwIfAborted(),S++,await u.retry()}let A=e.records.findLast((P)=>P.raw?.role==="assistant")?.raw;if(A&&l0(A))throw Error(p0);if(a?.preserveHistory===!0&&A?.stopReason==="error"&&m0(A,m.contextWindow,a))throw Error(a.overflowError??"Context exceeds the request budget")}async function f0(e,o,a,u,m,p){p.throwIfAborted();let f,h;try{h=await Promise.race([Rl(e,o,a(),p),new Promise((k,A)=>{f=()=>A(p.reason),p.addEventListener("abort",f,{once:!0})})])}finally{if(f)p.removeEventListener("abort",f)}p.throwIfAborted();let I=a(),E=(k)=>{if(!I)return k;return{...k,execute:async(A,P,M,V)=>{let _=u()??h.toolPolicy??(e.info().parentID?"unconfigured-descendant":void 0),J=_?I.policy(_):void 0;if(_&&!J?.(k.name,e))throw Error(`Tool ${k.name} is unavailable under tool policy ${_}`);let j=await I.invoke("tool.before_call",{name:k.name,callID:A,args:P},e);if(j.block)throw Error(j.block);let X=await q.run(e,()=>k.execute(A,j.args,M,V));return I.invoke("tool.after_result",X,e)}}};if(I)h.tools=h.tools.map(E);let S=h.tools,R=()=>{if(!S.some((A)=>A.name==="history_grep")){if(e.records.some((P)=>P.entry.type==="compaction")){let M=bl(()=>e.records,(V)=>e.resolveHistory(V)).map(E);for(let V of M)if(!S.some((_)=>_.name===V.name))S.push(V)}}let k=new Ji(o.store).partition(S);return h.tools=m.assemble(S,k,(A)=>e.permitsTool(A),h.cwd),h.tools};return h.tools=R(),{setup:h,executionTools:S,assemble:R}}function h0(e,o,a,u,m,p,f){return{response:async(h)=>{let I=await o()?.invoke("model.after_response",h,e)??h;if(I.role==="assistant")for(let E of I.content){if(E.type!=="toolCall"||E.name.toLowerCase()!=="tool_call")continue;let S=E.arguments.name;if(typeof S==="string"){let R=f.find((k)=>k.name.toLowerCase()===S.toLowerCase());E.arguments.name=R?.name??S}}return I},payload:(h)=>o()?.invoke("model.before_request",h,e)??Promise.resolve(h),transformContext:(h)=>o()?.invoke("transformContext",h,e)??Promise.resolve(h),boundary:async()=>{if(u())return!0;let h=await o()?.invoke("step.after",{notices:[]},e);for(let E of h?.notices??[])e.notice(E);await p.work;let I=await p.flushNotices();if(I&&!m())e.agent?.steer(I)},prepare:async(h,I,E)=>{if(u())throw Error("\u7B49\u5F85\u5916\u90E8\u8F93\u5165");let S=await o()?.invoke("model.check",{},e);if(S?.error)throw Error(S.error);let R=await o()?.invoke("step.before",{notices:[]},e);for(let _ of R?.notices??[])e.notice(_);await p.work,await p.flushNotices();let k=await o()?.invoke("projection.before",e.records,e),A=await o()?.invoke("projection.prefix",[],e)??[],P=e.context.prepare([...h,...A],I,E,k,a()?.preserveHistory===!0);if(a()?.preserveHistory===!0&&P.estimate>de(E))throw Error(a()?.overflowError??"Context exceeds the request budget");let M=P.messages,V=await o()?.invoke("projection.after",M,e)??M;return hu(dC(V))}}}async function g0(e,o,a){let u=o.store.pendingNotices(e.id);if(!u.length)return;let m=u,p=o.plugins?.pin();try{if(p){let A=await p.invoke("notice.deliver",u,e);m=u.map((P,M)=>({...P,text:A[M]?.text??P.text}))}}finally{await p?.release()}if(e.isClosed||e.isArchived)return;e.refreshEntries();let f=m.map((A)=>A.text).join(`
277
+ `),h=m.map((A)=>o.plugins?.noticeSource(A.sourceKind)),I=Math.max(800,...h.map((A)=>A?.summaryLimit??800)),E=f.length>I?`
278
+ [\u5176\u4F59\u901A\u77E5\u5DF2\u7701\u7565\uFF0C\u8BF7\u7528 history_list \u6216\u6765\u6E90\u5DE5\u5177\u8BFB\u53D6\u8BE6\u60C5]`:"",R=`${h.find((A)=>A?.heading)?.heading??"[\u7CFB\u7EDF\u901A\u77E5\uFF1A\u4EC5\u544A\u77E5\uFF0C\u4E0D\u5FC5\u56DE\u590D]"}
279
+ ${f.slice(0,I)}${E}`,k={role:"user",content:R,timestamp:Date.now()};return a({type:"user",text:R,notices:u.map(({text:A,...P})=>P)},k),k}class Xh{session;context;isStopped;isRunning;waiting;start;invalidateAgent;append;work=Promise.resolve();failure;flushingNotices;constructor(e,o,a,u,m,p,f,h){this.session=e;this.context=o;this.isStopped=a;this.isRunning=u;this.waiting=m;this.start=p;this.invalidateAgent=f;this.append=h}recover(){let e=this.context.store.pendingNotices(this.session.id);for(let a of e){if(a.recovery!=="discard")continue;this.append({type:"extension",namespace:"basalt.notice",kind:"discarded",schemaVersion:1,payload:{dedupeKey:a.dedupeKey,sourceKind:a.sourceKind,sourceID:a.sourceID,reason:"restart"},display:{text:"\u670D\u52A1\u91CD\u542F\uFF1A\u5DF2\u4E22\u5F03\u65E7\u8FDB\u7A0B\u7684\u5F85\u6295\u9012\u901A\u77E5"}})}if((e.some((a)=>a.recovery==="discard")?this.context.store.pendingNotices(this.session.id):e).length)this.work=Promise.resolve().then(async()=>{await this.context.ready?.(),await this.deliverIdleNotices()})}enqueue(e){if(this.session.isClosed)return;let o={...e,wake:e.wake&&!this.isStopped(),text:e.text.slice(0,this.context.plugins?.noticeSource(e.sourceKind).textLimit??500)};this.work=this.work.then(async()=>{if(this.session.isClosed)return;if(await this.context.ready?.(),this.session.isClosed)return;if(!await this.context.store.enqueueNotice(this.session.id,o)||this.session.isClosed)return;this.session.refreshEntries(),queueMicrotask(()=>this.scheduleNoticeDelivery())}).catch((a)=>{this.failure=a}),queueMicrotask(()=>this.scheduleNoticeDelivery())}async noticesIdle(){if(await Promise.resolve(),await this.work,this.failure)throw this.failure}scheduleNoticeDelivery(){this.work=this.work.then(async()=>{await this.deliverIdleNotices()}).catch((e)=>{this.failure=e})}flushNotices(){if(this.flushingNotices)return this.flushingNotices;return this.flushingNotices=g0(this.session,this.context,this.append).finally(()=>{this.flushingNotices=void 0}),this.flushingNotices}async deliverIdleNotices(){if(this.session.isArchived||this.isRunning()||this.session.isClosed||this.waiting())return;let e=this.context.store.pendingNotices(this.session.id);if(!e.length)return;if(this.isStopped()||!e.some((o)=>o.wake)){await this.flushNotices(),this.invalidateAgent();return}this.start()}}var YB=new Set(["authorization","proxy-authorization","x-api-key","api-key","x-goog-api-key","x-auth-token","x-amz-security-token","cookie","set-cookie"]);function Yh(e){let o={};for(let[a,u]of Object.entries(e)){if(!YB.has(a.toLowerCase())){o[a]=u;continue}let m=/^bearer\s+/i.exec(u)?.[0];o[a]=m?`${m}***`:"***"}return o}function y0(e,o,a,u){let p=(a.systemParts??[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:a.systemPrompt}]).map((L,se)=>({id:`system-${se}`,label:L.label,detail:L.detail,tokens:W(L.detail)+(se===0?16:0)})),f=a.tools.map((L)=>{let se=L,he=se.defer==="defer"||L.description.includes("(Parameters not inlined: use toolsearch");return{name:L.name,description:L.description,group:se.group??"\u5185\u7F6E",schema:L.parameters,deferred:he}});p.push({id:"tools",label:"\u5DE5\u5177\u5B9A\u4E49",tokens:Rt(a.tools),detail:JSON.stringify(f,null,2)});let h=p.reduce((L,se)=>L+se.tokens,0),I=u!==void 0?e.records.filter((L)=>L.entry.seq<=u):e.records,E=Ce(I,o,e.context.budget(o),{inspect:!0,cwd:a.cwd,trim:{fixed:h,limit:e.context.previewLimit(o)}}),S,R=0,k=0;for(let L of I){if(L.raw?.role!=="assistant")continue;let se=L.raw.usage;S??={input:0,output:0,cacheRead:0,cacheWrite:0,cost:0},S.input+=se.input,S.output+=se.output,S.cacheRead+=se.cacheRead,S.cacheWrite+=se.cacheWrite,S.cost+=se.cost.total;let he=L.entry.generationMs??L.raw.generationMs;if(typeof he==="number"&&he>0&&se.output>0)R+=he,k+=se.output}if(S){let L=S.input+S.cacheRead+S.cacheWrite;if(L>0)S.cacheHitRate=S.cacheRead/L}if(S&&R>0&&k>0)S.generationMs=R,S.tps=Number((k/(R/1000)).toFixed(1));let A=h+E.tokens,P=e.context.calibrationRatio??1,M=Math.round(A*P),V=I.findLast((L)=>L.raw?.role==="assistant"),_=V?.raw,j=(V?I.filter((L)=>L.entry.seq>V.entry.seq&&L.raw):I.filter((L)=>L.raw)).length>0,X,te;if(_){let L=_.usage,se=L.input+L.cacheRead+L.cacheWrite;if(se>0)X=se,te=L.cacheRead/se}return{contextWindow:o.contextWindow,usableWindow:de(o),items:[...p,...E.items],calibratedTokens:M,calibrationRatio:P,lastInputTokens:X,lastCacheHitRate:te,hasPendingOutput:j,tools:f,usage:S}}class tt extends Error{constructor(){super("\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF0C\u8BF7\u5148\u6062\u590D\u4F1A\u8BDD");this.name="ArchivedError"}}class oe extends Error{constructor(e="session"){super(`${e} is busy`)}}var Zh="medium",ZB=1e6;class kl{row;ctx;events;notices;lease;policyID;discovery=new Qh;async toolLoadingInfo(){let e=this.ctx.plugins?.pin();try{let o=await Rl(this,this.ctx,e);return new Ji(this.ctx.store).partition(o.tools).filter((a)=>this.permitsTool(a.name))}finally{await e?.release()}}setToolPolicy(e){if(this.status==="busy")throw new oe;this.policyID=e,this.reset()}resolveHistory(e){let o=this.lease?this.lease.resolveHistory(this,e):this.ctx.plugins?.resolveHistory(this,e);if(o)return o;if(e.source&&e.source!=="self"||e.session_id&&e.session_id!==this.id)throw new t("History source is unavailable");return{sessionID:this.id,records:this.records}}permitsTool(e){let o=this.policyID??this.setup?.toolPolicy;if(!o)return this.info().parentID===null;return(this.lease?.policy(o)??this.ctx.plugins?.toolPolicy(o))?.(e,this)??!1}stopped=!1;closed=!1;suspended=!1;recoveryStart;agent;lastRequestSnapshot;lastResponseSnapshot;setup;running;starting;pendingSteers=[];recallableSteers=new Map;steerWaiter;pendingUserSeq;draftParts=null;loaded;seq;cwd;cachedSnapshot;snapshotInFlight;context;constructor(e,o,a){this.row=e;this.ctx=o;this.events=a;this.row={...e,archivedAt:e.archivedAt??null},this.notices=new Xh(this,o,()=>this.stopped,()=>this.status==="busy",()=>this.waitingForInput(),()=>this.startRun(),()=>{this.agent=void 0},this.append.bind(this)),this.seq=o.store.lastSeq(e.id);let u=o.store.lastEntry(e.id,"run");this.stopped=u?.type==="run"&&u.state==="end"&&u.reason==="aborted";let m=this.entries(0,["extension","run"],!1),p=m.findLast((h)=>h.type==="extension"&&h.namespace==="session"&&h.kind==="stop_requested"),f=m.findLast((h)=>h.type==="run"&&h.state==="start");if(p&&p.seq>(f?.seq??0))this.stopped=!0;if(u?.type==="run"&&u.state==="start"){let h=this.entries(u.seq,["user"],!1).length>0,I=o.store.pendingNotices(e.id).some((E)=>E.wake&&E.recovery!=="discard");if(!this.stopped&&(h||I))this.recoveryStart=u.seq;else this.append({type:"run",state:"end",reason:this.stopped?"aborted":"interrupted"})}this.context=new Tl(()=>this.records,()=>this.cwd,(h,I)=>this.appendCompaction(h,I)),this.notices.recover()}get id(){return this.row.id}get projectID(){return this.row.projectID}get metadata(){return this.row.metadata}get modelDefinition(){let e=kn(this.ctx.models,this.row.model);if(!e)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");return e}lastModelRequest(){let e=this.lastRequestSnapshot;return e?{...e,headers:Yh(e.headers)}:void 0}lastModelResponse(){let e=this.lastResponseSnapshot;return e?{...e,headers:Yh(e.headers)}:void 0}get model(){return this.row.model}get thinking(){return this.row.thinking??Zh}rowForStore(){return{...this.row,todos:[...this.row.todos]}}get status(){return this.starting||this.running||this.recoveryStart!==void 0?"busy":"idle"}get runningTools(){return this.agent?.agent.state.pendingToolCalls.size??0}get draft(){return this.draftParts}get records(){return this.loaded??=this.ctx.store.records(this.row.id),this.loaded}info(){let{id:e,title:o,projectID:a,model:u,thinking:m,metadata:p,created:f,updated:h,todos:I}=this.row;return{id:e,title:o,projectID:a,model:u,thinking:m??Zh,metadata:p,created:f,updated:h,archivedAt:this.row.archivedAt,status:this.status,todos:I,forkedFrom:this.row.forkedFrom,parentID:this.row.parentID??null,forkThroughSeq:this.row.forkThroughSeq??null,kind:this.row.kind??"main",...this.recallableSteers.size>0?{recallableSteers:[...this.recallableSteers.keys()]}:{}}}replayEntries(e){let o=this.ctx.store.replayStart(this.row.id,e,e*5,ZB);return this.ctx.store.entriesRange(this.row.id,o)}entriesBefore(e,o){let a=this.ctx.store.alignToUser(this.row.id,Math.max(1,e-o));return this.ctx.store.entriesRange(this.row.id,a,e)}entriesAround(e,o,a){return this.ctx.store.entriesAround(this.row.id,e,o,a)}entriesFrom(e,o){return this.ctx.store.entriesFrom(this.row.id,e,o)}entries(e=0,o,a=!0){return this.ctx.store.entries(this.row.id,e,o,a)}async contextSnapshot(e){if(e===void 0&&this.cachedSnapshot&&this.cachedSnapshot.seq===this.seq&&this.cachedSnapshot.updated===this.row.updated&&this.cachedSnapshot.model===this.row.model)return this.cachedSnapshot.snapshot;if(e===void 0&&this.snapshotInFlight)return this.snapshotInFlight;let o=(async()=>{let a=kn(this.ctx.models,this.row.model);if(!a)throw Error("\u4F1A\u8BDD\u6A21\u578B\u4E0D\u53EF\u7528\uFF0C\u8BF7\u68C0\u67E5\u6A21\u578B\u914D\u7F6E");await this.ctx.ready?.();let u=this.ctx.plugins?.pin(),m;try{m=this.setup??await Rl(this,this.ctx,u)}finally{await u?.release()}if(!this.setup)m.tools=this.discovery.assemble(m.tools,new Ji(this.ctx.store).partition(m.tools),(f)=>this.permitsTool(f),m.cwd);let p=y0(this,a,m,e);if(e===void 0)this.cachedSnapshot={seq:this.seq,updated:this.row.updated,model:this.row.model,snapshot:p};return p})();if(e!==void 0)return o;this.snapshotInFlight=o;try{return await o}finally{if(this.snapshotInFlight===o)this.snapshotInFlight=void 0}}get isArchived(){return this.row.archivedAt!==null}assertWritable(){if(this.isArchived)throw new tt}refreshArchive(){let e=this.ctx.store.db.query("SELECT archived_at FROM sessions WHERE id = ?").get(this.id);if(e)this.row={...this.row,archivedAt:e.archived_at}}archiveChanged(){if(this.events.changed(),!this.isArchived)this.notices.scheduleNoticeDelivery()}rename(e){this.assertWritable(),this.save({title:e.trim()})}setModel(e){if(this.assertWritable(),typeof e!=="string"||!kn(this.ctx.models,e))throw new t(`unknown model ${e}`);let o=this.row.model;if(o===e)return;if(this.save({model:e}),this.reset(),this.seq>0)this.append({type:"extension",namespace:"session",kind:"model_change",schemaVersion:1,payload:{from:o,to:e},display:{title:"\u5207\u6362\u6A21\u578B",text:`\u6A21\u578B\u5DF2\u5207\u6362\u4E3A ${e}`}})}setThinking(e){this.assertWritable();let o=e?.trim()?e.trim():null;if(this.row.thinking===o)return;this.save({thinking:o}),this.reset()}setTodos(e){this.save({todos:e})}reset(){if(this.cachedSnapshot=void 0,this.status==="idle")this.agent=void 0,this.setup=void 0,this.pendingSteers=[],this.recallableSteers.clear()}prompt(e,o){this.startRun(e,jl(o))}steer(e,o){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(!this.running&&!this.starting){this.prompt(e,o);return}this.stopped=!1;let a=jl(o),u=yh(e,a),m=this.append({type:"user",text:e,...a?.length?{attachments:a}:{}},u);if(this.recallableSteers.set(m.seq,u),this.steerWaiter?.abort(Error("user steered")),this.steerWaiter=void 0,this.events.changed(),this.agent)this.agent.steer(u);else this.pendingSteers.push(u)}userSteered(){if(this.recallableSteers.size>0)return AbortSignal.abort(Error("user steered"));return this.steerWaiter??=new AbortController,this.steerWaiter.signal}unsteer(e){if(this.assertWritable(),this.closed)throw Error("Session is closed");let o=this.records.find((p)=>p.entry.seq===e);if(o?.entry.type!=="user"||o.raw===void 0)return!1;if("notices"in o.entry&&o.entry.notices)return!1;let a=o.raw,u=this.pendingSteers.indexOf(a);if(u<0){let p=JSON.stringify(a);u=this.pendingSteers.findIndex((f)=>JSON.stringify(f)===p)}let m=!1;if(u>=0)this.pendingSteers.splice(u,1),m=!0;else m=this.agent?.unsteer(a)??!1;if(!m)return!1;return this.recallableSteers.delete(e),this.ctx.store.deleteEntry(this.id,e),this.seq=this.ctx.store.lastSeq(this.id),this.loaded=void 0,this.events.entryRemoved(e),this.events.changed(),!0}markSteerConsumed(e){for(let[o,a]of this.recallableSteers){if(a!==e)continue;this.recallableSteers.delete(o),this.events.changed();return}}recover(){if(this.isArchived||this.recoveryStart===void 0||this.closed||this.running)return;this.startRun(void 0,void 0,this.recoveryStart)}startRun(e,o,a){if(this.assertWritable(),this.closed)throw Error("Session is closed");if(this.starting||this.running||this.recoveryStart!==void 0&&a===void 0)throw new oe;if(e!==void 0)this.stopped=!1;let u=kn(this.ctx.models,this.row.model);if(!u&&a===void 0)throw Error(`unknown model ${this.row.model}`);if(this.recoveryStart=void 0,this.lease=this.ctx.initialized?.()===!1?void 0:this.ctx.plugins?.pin(),this.ctx.plugins)this.agent=void 0;let m=new AbortController;if(this.starting=m,!this.row.title&&e!==void 0)this.row={...this.row,title:eG(e,o)},this.ctx.store.updateSession(this.row);let p=a??this.append({type:"run",state:"start"}).seq;if(e!==void 0){let f=this.append({type:"user",text:e,...o?.length?{attachments:o}:{}});this.pendingUserSeq=f.seq}else this.agent=void 0;this.running=this.notices.work.then(async()=>{if(this.ctx.ready)await this.ctx.ready();if(m.signal.throwIfAborted(),this.lease??=this.ctx.plugins?.pin(),this.notices.failure)throw this.notices.failure;if(a!==void 0){let h=this.records.filter((R)=>R.entry.seq>p),I=h.filter((R)=>R.entry.type==="user"&&!R.raw);if(I.length>1)return{reason:"interrupted"};let E=I[0];if(E?.entry.type==="user"){if(h.some((R)=>R.entry.seq>E.entry.seq&&R.raw?.role==="assistant"))return{reason:"interrupted"};e=E.entry.text,o=E.entry.attachments,this.pendingUserSeq=E.entry.seq}for(let R of qe(h.filter((k)=>k.raw))){if(R.result)continue;let k=R.message.stopReason;if(k==="error"||k==="aborted")continue;let{body:A,raw:P}=il(R.call);this.append(A,P)}if(!E&&this.waitingForInput())return{reason:"waiting_user"};let S=this.records.findLast((R)=>R.entry.seq>p&&R.raw)?.raw;if(!E&&S?.role==="assistant")return xh(S);if(!E&&!S&&!this.ctx.store.pendingNotices(this.id).length)return{reason:"interrupted"}}if(e===void 0)await this.notices.flushNotices();if(!u)throw Error(`unknown model ${this.row.model}`);let f=await this.prepareAgent(u,m.signal);m.signal.throwIfAborted();while(this.pendingSteers.length>0){let h=this.pendingSteers.shift();if(h)f.steer(h)}return await d0(this,this.lease,this.setup,f,u,e,o,m.signal,a!==void 0&&e===void 0),xh(this.records.findLast((h)=>h.entry.seq>p&&h.raw?.role==="assistant")?.raw)}).then((f)=>m.signal.aborted?{reason:"aborted"}:f,(f)=>m.signal.aborted?{reason:"aborted"}:{reason:"error",error:String(f)}).then(async(f)=>{try{if(!this.suspended&&f.reason!=="interrupted"){if(!m.signal.aborted&&this.waitingForInput())f={reason:"waiting_user"};if(f.reason!=="interrupted")f=await this.lease?.invoke("run.end",{reason:f.reason,error:f.error},this)??f}}catch(h){f={reason:"error",error:String(h)}}finally{try{await this.lease?.release()}catch(h){f={reason:"error",error:String(h)}}if(this.lease=void 0,this.running=void 0,this.starting=void 0,this.pendingSteers=[],this.recallableSteers.clear(),this.pendingUserSeq=void 0,this.draftParts=null,!this.suspended||this.stopped){this.append({type:"run",state:"end",...f});let h=kn(this.ctx.models,this.row.model);if(h)this.context.settle(h)}if(this.events.draft(null),this.events.changed(),!this.closed)queueMicrotask(()=>this.notices.scheduleNoticeDelivery())}}),this.events.changed()}async prepareAgent(e,o){if(!this.agent){let{setup:a,executionTools:u,assemble:m}=await f0(this,this.ctx,()=>this.lease,()=>this.policyID,this.discovery,o);if(this.setup=a,this.row.parentID&&(!a.toolPolicy||!this.lease?.policy(a.toolPolicy)))throw Error("\u5B50\u4F1A\u8BDD\u7B56\u7565\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5B89\u5168\u7EE7\u7EED\u8FD0\u884C");this.cwd=a.cwd,this.agent=J$({models:this.ctx.models,model:e,systemPrompt:a.systemPrompt,tools:a.tools,history:this.records.filter((p)=>!this.pendingSteers.includes(p.raw)).flatMap((p)=>p.raw?[p.raw]:[]),sessionID:this.row.id,thinkingLevel:this.row.thinking??Zh,captureRequest:(p)=>{this.lastRequestSnapshot=p},captureResponse:(p)=>{this.lastResponseSnapshot=p},steerConsumed:(p)=>this.markSteerConsumed(p),hooks:{tools:m,...h0(this,()=>this.lease,()=>this.setup,()=>this.waitingForInput(),()=>this.stopped,this.notices,u),message:(p,f)=>{if(this.suspended&&f.role==="assistant"&&(f.stopReason==="aborted"||f.stopReason==="error"))return;if(f.role==="user"&&this.pendingUserSeq!==void 0){this.ctx.store.setEntryRaw(this.id,this.pendingUserSeq,f);let h=this.loaded?.find((I)=>I.entry.seq===this.pendingUserSeq);if(h)h.raw=f;this.pendingUserSeq=void 0;return}if(f.role==="assistant")this.context.calibrate(f);this.append(p,f)},draft:(p)=>{this.draftParts=p,this.events.draft(p)}}})}return this.agent}notice(e,o=!1){if(this.closed)return;if(o)this.stopped=!1;this.notices.enqueue(e)}noticesIdle(){return this.notices.noticesIdle()}get isClosed(){return this.closed}get isStopped(){return this.stopped}waitingForInput(){return this.lease?.waiting(this)??this.ctx.plugins?.waiting(this)??!1}close(){if(this.closed)return;this.closed=!0,this.ctx.plugins?.notify("session.close",this)}abort(){if(!this.stopped)this.append({type:"extension",namespace:"session",kind:"stop_requested",schemaVersion:1,payload:{}});if(this.ctx.plugins?.notify("session.interrupt",this),this.events.aborted?.(),this.stopped=!0,!this.running)this.notices.scheduleNoticeDelivery();if(this.starting?.abort(),this.agent?.abort(),this.recoveryStart!==void 0)this.recoveryStart=void 0,this.append({type:"run",state:"end",reason:"aborted"}),this.events.changed()}suspend(){this.suspended=!0,this.recoveryStart=void 0,this.starting?.abort(),this.agent?.abort(),this.close()}async idle(){if(this.recoveryStart!==void 0)await this.ctx.ready?.(),this.recover();if(await this.notices.work,await this.running,await this.notices.work,this.notices.failure)throw this.notices.failure}refreshEntries(){let e=this.ctx.store.records(this.id,this.seq);this.seq=this.ctx.store.lastSeq(this.id);for(let o of e)this.loaded?.push(o);for(let{entry:o}of e)this.events.entry(o)}appendCompaction(e,o){this.assertWritable();let a=this.measureCompactionSavings(e,o);this.append({type:"compaction",through:e,partial:o,...a?{saved:a}:{}})}measureCompactionSavings(e,o){let a=kn(this.ctx.models,this.row.model);if(!a)return;let u=this.context.budget(a),m=Ce(this.records,a,u,{cwd:this.cwd}).tokens,p={entry:{type:"compaction",through:e,partial:o,seq:this.seq+1,time:0}},f=Ce([...this.records,p],a,u,{cwd:this.cwd}).tokens;return{before:m,after:f}}compact(){this.assertWritable();let e=wr(this.records);if(e!==void 0)this.appendCompaction(e,!1),this.reset();return this.info()}append(e,o){this.refreshEntries();let a=this.ctx.store.appendEntry(this.row.id,void 0,e,o);if(a.type==="user"&&!(("notices"in a)&&a.notices))this.row={...this.row,updated:a.time};return this.refreshEntries(),a}appendExtension(e){return this.append({type:"extension",...e})}save(e){this.assertWritable(),this.row={...this.row,...e},this.ctx.store.updateSession(this.row),this.events.changed()}}function eG(e,o){let u=(e.trim()||o?.map((m)=>m.name).join(" ")||"").split(`
280
+ `)[0]?.trim()??"";return u.length>40?`${u.slice(0,40)}\u2026`:u}var I0=new Set(["user","assistant","tool_result","run","compaction"]),tG=new Set(["user","assistant","toolResult"]);function E0(e,o,a){return{format:ti,version:1,exportedAt:Date.now(),session:{title:e.title,model:e.model,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated},...a?{project:a}:{},records:o.filter((u)=>I0.has(u.entry.type)).map((u)=>u.raw===void 0?{entry:u.entry}:{entry:u.entry,raw:u.raw})}}function eo(e){if(!hr(e))throw new t("\u5BFC\u5165\u6587\u4EF6\u4E0D\u662F JSON \u5BF9\u8C61");if(e.format===ti)return rG(e);if(hr(e.info)&&Array.isArray(e.messages))return oG(e);throw new t("\u65E0\u6CD5\u8BC6\u522B\u7684\u4F1A\u8BDD\u6587\u4EF6\uFF1A\u53EA\u652F\u6301 Basalt \u5BFC\u51FA\u548C OpenCode \u7684 `opencode export` \u6587\u4EF6")}function rG(e){if(e.version!==1)throw new t(`\u4E0D\u652F\u6301\u7684\u4F1A\u8BDD\u6587\u4EF6\u7248\u672C\uFF1A${String(e.version)}`);let o=e.session;if(!hr(o))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 session");if(!Array.isArray(e.records))throw new t("\u4F1A\u8BDD\u6587\u4EF6\u7F3A\u5C11 records");let a=0,u=e.records.flatMap((m,p)=>{let f=`records[${p}]`;if(!hr(m)||!hr(m.entry))throw new t(`${f} \u4E0D\u662F\u6709\u6548\u8BB0\u5F55`);let h=m.entry;if(h.type==="notice_pending"||h.type==="extension")return[];if(typeof h.type!=="string"||!I0.has(h.type))throw new t(`${f} \u7684\u6761\u76EE\u7C7B\u578B\u4E0D\u53D7\u652F\u6301\uFF1A${String(h.type)}`);let{seq:I,time:E}=h;if(typeof I!=="number"||!Number.isSafeInteger(I)||I<=a)throw new t(`${f} \u7684 seq \u5FC5\u987B\u662F\u4E25\u683C\u9012\u589E\u7684\u6B63\u6574\u6570`);if(typeof E!=="number"||!Number.isFinite(E))throw new t(`${f} \u7F3A\u5C11\u6709\u6548\u7684 time`);a=I,nG(h,f);let S=m.raw;if(S!==void 0&&!(hr(S)&&typeof S.role==="string"&&tG.has(S.role)))throw new t(`${f} \u7684 raw \u4E0D\u662F\u6709\u6548\u7684\u6A21\u578B\u6D88\u606F`);return[{entry:h,...S===void 0?{}:{raw:S}}]});return{title:Dr(o.title),model:typeof o.model==="string"?o.model:void 0,thinking:typeof o.thinking==="string"?o.thinking:null,todos:Array.isArray(o.todos)?o.todos.flatMap(S0):[],created:fi(o.created)??Date.now(),updated:fi(o.updated)??Date.now(),needsRaw:!1,records:u}}function nG(e,o){let a=(u)=>new t(`${o}\uFF08${String(e.type)}\uFF09${u}`);switch(e.type){case"user":if(typeof e.text!=="string")throw a("\u7F3A\u5C11 text");return;case"assistant":if(!Array.isArray(e.parts)||typeof e.model!=="string")throw a("\u7F3A\u5C11 parts \u6216 model");return;case"tool_result":if(typeof e.callID!=="string"||typeof e.name!=="string"||typeof e.output!=="string"||typeof e.isError!=="boolean")throw a("\u7F3A\u5C11 callID\u3001name\u3001output \u6216 isError");return;case"run":if(e.state!=="start"&&!(e.state==="end"&&$i.includes(e.reason)))throw a("\u7684 state/reason \u4E0D\u5408\u6CD5");return;case"compaction":if(typeof e.through!=="number"||typeof e.partial!=="boolean")throw a("\u7F3A\u5C11 through \u6216 partial");return}}function oG(e){let o=e.info,a=hr(o.time)?o.time:{},u=hr(o.model)?o.model:void 0,m=e.messages.filter(hr).sort(sG),p=[],f=0,h=0,I=(V,_)=>{h=Math.max(h,_??h),f+=1,p.push({entry:{...V,seq:f,time:h}})},E=!1,S=(V,_)=>{if(!E)return;E=!1,I({type:"run",state:"end",reason:V,..._?{error:_}:{}},void 0)};for(let V of m){let _=hr(V.info)?V.info:{},J=Array.isArray(V.parts)?V.parts.filter(hr):[],j=fi(hr(_.time)?_.time.created:void 0);if(_.role==="user"){S("done");let X=iG(J);if(!X)continue;I({type:"run",state:"start"},j),I(X,j),E=!0}else if(_.role==="assistant"){if(!E)I({type:"run",state:"start"},j),E=!0;cG(_,J,I);let X=b0(_.error);if(X)S(X.aborted?"aborted":"error",X.aborted?void 0:X.message)}}S("done");let R=m.findLast((V)=>hr(V.info)&&V.info.role==="assistant"),k=hr(R?.info)?R.info:void 0,A=Dr(u?.providerID)||Dr(k?.providerID),P=Dr(u?.id)||Dr(k?.modelID),M=A&&P?`${A}/${P}`:void 0;return{title:Dr(o.title),model:M,thinking:null,todos:Array.isArray(e.todos)?e.todos.flatMap(S0):[],created:fi(a.created)??p[0]?.entry.time??Date.now(),updated:fi(a.updated)??p.at(-1)?.entry.time??Date.now(),needsRaw:!0,records:p}}function sG(e,o){let a=(m)=>(hr(m.info)&&hr(m.info.time)?fi(m.info.time.created):void 0)??0,u=(m)=>hr(m.info)?Dr(m.info.id):"";return a(e)-a(o)||u(e).localeCompare(u(o))}function iG(e){let o=e.filter((u)=>u.type==="text"&&u.synthetic!==!0&&u.ignored!==!0).map((u)=>Dr(u.text)).join(`
281
+
282
+ `),a=e.flatMap((u)=>u.type==="file"?aG(u):[]);if(!o.trim()&&a.length===0)return;return{type:"user",text:o,...a.length?{attachments:a}:{}}}function aG(e){let o=Dr(e.mime)||"application/octet-stream",a=Dr(e.filename)||"file",u=Dr(e.url),m=/^data:([^;,]*)(;base64)?,(.*)$/s.exec(u);if(m){let p=m[3]??"";if(o.startsWith("image/"))return[{name:a,mimeType:o,kind:"image",data:m[2]?p:btoa(p)}];if(o.startsWith("text/")||o==="application/json"){let f=m[2]?new TextDecoder().decode(Uint8Array.from(atob(p),(h)=>h.charCodeAt(0))):p;return[{name:a,mimeType:o,kind:"text",data:f}]}return[]}if(u.startsWith("file://"))try{return[{name:a,mimeType:o,kind:"path",data:decodeURIComponent(new URL(u).pathname)}]}catch{return[]}return[]}function uG(e){let o=[[]];for(let a of e){if(a.type==="step-start"){if(o.at(-1)?.length)o.push([]);continue}if(a.type==="reasoning"||a.type==="text"||a.type==="tool")o.at(-1)?.push(a)}return o.filter((a)=>a.length>0)}function cG(e,o,a){let u=`${Dr(e.providerID)}/${Dr(e.modelID)}`,m=b0(e.error),p=uG(o);p.forEach((f,h)=>{let I=f.flatMap((R)=>{if(R.type==="reasoning")return Dr(R.text).trim()?[{type:"thinking",text:Dr(R.text)}]:[];if(R.type==="text")return R.ignored!==!0&&Dr(R.text).trim()?[{type:"text",text:Dr(R.text)}]:[];return[{type:"tool_call",id:x0(R.callID),name:Dr(R.tool),input:hr(R.state)&&hr(R.state.input)?R.state.input:{}}]}),E=h===p.length-1,S=mG(f);a({type:"assistant",parts:I,model:u,...E&&m&&!m.aborted?{error:m.message}:{}},S);for(let R of f){if(R.type!=="tool")continue;let k=hr(R.state)?R.state:{},A=k.status==="error",P=k.status==="pending"||k.status==="running",M=A?[Dr(k.output),Dr(k.error)].filter(Boolean).join(`
283
+ `):P?"\u5BFC\u5165\u524D\u8BE5\u8C03\u7528\u5C1A\u672A\u5B8C\u6210\uFF0C\u7ED3\u679C\u672A\u77E5\u3002":Dr(k.output);a({type:"tool_result",callID:x0(R.callID),name:Dr(R.tool),output:M,isError:A||P},fi(hr(k.time)?k.time.end:void 0))}})}function x0(e){return Dr(e).replace(/[^a-zA-Z0-9_-]/g,"_").slice(0,64)||"call"}function b0(e){if(!hr(e))return;let o=hr(e.data)?e.data:{};return{message:Dr(o.message)||Dr(e.name)||"unknown error",aborted:e.name==="MessageAbortedError"}}function mG(e){for(let o of e){let a=hr(o.time)?fi(o.time.start):hr(o.state)?pG(o.state):void 0;if(a!==void 0)return a}return}function pG(e){return hr(e.time)?fi(e.time.start):void 0}function S0(e){if(!hr(e)||typeof e.content!=="string")return[];if(e.status==="pending"||e.status==="in_progress"||e.status==="completed")return[{content:e.content,status:e.status}];return[]}function w0(e,o){let a={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return e.map(({entry:u})=>{let m=u.time;switch(u.type){case"user":return{entry:u,raw:lG(u,m)};case"assistant":{let p=u.parts.flatMap((h)=>{if(h.type==="text")return[{type:"text",text:h.text}];if(h.type==="thinking")return[];return[{type:"toolCall",id:h.id,name:h.name,arguments:dG(h.input)}]}),f=p.some((h)=>h.type==="toolCall");return{entry:u,raw:{role:"assistant",content:p,api:o.api,provider:o.provider,model:o.id,usage:a,stopReason:u.error?"error":f?"toolUse":"stop",...u.error?{errorMessage:u.error}:{},timestamp:m}}}case"tool_result":return{entry:u,raw:{role:"toolResult",toolCallId:u.callID,toolName:u.name,content:[{type:"text",text:u.output}],isError:u.isError,timestamp:m}};default:return{entry:u}}})}function lG(e,o){let a=(e.attachments??[]).flatMap((p)=>p.kind==="path"?[`<file path=${JSON.stringify(p.data)} />`]:p.kind==="text"?[`<file name=${JSON.stringify(p.name)}>
284
+ ${p.data}
285
+ </file>`]:[]),u=(e.attachments??[]).filter((p)=>p.kind==="image").map((p)=>({type:"image",data:p.data,mimeType:p.mimeType})),m=[...a,...e.text.trim()?[e.text]:[]].join(`
286
+
287
+ `);return{role:"user",content:u.length?[{type:"text",text:m},...u]:m,timestamp:o}}function hr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Dr(e){return typeof e==="string"?e:""}function fi(e){return typeof e==="number"&&Number.isFinite(e)?e:void 0}function dG(e){return hr(e)?e:{}}function Kt(e,o){let a=e.at(-1)?.entry.seq??0,u,m,p;for(let{entry:E}of e){if(E.type==="run"&&E.state==="start")u=E.seq;if(E.seq===o)if(E.type==="user"&&!E.notices)a=(u??E.seq)-1;else m=u;if(E.type==="run"&&E.state==="end"){if(m!==void 0&&u===m)p=E.seq;u=void 0}}let f=e.find((E)=>E.entry.seq===o)?.entry;if(o!==void 0&&!f)throw Error("\u6761\u76EE\u4E0D\u5B58\u5728");if(f&&!(f.type==="user"&&!f.notices)){if(m!==void 0&&p===void 0)throw Error("\u8FD9\u8F6E\u5C1A\u672A\u7ED3\u675F\uFF0C\u8BF7\u7ED3\u675F\u540E\u518D\u5206\u53C9");a=p??f.seq}else if(o===void 0&&u!==void 0)a=e.findLast(({entry:E})=>E.type==="run"&&E.state==="end")?.entry.seq??0;let h=e.filter(({entry:E})=>E.seq<=a&&(E.type!=="compaction"||E.through<=a)),I=new Map(h.map(({entry:E},S)=>[E.seq,S+1]));return h.map((E,S)=>{let R=structuredClone(E);if(R.entry.seq=S+1,R.entry.type==="compaction"){let k=R.entry.through,A=h.findLast(({entry:P})=>P.seq<=k);R.entry.through=A?I.get(A.entry.seq)??0:0}return R})}function Qt(e){let o=new Map,a=[];for(let u of e){if(u.type==="assistant"){for(let f of u.parts)if(f.type==="tool_call"&&f.name==="todo")o.set(f.id,f.input)}if(u.type!=="tool_result"||u.name!=="todo"||u.isError)continue;let m=o.get(u.callID);if(!m||typeof m!=="object"||!("todos"in m)||!Array.isArray(m.todos))continue;let p=[];for(let f of m.todos){if(!f||typeof f!=="object"||!("content"in f)||typeof f.content!=="string"||!("status"in f)||f.status!=="pending"&&f.status!=="in_progress"&&f.status!=="completed")throw Error("\u5386\u53F2\u5F85\u529E\u6570\u636E\u65E0\u6548\uFF0C\u65E0\u6CD5\u6062\u590D\u4F1A\u8BDD");p.push({content:f.content,status:f.status})}a=p}return a}import{Buffer as k0}from"buffer";import{createHash as fG}from"crypto";import{isDeepStrictEqual as Al}from"util";var Pl="@blob:";function bu(e){if(typeof e!=="object"||e===null||Array.isArray(e))return!1;let o=Object.getPrototypeOf(e);return o===Object.prototype||o===null}function T0(e,o,a){if(typeof e!=="string"||e.length<256||e.startsWith(Pl))return;let u=k0.from(e,"base64");if(u.byteLength===0||u.toString("base64")!==e)return;let m=fG("sha256").update(u).digest("hex");return a.put(m,o,new Uint8Array(u.buffer,u.byteOffset,u.byteLength)),`${Pl}${m}`}function R0(e,o){if(typeof e!=="string"||!e.startsWith(Pl))return;let a=o.get(e.slice(Pl.length));if(a===void 0)return;return k0.from(a.buffer,a.byteOffset,a.byteLength).toString("base64")}function $l(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=T0(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=T0(m.data,m.mimeType,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function hi(e,o){if(!o)return e;if(e.type==="user"){if(!e.attachments||e.attachments.length===0)return e;let a=!1,u=e.attachments.map((m)=>{if(m.kind!=="image")return m;let p=R0(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,attachments:u}}if(e.type==="tool_result"){if(!e.images||e.images.length===0)return e;let a=!1,u=e.images.map((m)=>{let p=R0(m.data,o);if(p===void 0)return m;return a=!0,{...m,data:p}});if(!a)return e;return{...e,images:u}}return e}function zc(e,o){if(!bu(o))return o;if(e.type==="user"){let{merged:a,images:u}=Bc(e.text,e.attachments),m=u.length>0?[{type:"text",text:a},...u]:a,p=Object.keys(o),{role:f,timestamp:h,content:I}=o;if(p.length===3&&f==="user"&&typeof h==="number"&&"content"in o&&Al(I,m))return{role:"user",timestamp:h};return o}if(e.type==="tool_result"){let{role:a,toolCallId:u,toolName:m,isError:p,timestamp:f,content:h}=o;if(a!=="toolResult"||u!==e.callID||typeof m!=="string"||p!==e.isError||typeof f!=="number")return o;let I=[{type:"text",text:e.output},...(e.images??[]).map((J)=>({type:"image",mimeType:J.mimeType,data:J.data}))];if("details"in o?!Al(o.details,e.meta):e.meta!==void 0)return o;let{role:S,toolCallId:R,toolName:k,content:A,details:P,isError:M,timestamp:V,..._}=o;if(Al(h,I))return{role:"toolResult",...m!==e.name?{toolName:m}:{},..._,timestamp:f};if(Array.isArray(h)){let J=e.images??[],j=0,X=!0,te=h.map((L)=>{if(bu(L)&&L.type==="image"){let se=J[j++],he=Object.keys(L);if(se&&he.length===3&&L.mimeType===se.mimeType&&L.data===se.data)return{type:"image",mimeType:L.mimeType};X=!1}return L});if(X&&j===J.length)return{role:"toolResult",...m!==e.name?{toolName:m}:{},content:te,..._,timestamp:f}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u)||u.length!==e.parts.length)return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&I?.type==="text"&&f.text===I.text){m=!0;let E={...f};return delete E.text,E}if(f.type==="thinking"&&I?.type==="thinking"&&f.thinking===I.text){m=!0;let E={...f};return delete E.thinking,E}if(f.type==="toolCall"&&I?.type==="tool_call"&&f.id===I.id&&f.name===I.name&&"arguments"in f&&Al(f.arguments,I.input)){m=!0;let E={...f};return delete E.id,delete E.name,delete E.arguments,E}}return f});if(!m)return o;return{...o,content:p}}return o}function eg(e,o){if(!bu(o))return o;if(e.type==="user"){let{role:a,timestamp:u}=o;if(a==="user"&&!("content"in o)&&typeof u==="number"&&Object.keys(o).length===2){let{merged:m,images:p}=Bc(e.text,e.attachments);return{role:"user",content:p.length>0?[{type:"text",text:m},...p]:m,timestamp:u}}return o}if(e.type==="tool_result"){let{role:a,timestamp:u}=o;if(a==="toolResult"&&(!("content"in o)||!("toolCallId"in o))&&typeof u==="number"){let{role:p,toolName:f,content:h,timestamp:I,...E}=o,S;if(Array.isArray(h)){let R=e.images??[],k=0;S=h.map((A)=>{if(bu(A)&&A.type==="image"&&!("data"in A)){let P=R[k++];if(P)return{type:"image",mimeType:A.mimeType,data:P.data}}return A})}else S=[{type:"text",text:e.output},...(e.images??[]).map((R)=>({type:"image",mimeType:R.mimeType,data:R.data}))];return{role:"toolResult",toolCallId:e.callID,toolName:typeof f==="string"?f:e.name,content:S,...e.meta!==void 0?{details:e.meta}:{},isError:e.isError,...E,timestamp:u}}return o}if(e.type==="assistant"){let{role:a,content:u}=o;if(a!=="assistant"||!Array.isArray(u))return o;let m=!1,p=u.map((f,h)=>{let I=e.parts[h];if(bu(f)){if(f.type==="text"&&!("text"in f)&&I?.type==="text"){m=!0;let{type:E,...S}=f;return{type:E,text:I.text,...S}}if(f.type==="thinking"&&!("thinking"in f)&&I?.type==="thinking"){m=!0;let{type:E,...S}=f;return{type:E,thinking:I.text,...S}}if(f.type==="toolCall"&&!("arguments"in f)&&I?.type==="tool_call"){m=!0;let{type:E,...S}=f;return{type:E,id:I.id,name:I.name,arguments:structuredClone(I.input),...S}}}return f});if(!m)return o;return{...o,content:p}}return o}function A0(e){let o=e.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)"),a=e.query("SELECT data FROM blobs WHERE hash = ?"),u={put(I,E,S){o.run(I,E,S)},get(I){return a.get(I)?.data}},m=e.query("SELECT session_id, seq, body, raw FROM entries").all(),p=e.query("UPDATE entries SET body = ?, raw = ? WHERE session_id = ? AND seq = ?"),f=e.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ?"),h=0;return e.transaction(()=>{for(let I of m){let E;try{E=JSON.parse(I.body)}catch{continue}let S=hi(E,u),R=$l(S,u),k=R===E?I.body:JSON.stringify(R),A=I.raw;if(I.raw!==null)try{let P=JSON.parse(I.raw),M=eg(S,P),V=zc(S,M);A=JSON.stringify(V)}catch{A=I.raw}if(k!==I.body)p.run(k,A,I.session_id,I.seq),h++;else if(A!==I.raw)f.run(A,I.session_id,I.seq),h++}})(),h}import{Database as hG}from"bun:sqlite";import{chmodSync as P0,existsSync as gG,mkdirSync as yG}from"fs";import{dirname as xG}from"path";var tg=[`
288
+ CREATE TABLE projects (
289
+ id TEXT PRIMARY KEY,
290
+ name TEXT NOT NULL,
291
+ directory TEXT NOT NULL UNIQUE,
292
+ instructions TEXT NOT NULL DEFAULT '',
293
+ created INTEGER NOT NULL,
294
+ updated INTEGER NOT NULL
295
+ );
296
+ CREATE TABLE automations (
297
+ id TEXT PRIMARY KEY,
298
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
299
+ name TEXT NOT NULL,
300
+ prompt TEXT NOT NULL,
301
+ schedule TEXT NOT NULL,
302
+ model TEXT NOT NULL,
303
+ enabled INTEGER NOT NULL,
304
+ created INTEGER NOT NULL,
305
+ updated INTEGER NOT NULL,
306
+ next_run INTEGER,
307
+ last_run INTEGER,
308
+ last_session_id TEXT
309
+ );
310
+ CREATE TABLE sessions (
311
+ id TEXT PRIMARY KEY,
312
+ project_id TEXT REFERENCES projects(id) ON DELETE CASCADE,
313
+ automation_id TEXT REFERENCES automations(id) ON DELETE SET NULL,
314
+ title TEXT NOT NULL DEFAULT '',
315
+ model TEXT NOT NULL,
316
+ todos TEXT NOT NULL DEFAULT '[]',
317
+ created INTEGER NOT NULL,
318
+ updated INTEGER NOT NULL
319
+ );
320
+ CREATE INDEX sessions_project ON sessions(project_id);
321
+ CREATE TABLE entries (
322
+ session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
323
+ seq INTEGER NOT NULL,
324
+ time INTEGER NOT NULL,
325
+ body TEXT NOT NULL,
326
+ raw TEXT,
327
+ PRIMARY KEY (session_id, seq)
328
+ ) WITHOUT ROWID;
329
+ `,"","","",`
330
+ ALTER TABLE sessions ADD COLUMN parent_id TEXT REFERENCES sessions(id) ON DELETE CASCADE;
331
+ ALTER TABLE sessions ADD COLUMN fork_through_seq INTEGER;
332
+ ALTER TABLE sessions ADD COLUMN kind TEXT NOT NULL DEFAULT 'main';
333
+ CREATE INDEX sessions_parent ON sessions(parent_id);`,`ALTER TABLE sessions ADD COLUMN forked_from_id TEXT;
334
+ ALTER TABLE sessions ADD COLUMN forked_from_seq INTEGER;
335
+ ALTER TABLE sessions ADD COLUMN notice_floor_seq INTEGER NOT NULL DEFAULT 0;`,"ALTER TABLE sessions ADD COLUMN truncation_epoch INTEGER NOT NULL DEFAULT 0;",`CREATE TABLE plugin_kv (namespace TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL,
336
+ PRIMARY KEY (namespace, key));
337
+ CREATE TABLE plugin_migrations (namespace TEXT NOT NULL, version INTEGER NOT NULL,
338
+ PRIMARY KEY (namespace, version));
339
+ CREATE TABLE plugin_settings (id TEXT PRIMARY KEY, enabled INTEGER NOT NULL);`,"ALTER TABLE sessions ADD COLUMN thinking TEXT;","ALTER TABLE sessions ADD COLUMN metadata TEXT;","ALTER TABLE sessions ADD COLUMN archived_at INTEGER;",`CREATE TABLE search_queue (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, seq INTEGER NOT NULL);
340
+ CREATE TRIGGER search_entries_ai AFTER INSERT ON entries BEGIN
341
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
342
+ END;
343
+ CREATE TRIGGER search_entries_ad AFTER DELETE ON entries BEGIN
344
+ INSERT INTO search_queue (session_id, seq) VALUES (old.session_id, old.seq);
345
+ END;
346
+ CREATE TRIGGER search_entries_au AFTER UPDATE OF body ON entries BEGIN
347
+ INSERT INTO search_queue (session_id, seq) VALUES (new.session_id, new.seq);
348
+ END;
349
+ CREATE TRIGGER search_sessions_ai AFTER INSERT ON sessions WHEN new.title <> '' BEGIN
350
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
351
+ END;
352
+ CREATE TRIGGER search_sessions_title AFTER UPDATE OF title ON sessions WHEN old.title IS NOT new.title BEGIN
353
+ INSERT INTO search_queue (session_id, seq) VALUES (new.id, 0);
354
+ END;
355
+ CREATE TRIGGER search_sessions_ad AFTER DELETE ON sessions BEGIN
356
+ INSERT INTO search_queue (session_id, seq) VALUES (old.id, 0);
357
+ END;`,`CREATE INDEX entries_search_compaction ON entries(session_id,json_extract(body,'$.through'))
358
+ WHERE json_extract(body,'$.type')='compaction';
359
+ CREATE TABLE IF NOT EXISTS blobs (
360
+ hash TEXT PRIMARY KEY,
361
+ mime TEXT NOT NULL,
362
+ data BLOB NOT NULL
363
+ ) WITHOUT ROWID;
364
+ CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq);`,"ALTER TABLE projects ADD COLUMN position INTEGER NOT NULL DEFAULT 0;","ALTER TABLE projects ADD COLUMN closed_at INTEGER;"];var IG=[20,50,100,200,400,800];function EG(e){if(!e||typeof e!=="object")return!1;let o="code"in e&&typeof e.code==="string"?e.code:"";if(o==="SQLITE_BUSY"||o.startsWith("SQLITE_BUSY_"))return!0;if(("errno"in e&&typeof e.errno==="number"?e.errno:0)===5)return!0;let u="message"in e&&typeof e.message==="string"?e.message:"";return/database is locked/i.test(u)}function rg(e){let o=0;while(!0)try{return e()}catch(a){let u=IG[o];if(u===void 0||!EG(a))throw a;o++,Bun.sleepSync(u)}}function $0(e,o){if(e!==":memory:")yG(xG(e),{recursive:!0});let a=new hG(e,{create:!0,strict:!0}),u=(p,f=!0)=>new Proxy(function(...h){return Reflect.apply(p,this,h)},{apply(h,I,E){Vs();let S=o.length===0&&!a.inTransaction,R=f?Reflect.get(p,"immediate"):void 0,k=()=>{let A=[];o.push(A);let P=!1;try{let M=typeof R==="function"?Reflect.apply(R,p,E):Reflect.apply(h,I,E);return P=!0,M}finally{o.pop();let M=o.at(-1);if(P&&M)M.push(...A);else for(let V of A)if(P)V.commit();else V.rollback()}};return S?rg(k):k()},get(h,I){let E=Reflect.get(p,I);if(["deferred","immediate","exclusive"].includes(String(I))&&typeof E==="function")return u(E,!1);return E}}),m=new Proxy(a,{get(p,f){let h=Reflect.get(p,f,p);if(typeof h!=="function")return h;return(...I)=>{Vs();let R=(f==="run"||f==="exec")&&o.length===0&&!a.inTransaction?rg(()=>Reflect.apply(h,p,I)):Reflect.apply(h,p,I);if(f==="transaction"&&typeof R==="function")return u(R,!0);if(f!=="query"&&f!=="prepare")return R;if(!R||typeof R!=="object")throw Error("Invalid SQL statement");return new Proxy(R,{get(k,A,P){let M=Reflect.get(k,A,k);if(typeof M!=="function")return M;return(...V)=>{Vs();let j=(A==="run"||A==="get"||A==="all"||A==="values")&&o.length===0&&!a.inTransaction?rg(()=>Reflect.apply(M,k,V)):Reflect.apply(M,k,V);return j===k?P:j}}})}}});if(e!==":memory:")P0(e,384);if(m.run("PRAGMA journal_mode = WAL"),m.run("PRAGMA synchronous = FULL"),m.run("PRAGMA foreign_keys = ON"),m.run("PRAGMA busy_timeout = 10000"),m.run("PRAGMA mmap_size = 268435456"),bG(m),m.run("CREATE TABLE IF NOT EXISTS blobs (hash TEXT PRIMARY KEY, mime TEXT NOT NULL, data BLOB NOT NULL) WITHOUT ROWID"),m.run("CREATE INDEX IF NOT EXISTS entries_session_type_seq ON entries(session_id, json_extract(body, '$.type'), seq)"),e!==":memory:")for(let p of["-wal","-shm"]){let f=e+p;if(gG(f))P0(f,384)}return m}function bG(e,o=tg){let{user_version:a}=e.query("PRAGMA user_version").get();if(a>o.length)throw Error(`\u6570\u636E\u5E93\u7248\u672C ${a} \u6BD4\u5F53\u524D Basalt \u8FD0\u884C\u65F6\u65B0\uFF08\u5F53\u524D\u6700\u9AD8\u652F\u6301 ${o.length}\uFF09\uFF0C\u8BF7\u5347\u7EA7 Basalt`);for(let u=a;u<o.length;u++)e.transaction(()=>{let m=o[u]??"",p=Array.isArray(m)?m:u>=4?SG(m):[m];for(let f of p)try{if(f.trim())e.run(f)}catch(h){if(!(h instanceof Error)||!/already exists|duplicate column name/i.test(h.message))throw h}e.run(`PRAGMA user_version = ${u+1}`)})()}function SG(e){let o=[],a=0,u=0,m=[],p=!1,f=0,h=(I)=>{let E=e.slice(a,I).trim();if(E)o.push(E);a=I+1,m=[],p=!1,f=0};while(u<e.length){let I=e[u];if(I==="'"||I==='"'||I==="`"||I==="["){let E=I==="["?"]":I;u++;while(u<e.length)if(e[u]===E)if(E!=="]"&&e[u+1]===E)u+=2;else break;else u++;u++;continue}if(I==="-"&&e[u+1]==="-"){let E=e.indexOf(`
365
+ `,u);u=E===-1?e.length:E+1;continue}if(I==="/"&&e[u+1]==="*"){let E=e.indexOf("*/",u+2);u=E===-1?e.length:E+2;continue}if(/[A-Za-z_]/.test(I)){let E=u+1;while(E<e.length&&/[A-Za-z0-9_$]/.test(e[E]))E++;let S=e.slice(u,E).toUpperCase();if(m.length<3)m.push(S),p=m[0]==="CREATE"&&(m[1]==="TRIGGER"||m[2]==="TRIGGER");if(p){if(S==="BEGIN"||S==="CASE"&&f>0)f++;else if(S==="END"&&f>0)f--}u=E;continue}if(I===";"&&f===0)h(u);u++}return h(e.length),o}var Cl=({position:e,closed_at:o,...a})=>({...a,closedAt:o??null}),vl=(e)=>{let o;if(e.metadata)try{o=JSON.parse(e.metadata)}catch{}if(e.automation_id&&!o?.["automations.id"])o={...o,"automations.id":e.automation_id};return{id:e.id,title:e.title,projectID:e.project_id,metadata:o,model:e.model,thinking:e.thinking??null,todos:JSON.parse(e.todos),created:e.created,updated:e.updated,archivedAt:e.archived_at??null,...e.forked_from_id!==null&&e.forked_from_seq!==null?{forkedFrom:{id:e.forked_from_id,seq:e.forked_from_seq}}:{},parentID:e.parent_id??null,forkThroughSeq:e.fork_through_seq??null,kind:e.kind??"main"}};var Ml=new Set(["user","run","extension","notice_pending","compaction"]);class Ol{path;plugins;entryTransactions=[];db;blobs;smallEntries=new Map;constructor(e){this.path=e;this.db=$0(e,this.entryTransactions),this.blobs={put:(o,a,u)=>{this.db.query("INSERT OR IGNORE INTO blobs (hash, mime, data) VALUES (?, ?, ?)").run(o,a,u)},get:(o)=>this.db.query("SELECT data FROM blobs WHERE hash = ?").get(o)?.data}}close(){this.db.close()}projects(){return this.db.query("SELECT * FROM projects ORDER BY position, updated DESC").all().map(Cl)}project(e){let o=this.db.query("SELECT * FROM projects WHERE id = ?").get(e);return o?Cl(o):void 0}projectByDirectory(e){let o=this.db.query("SELECT * FROM projects WHERE directory = ?").get(e);return o?Cl(o):void 0}insertProject(e){this.db.query("INSERT INTO projects (id, name, directory, instructions, created, updated, position) VALUES (?, ?, ?, ?, ?, ?, (SELECT COALESCE(MAX(position), -1) + 1 FROM projects))").run(e.id,e.name,e.directory,e.instructions,e.created,e.updated)}reorderProjects(e){this.db.transaction(()=>{let o=this.db.query("UPDATE projects SET position = ? WHERE id = ?");for(let[a,u]of e.entries())o.run(a,u)})()}updateProject(e){this.db.query("UPDATE projects SET name = ?, instructions = ?, updated = ?, closed_at = ? WHERE id = ?").run(e.name,e.instructions,e.updated,e.closedAt,e.id)}deleteProject(e){let o=this.sessionIDs(e);for(let a of o)this.invalidateEntryCache(a);this.db.transaction(()=>{let a=new Set;for(let u of o)for(let m of this.collectSessionBlobHashes(u))a.add(m);this.db.query("DELETE FROM projects WHERE id = ?").run(e),this.pruneCandidateBlobs(a)})()}sessions(){return this.db.query("SELECT * FROM sessions WHERE parent_id IS NULL ORDER BY updated DESC, id").all().map(vl)}allSessions(){return this.db.query("SELECT * FROM sessions").all().map(vl)}childSessions(e){return this.db.query("SELECT * FROM sessions WHERE parent_id = ?").all(e).map(vl)}sessionIDs(e){return this.db.query("SELECT id FROM sessions WHERE project_id = ?").all(e).map((o)=>o.id)}insertSession(e){this.db.query("INSERT INTO sessions (id, project_id, title, model, thinking, todos, created, updated, parent_id, fork_through_seq, kind, forked_from_id, forked_from_seq, metadata, archived_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(e.id,e.projectID,e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.created,e.updated,e.parentID??null,e.forkThroughSeq??null,e.kind??"main",e.forkedFrom?.id??null,e.forkedFrom?.seq??null,e.metadata?JSON.stringify(e.metadata):null,e.archivedAt??null)}copySession(e,o,a){this.insertSessionWithRecords(o,Kt(this.records(e),a))}insertSessionWithRecords(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{this.insertSession(e),this.db.query("UPDATE sessions SET notice_floor_seq = ? WHERE id = ?").run(o.at(-1)?.entry.seq??0,e.id);let a=this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)");for(let{entry:u,raw:m}of o){let{seq:p,time:f,...h}=u,I=h,E=$l(I,this.blobs),S=m===void 0?null:JSON.stringify(zc(I,m));a.run(e.id,p,f,JSON.stringify(E),S)}})()}truncationEpoch(e){let o=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!o)throw Error("Session no longer exists");return o.truncation_epoch}truncateSession(e,o){this.invalidateEntryCache(e.id),this.db.transaction(()=>{let a=this.collectSessionBlobHashes(e.id,o);this.db.query("DELETE FROM entries WHERE session_id = ? AND (seq >= ? OR (json_extract(body, '$.type') = 'compaction' AND json_extract(body, '$.through') >= ?) OR json_extract(body, '$.type') = 'notice_pending')").run(e.id,o,o),this.db.query("UPDATE sessions SET notice_floor_seq = MIN(notice_floor_seq, ?), truncation_epoch = truncation_epoch + 1 WHERE id = ?").run(o-1,e.id),this.updateSession(e),this.pruneCandidateBlobs(a)})()}atomic(e){return this.db.transaction(e)()}setArchived(e,o){this.db.transaction(()=>{let a=this.db.query("UPDATE sessions SET archived_at = ? WHERE id = ?");for(let u of e)a.run(o,u)})()}updateSession(e){this.db.query("UPDATE sessions SET title = ?, model = ?, thinking = ?, todos = ?, updated = ? WHERE id = ?").run(e.title,e.model,e.thinking??null,JSON.stringify(e.todos),e.updated,e.id)}deleteSession(e){this.invalidateEntryCache(e),this.db.transaction(()=>{let o=new Set,a=[e];while(a.length>0){let u=a.pop();if(!u)continue;for(let m of this.collectSessionBlobHashes(u))o.add(m);for(let m of this.childSessions(u))a.push(m.id)}this.db.query("DELETE FROM sessions WHERE id = ?").run(e),this.pruneCandidateBlobs(o)})()}collectSessionBlobHashes(e,o=1){let a=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq >= ? AND body LIKE '%@blob:%'").all(e,o),u=new Set;for(let m of a)for(let p of m.body.matchAll(/@blob:([0-9a-f]{64})/g))if(p[1])u.add(p[1]);return u}pruneCandidateBlobs(e){if(e.size===0)return;let o=this.db.query("SELECT 1 AS one FROM entries WHERE body LIKE ? LIMIT 1"),a=this.db.query("DELETE FROM blobs WHERE hash = ?");for(let u of e)if(!o.get(`%@blob:${u}%`))a.run(u)}lastSeq(e){return this.db.query("SELECT max(seq) AS seq FROM entries WHERE session_id = ?").get(e)?.seq??0}appendEntry(e,o,a,u){Vs();let m=this.plugins,p=m?.pinEntry(a),f;try{return f=this.db.transaction(()=>{let h=Math.max(o??0,this.lastSeq(e)+1),E=(p&&m?m.beforeEntry(p,a,e,h):void 0)??a,S=JSON.stringify(E),R=p?JSON.parse(S):E,k={...R,seq:h,time:Date.now()},A=$l(R,this.blobs),P=A===R&&!p?S:JSON.stringify(A),M=u===void 0?null:JSON.stringify(zc(R,u));if(this.db.query("INSERT INTO entries (session_id, seq, time, body, raw) VALUES (?, ?, ?, ?, ?)").run(e,h,k.time,P,M),k.type==="user"&&!(("notices"in k)&&k.notices))this.db.query("UPDATE sessions SET updated = ? WHERE id = ?").run(k.time,e);return this.cacheAppended(e,k,P),k})(),f}finally{if(p&&m){let h={commit:()=>m.finishEntry(p,e,f),rollback:()=>m.finishEntry(p,e)},I=this.entryTransactions.at(-1);if(I)I.push(h);else h.commit()}}}setEntryRaw(e,o,a){let u=this.db.query("SELECT body FROM entries WHERE session_id = ? AND seq = ? AND raw IS NULL").get(e,o);if(!u)throw Error("pending message entry is missing or already completed");let m=hi(JSON.parse(u.body),this.blobs),p=zc(m,a);if(this.db.query("UPDATE entries SET raw = ? WHERE session_id = ? AND seq = ? AND raw IS NULL").run(JSON.stringify(p),e,o).changes!==1)throw Error("pending message entry is missing or already completed")}entries(e,o=0,a,u=!0){if(a&&a.length===0)return[];let m=a?.every((f)=>Ml.has(f))?this.cachedEntries(e):void 0;if(m&&a)return m.filter((h)=>h.seq>o&&a.includes(h.type)).map((h)=>({...u?hi(h,this.blobs):h}));return(a?this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq > ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,o,...a):this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o)).map((f)=>({...hi(JSON.parse(f.body),u?this.blobs:void 0),seq:f.seq,time:f.time}))}deleteEntry(e,o){this.invalidateEntryCache(e),this.db.query("DELETE FROM entries WHERE session_id = ? AND seq = ?").run(e,o)}invalidateEntryCache(e){if(e===void 0)this.smallEntries.clear();else this.smallEntries.delete(e)}cachedEntries(e){if(this.db.inTransaction)return;let o=this.smallEntries.get(e);if(o)return o;let a=[...Ml],u=this.db.query(`SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') IN (${a.map(()=>"?").join(", ")}) ORDER BY seq`).all(e,...a).map((m)=>({...JSON.parse(m.body),seq:m.seq,time:m.time}));return this.smallEntries.set(e,u),u}cacheAppended(e,o,a){let u=this.smallEntries.get(e);if(!u||!Ml.has(o.type))return;if(this.entryTransactions.length>1){this.smallEntries.delete(e);return}u.push({...JSON.parse(a),seq:o.seq,time:o.time})}entriesRange(e,o,a=Number.MAX_SAFE_INTEGER){return this.db.query("SELECT seq, time, body FROM entries WHERE session_id = ? AND seq >= ? AND seq < ? ORDER BY seq").all(e,o,a).map((u)=>({...hi(JSON.parse(u.body),this.blobs),seq:u.seq,time:u.time}))}alignToUser(e,o){if(o<=1)return 1;return this.db.query("SELECT max(seq) AS seq FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND seq <= ? AND json_extract(body, '$.type') IN ('user', 'compaction')").get(e,o)?.seq??1}alignToTurnEnd(e,o){let a=this.lastSeq(e),u=(I)=>this.db.query("SELECT json_extract(body, '$.type') AS type, json_extract(body, '$.state') AS state FROM entries WHERE session_id = ? AND seq = ?").get(e,I),m=u(o),p=m?.type==="run"&&m.state==="start"?o+1:o;if(p>=a)return a;let f=this.db.query("SELECT seq, json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end' AS end FROM entries WHERE session_id = ? AND seq >= ? AND ((json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'end') OR (seq > ? AND (json_extract(body, '$.type') IN ('user', 'compaction') OR (json_extract(body, '$.type') = 'run' AND json_extract(body, '$.state') = 'start')))) ORDER BY seq LIMIT 1").get(e,p,p);if(!f)return a;if(f.end)return f.seq;let h=u(f.seq-1);return h?.type==="run"&&h.state==="start"&&f.seq-1>p?f.seq-2:f.seq-1}entriesAround(e,o,a,u){let m=this.lastSeq(e);if(m===0)return{entries:[],from:1,to:0,hasBefore:!1,hasAfter:!1};let p=Math.min(Math.max(1,o),m),f=this.alignToUser(e,Math.max(1,p-a)),h=this.alignToTurnEnd(e,Math.min(m,p+u));return this.window(e,f,h,m)}entriesFrom(e,o,a){let u=this.lastSeq(e),m=Math.max(1,o);if(m>u)return{entries:[],from:m,to:u,hasBefore:u>0,hasAfter:!1};let p=this.alignToTurnEnd(e,Math.min(u,m+a-1));return this.window(e,m,p,u)}window(e,o,a,u){let m=this.db.query("SELECT 1 AS one FROM entries WHERE session_id = ? AND seq < ? LIMIT 1").get(e,o);return{entries:this.entriesRange(e,o,a+1),from:o,to:a,hasBefore:m!==null,hasAfter:a<u}}replayStart(e,o,a,u=Number.POSITIVE_INFINITY){let m=this.lastSeq(e),p=this.lastEntry(e,"compaction"),f=p?.type==="compaction"?p.through+1:1,h=Math.max(1,m-o+1),I=Math.max(1,m-a+1,Math.min(f,h));return this.alignToUser(e,I<h?Math.min(h,this.budgetStart(e,I,u)):I)}budgetStart(e,o,a){let u=this.db.query("SELECT seq, length(body) AS size FROM entries WHERE session_id = ? AND seq >= ? ORDER BY seq DESC").all(e,o),m=0;for(let p of u)if(m+=p.size,m>a)return p.seq+1;return o}records(e,o=0){return this.db.query("SELECT seq, time, body, raw FROM entries WHERE session_id = ? AND seq > ? ORDER BY seq").all(e,o).map((a)=>{let u=hi(JSON.parse(a.body),this.blobs);return{entry:{...u,seq:a.seq,time:a.time},...a.raw===null?{}:{raw:eg(u,JSON.parse(a.raw))}}})}lastEntry(e,o){if(Ml.has(o)){let u=this.cachedEntries(e);if(u){let m=u.findLast((p)=>p.type===o);return m?{...hi(m,this.blobs)}:void 0}}let a=this.db.query("SELECT seq, time, body FROM entries INDEXED BY entries_session_type_seq WHERE session_id = ? AND json_extract(body, '$.type') = ? ORDER BY seq DESC LIMIT 1").get(e,o);return a?{...hi(JSON.parse(a.body),this.blobs),seq:a.seq,time:a.time}:void 0}async enqueueNotice(e,o){let a=this.truncationEpoch(e),u=o;if(this.plugins){let m=this.plugins.pin();try{let p=await m.invoke("notice.enqueue",o,this.plugins.runtime.get(e));if(p===null)return!1;o={...p,dedupeKey:u.dedupeKey,wake:u.wake&&p.wake,recovery:u.recovery}}finally{await m.release()}}return this.db.transaction(()=>{let m=this.db.query("SELECT truncation_epoch FROM sessions WHERE id = ?").get(e);if(!m||m.truncation_epoch!==a)return!1;if(this.entries(e,0,["user","notice_pending"],!1).some((h)=>h.type==="notice_pending"&&h.notice.dedupeKey===o.dedupeKey||h.type==="user"&&h.notices?.some((I)=>I.dedupeKey===o.dedupeKey)))return!1;return this.appendEntry(e,this.lastSeq(e)+1,{type:"notice_pending",notice:o}),!0})()}pendingNotices(e){let o=this.db.query("SELECT notice_floor_seq FROM sessions WHERE id = ?").get(e)?.notice_floor_seq??0,a=this.entries(e,o,["user","extension","notice_pending"],!1),u=new Set;for(let p of a)if(p.type==="user"&&p.notices)for(let f of p.notices)u.add(f.dedupeKey);else if(p.type==="extension"&&p.namespace==="basalt.notice"&&p.kind==="discarded"&&p.payload&&typeof p.payload==="object"&&"dedupeKey"in p.payload&&typeof p.payload.dedupeKey==="string")u.add(p.payload.dedupeKey);let m=[];for(let p of a)if(p.type==="notice_pending"&&!u.has(p.notice.dedupeKey))m.push(p.notice);return m}}function ne(e){let o=crypto.getRandomValues(new Uint8Array(6));return`${e}${Date.now().toString(36)}${Buffer.from(o).toString("base64url")}`}import{existsSync as wG,readdirSync as M0,statSync as O0}from"fs";import{join as _0}from"path";function Vc(e){try{return O0(e).size}catch{return 0}}function L0(e){try{return Math.round(O0(e).mtimeMs)}catch{return}}function N0(e){let o=0,a=0;try{let u=M0(e,{withFileTypes:!0});for(let m of u){let p=_0(e,m.name);if(m.isDirectory()){let f=N0(p);o+=f.bytes,a+=f.files}else if(m.isFile())o+=Vc(p),a+=1}}catch{return{bytes:0,files:0}}return{bytes:o,files:a}}function TG(e){if(!wG(e))return[];try{return M0(e,{withFileTypes:!0}).flatMap((o)=>{let a=_0(RG(e),o.name),u=L0(a);if(o.isDirectory()){let m=N0(a);return[{name:o.name,kind:"directory",bytes:m.bytes,files:m.files,...u!==void 0?{modified:u}:{}}]}if(o.isFile())return[{name:o.name,kind:"file",bytes:Vc(a),...u!==void 0?{modified:u}:{}}];return[]}).sort((o,a)=>a.bytes-o.bytes||o.name.localeCompare(a.name))}catch{return[]}}function RG(e){return e}function gi(e,o){let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return 0;let u=Object.values(a)[0];return typeof u==="number"?u:0}function C0(e,o){try{let a=e.db.query(`PRAGMA ${o}`).get();if(!a)return;let u=Object.values(a)[0];return u!==void 0&&u!==null?String(u):void 0}catch{return}}var kG={0:"OFF (0)",1:"NORMAL (1)",2:"FULL (2)",3:"EXTRA (3)"},AG={0:"NONE (0)",1:"FULL (1)",2:"INCREMENTAL (2)"};function PG(e){let o=new Map;try{let a=new Map,u=e.db.query("SELECT name, tbl_name FROM sqlite_master WHERE type = 'index' AND name NOT LIKE 'sqlite_%'").all();for(let p of u)a.set(p.name,p.tbl_name);let m=e.db.query("SELECT name, count(*) AS pages, sum(pgsize) AS bytes FROM dbstat GROUP BY name").all();for(let p of m){let f=a.get(p.name)??p.name;if(f.startsWith("sqlite_autoindex_")){let I=f.slice(17),E=I.lastIndexOf("_");if(E>0)f=I.slice(0,E)}let h=o.get(f)??{bytes:0,pages:0};o.set(f,{bytes:h.bytes+(Number(p.bytes)||0),pages:h.pages+(Number(p.pages)||0)})}}catch{}return o}function $G(e){let o=e.db.query("SELECT count(*) AS c FROM projects").get()?.c??0,a=e.db.query(`SELECT
366
+ count(*) AS total,
367
+ sum(CASE WHEN parent_id IS NULL THEN 1 ELSE 0 END) AS main_count,
368
+ sum(CASE WHEN parent_id IS NOT NULL THEN 1 ELSE 0 END) AS sub_count,
369
+ sum(CASE WHEN forked_from_id IS NOT NULL THEN 1 ELSE 0 END) AS forked_count,
370
+ sum(CASE WHEN automation_id IS NOT NULL THEN 1 ELSE 0 END) AS auto_count
371
+ FROM sessions`).get(),u=e.db.query(`SELECT
372
+ count(*) AS total,
373
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
374
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes,
375
+ min(time) AS oldest_time,
376
+ max(time) AS newest_time
377
+ FROM entries`).get(),p=e.db.query(`SELECT
378
+ coalesce(json_extract(body, '$.type'), 'unknown') AS type,
379
+ count(*) AS count,
380
+ coalesce(sum(octet_length(body)), 0) AS body_bytes,
381
+ coalesce(sum(octet_length(raw)), 0) AS raw_bytes
382
+ FROM entries
383
+ GROUP BY type
384
+ ORDER BY (body_bytes + raw_bytes) DESC, count DESC`).all().map((I)=>({type:String(I.type||"unknown"),count:Number(I.count)||0,bodyBytes:Number(I.body_bytes)||0,rawBytes:Number(I.raw_bytes)||0})),f=p.find((I)=>I.type==="compaction")?.count??0,h=[];try{let I=new Map,E=e.db.query("SELECT namespace, max(version) AS max_ver FROM plugin_migrations GROUP BY namespace").all();for(let k of E)I.set(k.namespace,Number(k.max_ver)||0);let S=e.db.query(`SELECT
385
+ namespace,
386
+ count(*) AS keys,
387
+ coalesce(sum(octet_length(key) + octet_length(value)), 0) AS bytes
388
+ FROM plugin_kv
389
+ GROUP BY namespace
390
+ ORDER BY bytes DESC, keys DESC`).all(),R=new Set;for(let k of S){R.add(k.namespace);let A=I.get(k.namespace);h.push({namespace:k.namespace,keys:Number(k.keys)||0,bytes:Number(k.bytes)||0,...A!==void 0?{migrationVersion:A}:{}})}for(let[k,A]of I.entries())if(!R.has(k))h.push({namespace:k,keys:0,bytes:0,migrationVersion:A})}catch{}return{projectCount:o,mainSessionCount:Number(a?.main_count)||0,subSessionCount:Number(a?.sub_count)||0,forkedSessionCount:Number(a?.forked_count)||0,automationSessionCount:Number(a?.auto_count)||0,totalEntries:Number(u?.total)||0,totalBodyBytes:Number(u?.body_bytes)||0,totalRawBytes:Number(u?.raw_bytes)||0,compactionCount:f,...u?.oldest_time?{oldestEntryTime:Number(u.oldest_time)}:{},...u?.newest_time?{newestEntryTime:Number(u.newest_time)}:{},entryTypes:p,pluginNamespaces:h}}function _l(e,o){let a=gi(e,"page_size"),u=gi(e,"page_count"),m=gi(e,"freelist_count"),p=e.db.query("PRAGMA journal_mode").get(),f=e.db.query("SELECT sqlite_version() AS v").get(),h=gi(e,"synchronous"),I=gi(e,"auto_vacuum"),E=gi(e,"cache_size"),S=E<0?Math.abs(E)*1024:E*a,R=gi(e,"foreign_keys")===1,k=gi(e,"busy_timeout"),A=C0(e,"encoding")??"UTF-8",P=C0(e,"quick_check(1)")??"ok",M=e.path!==":memory:"?L0(e.path):void 0,V=e.db.query("SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name").all(),_=PG(e),J=TG(o);return{dataDir:o,databasePath:e.path,dataBytes:J.reduce((j,X)=>j+X.bytes,0),database:{size:Vc(e.path),walSize:Vc(`${e.path}-wal`),shmSize:Vc(`${e.path}-shm`),sqliteVersion:f?.v??"unknown",journalMode:p?.journal_mode??"unknown",synchronous:kG[h]??String(h),foreignKeys:R,busyTimeout:k,encoding:A,autoVacuum:AG[I]??String(I),cacheSizeBytes:S,pageSize:a,pageCount:u,freelistCount:m,reclaimableBytes:m*a,schemaVersion:gi(e,"user_version"),...M!==void 0?{lastModified:M}:{},integrity:P},analytics:$G(e),entries:J,tables:V.map(({name:j,sql:X})=>{let te=j.replaceAll('"','""'),L=e.db.query(`SELECT count(*) AS count FROM "${te}"`).get().count,se=e.db.query(`PRAGMA table_info("${te}")`).all().map((Q)=>Q.name),he=e.db.query(`PRAGMA index_list("${te}")`).all().length,Me=Boolean(X&&/WITHOUT\s+ROWID/i.test(X)),We=_.get(j);return{name:j,rows:L,...We?{bytes:We.bytes,pages:We.pages}:{},indexes:he,columns:se,withoutRowid:Me}})}}function v0(e){let o;try{o=e.db.query("SELECT hash FROM blobs").all()}catch{return 0}if(o.length===0)return 0;let a=e.db.query("SELECT body FROM entries WHERE body LIKE '%@blob:%'").all(),u=new Set;for(let p of a)for(let f of p.body.matchAll(/@blob:([0-9a-f]{64})/g)){let h=f[1];if(h)u.add(h)}let m=[];for(let p of o)if(!u.has(p.hash))m.push(p.hash);if(m.length===0)return 0;try{e.db.transaction(()=>{let p=e.db.query("DELETE FROM blobs WHERE hash = ?");for(let f of m)p.run(f)})()}catch{return 0}return m.length}function q0(e,o,a){let u=_l(e,o);if(a.vacuum)A0(e.db),e.invalidateEntryCache(),v0(e),e.db.run("VACUUM");else if(a.checkpoint)v0(e);if(a.checkpoint||a.vacuum)e.db.run("PRAGMA wal_checkpoint(TRUNCATE)");return{before:u,after:_l(e,o)}}var CG=new Set(["toolsearch","tool_search","tool_call","database_search"]);class Ll{plugins;builtinNames;registered=new Map;constructor(e,o){this.plugins=e;this.builtinNames=o}list(){return[...this.registered.values(),...this.plugins.registeredTools()]}register(e){let o=e.name.trim().toLowerCase();if(!o)throw Error("Tool name cannot be empty");if(CG.has(o))throw Error(`Tool name '${e.name}' is reserved by the system`);if(new Set([...this.builtinNames().map((u)=>u.toLowerCase()),...this.list().map((u)=>u.name.toLowerCase())]).has(o))throw Error(`Tool names collide ignoring case: ${e.name}`);this.registered.set(o,e)}unregister(e){return this.registered.delete(e.trim().toLowerCase())}snapshot(){return[...this.registered.values()]}policy(e){return this.plugins.toolPolicy(e)}}function D0(e,o){let a=_n(o);return{id:e,name:o.name,reasoning:!0,thinkingLevels:a.length>0?a:["off","minimal","low","medium","high","max"],contextWindow:o.contextWindow,maxTokens:o.maxTokens}}async function F0(e,o){let a=e.options.visibleModelProviders?.(),m=(await e.options.models.getAvailable().catch(()=>[])).filter((f)=>!a||a.includes(f.provider)).map((f)=>({...D0(kt(f),f),available:!0})),p=new Set(m.map((f)=>f.id));for(let f of[o,...e.list(!0,{archive:"all"}).map((h)=>h.model)]){if(p.has(f))continue;let h=kn(e.options.models,f);if(!h||a&&!a.includes(h.provider))continue;p.add(f),m.push({...D0(f,h),available:!1})}return{models:m}}function j0(e,o){if(typeof o!=="string"||!kn(e.options.models,o))throw new t(`unknown model ${o}`);return o}import{existsSync as vG,statSync as MG}from"fs";import{basename as OG,resolve as _G}from"path";class ng{runtime;sessions;emit;arm;constructor(e,o,a,u){this.runtime=e;this.sessions=o;this.emit=a;this.arm=u}requireProject(e){let o=this.runtime.store.project(e);if(!o)throw new y("no such project");return o}createProject(e){if(typeof e.directory!=="string"||!e.directory.trim())throw new t("directory is required");let o=_G(e.directory.trim());if(!vG(o)||!MG(o).isDirectory())throw new t(`${o} is not a directory on the server`);let a=this.runtime.store.projectByDirectory(o);if(a){if(a.closedAt!==null)return this.updateProject(a.id,{closed:!1});return a}let u=Date.now(),m={id:ne("p"),name:e.name?.trim()||OG(o)||o,directory:o,instructions:e.instructions??"",created:u,updated:u,closedAt:null};return this.runtime.store.insertProject(m),this.emit({type:"project",project:m}),m}updateProject(e,o){let u={...this.requireProject(e),...typeof o.name==="string"&&o.name.trim()?{name:o.name.trim()}:{},...typeof o.instructions==="string"?{instructions:o.instructions}:{},...typeof o.closed==="boolean"?{closedAt:o.closed?Date.now():null}:{},updated:Date.now()};this.runtime.store.updateProject(u);for(let m of this.sessions.values())if(m.projectID===e)m.reset();return this.emit({type:"project",project:u}),u}reorderProjects(e){if(!Array.isArray(e)||!e.every((m)=>typeof m==="string"))throw new t("ids must be an array of project IDs");let o=new Set(this.runtime.store.projects().map((m)=>m.id)),a=new Set(e);if(!(a.size===e.length&&a.size===o.size&&e.every((m)=>o.has(m))))throw new t("ids must list every project exactly once; refresh the project list and retry");this.runtime.store.reorderProjects(e),this.emit({type:"project_order",ids:e})}async deleteProject(e){let o=this.requireProject(e),a=[...this.sessions.values()].filter((m)=>m.projectID===e);if(a.some((m)=>m.status==="busy"))throw new oe("a session in this project");await this.runtime.plugins.invokeProjectDelete(o),this.runtime.store.deleteProject(e);for(let m of a)m.close(),this.runtime.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});this.emit({type:"removed",kind:"project",id:e}),this.arm?.()}}import{existsSync as tK,readFileSync as rK}from"fs";import{homedir as nK}from"os";import{join as Su}from"path";var z0=new Set(["in","project","session","from","role","tool","model","is","after","before","date"]),LG={user:["user"],assistant:["assistant"],thinking:["thinking"],tool:["tool_input","tool_output"],input:["tool_input"],output:["tool_output"],tool_input:["tool_input"],tool_output:["tool_output"],error:["error"],title:["title"],attachment:["attachment"],notice:["notice"],extension:["extension"]},NG=new Set(['"',"\\","-","*",":","\u201C","\u201D"]),ig={'"':['"'],"\u201C":["\u201D",'"']},og=(e)=>e!==void 0&&/\s/.test(e),V0=(e)=>[...new Set(e)],Jc=(e)=>[...e].length;var qG={h:3600000,d:86400000,w:604800000,mo:2592000000,y:31536000000};function DG(e,o){let a=e.trim().toLowerCase(),u=new Date(o),m=u.getFullYear(),p=u.getMonth(),f=u.getDate();if(a==="today")return{start:new Date(m,p,f).getTime(),end:new Date(m,p,f+1).getTime()};if(a==="yesterday")return{start:new Date(m,p,f-1).getTime(),end:new Date(m,p,f).getTime()};let h=/^(\d+)(h|d|w|mo|y)$/.exec(a);if(h)return{start:o-Number(h[1])*qG[h[2]]};if(/^\d{4}$/.test(a))return{start:new Date(Number(a),0,1).getTime(),end:new Date(Number(a)+1,0,1).getTime()};let I=/^(\d{4})([-/])(\d{1,2})(?:\2(\d{1,2}))?(?:t(\d{1,2}):(\d{2})(?::(\d{2}))?)?$/.exec(a);if(!I)return null;let E=Number(I[1]),S=Number(I[3]);if(S<1||S>12)return null;if(I[4]===void 0){if(I[5]!==void 0)return null;return{start:new Date(E,S-1,1).getTime(),end:new Date(E,S,1).getTime()}}let R=Number(I[4]),k=Number(I[5]??0),A=Number(I[6]??0),P=Number(I[7]??0);if(k>23||A>59||P>59)return null;let M=new Date(E,S-1,R,k,A,P);if(M.getMonth()!==S-1||M.getDate()!==R)return null;if(I[5]!==void 0)return{start:M.getTime()};return{start:M.getTime(),end:new Date(E,S-1,R+1).getTime()}}var FG=()=>({projectID:[],sessionID:[],fields:[],tools:[],model:[],currentSession:!1,diagnostics:[]}),ag=(e,o)=>e===void 0?o:o===void 0?e:Math.max(e,o),ug=(e,o)=>e===void 0?o:o===void 0?e:Math.min(e,o);function sg(e,o,a,u,m,p){let f=a.trim(),h=(E,S)=>e.diagnostics.push({code:E,message:S,filter:o});if(!f)return h("empty_filter",`${o}: \u7F3A\u5C11\u53D6\u503C`);if(u&&o!=="is")return h("unsupported_negation",`-${o}: \u4E0D\u652F\u6301\u53D6\u53CD`);let I=m?[f]:f.split(",").map((E)=>E.trim()).filter(Boolean);switch(o){case"in":case"project":for(let E of I){let S=E.toLowerCase();if(o==="in"&&S==="this")e.currentSession=!0;else if(o==="in"&&S==="title")e.fields.push("title");else e.projectID.push(E)}return;case"session":for(let E of I)if(E.toLowerCase()==="this")e.currentSession=!0;else e.sessionID.push(E);return;case"from":case"role":for(let E of I){let S=LG[E.toLowerCase()];if(S)e.fields.push(...S);else h("bad_filter_value",`${o}:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u89D2\u8272/\u5B57\u6BB5`)}return;case"tool":e.tools.push(...I);return;case"model":e.model.push(...I);return;case"is":for(let E of I){let S=E.toLowerCase();if(S==="error")e.isError=!u;else if(S==="archived")e.archived=!u;else if(S==="compacted")e.compacted=!u;else h("bad_filter_value",`is:${E} \u4E0D\u662F\u5DF2\u77E5\u7684\u72B6\u6001\uFF08error/archived/compacted\uFF09`)}return;case"after":case"before":case"date":{let E=DG(f,p);if(!E)return h("bad_filter_value",`${o}:${f} \u4E0D\u662F\u6709\u6548\u7684\u65F6\u95F4`);if(o==="after")e.after=ag(e.after,E.start);else if(o==="before")e.before=ug(e.before,E.start);else if(e.after=ag(e.after,E.start),E.end!==void 0)e.before=ug(e.before,E.end)}}}function jG(e,o){let a={},u=(P,M)=>{let V=V0([...P??[],...M]);return V.length?V:void 0},m=u(e?.projectID,o.projectID),p=u(e?.sessionID,o.sessionID),f=u(e?.fields,o.fields),h=u(e?.tools,o.tools),I=u(e?.model,o.model);if(m)a.projectID=m;if(p)a.sessionID=p;if(f)a.fields=f;if(h)a.tools=h;if(I)a.model=I;let E=o.isError??e?.isError,S=o.archived??e?.archived,R=o.compacted??e?.compacted;if(E!==void 0)a.isError=E;if(S!==void 0)a.archived=S;if(R!==void 0)a.compacted=R;let k=ag(e?.after,o.after),A=ug(e?.before,o.before);if(k!==void 0)a.after=k;if(A!==void 0)a.before=A;if(k!==void 0&&A!==void 0&&k>=A)o.diagnostics.push({code:"empty_time_range",message:"after \u4E0D\u65E9\u4E8E before\uFF0C\u65F6\u95F4\u8303\u56F4\u4E3A\u7A7A"});return a}function U0(e,o){let a=ig[e[o]]??['"'],u="",m=o+1;while(m<e.length){let p=e[m],f=e[m+1];if(p==="\\"&&f!==void 0&&(f==="\\"||f==='"'||f==="\u201C"||f==="\u201D")){u+=f,m+=2;continue}if(a.includes(p))return{text:u,next:m+1,closed:!0};u+=p,m++}return{text:u,next:m,closed:!1}}function B0(e){let o=e[e.length-1];if(e.length<2||!o||o.esc||o.c!==":"&&o.c!=="\uFF1A")return;let a=e.slice(0,-1).map((m)=>m.esc||!/[A-Za-z]/.test(m.c)?"":m.c).join("");if(a.length!==e.length-1)return;let u=a.toLowerCase();return z0.has(u)?u:void 0}function G0(e,o,a){let u=e==="word"&&!a&&Jc(o)>=4&&/^[\p{Script=Latin}\p{N}_]+$/u.test(o)&&!/^\p{N}+$/u.test(o);return{kind:e,text:o,prefix:a,fuzzy:u}}function UG(e,o){let a=[],u=e.length,m=0;while(m<u){if(og(e[m])){m++;continue}let p=!1;if(e[m]==="-"){if(m+1>=u||og(e[m+1])){m++;continue}p=!0,m++}if(ig[e[m]]){let A=U0(e,m);if(m=A.next,!A.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});let P=A.text.trim();if(P)a.push({kind:"term",negated:p,term:G0("phrase",P,!1)});continue}let f=[],h;while(m<u&&!og(e[m])){let A=e[m],P=e[m+1];if(A==="\\"&&P!==void 0&&NG.has(P)){f.push({c:P,esc:!0}),m+=2;continue}let M=ig[A]?B0(f):void 0;if(M){let V=U0(e,m);if(m=V.next,!V.closed)o.push({code:"unclosed_quote",message:"\u5F15\u53F7\u672A\u95ED\u5408\uFF0C\u5DF2\u6309\u5230\u672B\u5C3E\u5904\u7406"});h={key:M,value:V.text,quoted:!0};break}f.push({c:A,esc:!1}),m++}if(h){a.push({kind:"filter",negated:p,...h});continue}let I=f.findIndex((A,P)=>P>0&&!A.esc&&(A.c===":"||A.c==="\uFF1A")),E=I>0?B0(f.slice(0,I+1)):void 0;if(E){a.push({kind:"filter",negated:p,key:E,value:f.slice(I+1).map((A)=>A.c).join(""),quoted:!1});continue}if(!p&&f.length===2&&f.every((A)=>!A.esc)&&f[0]?.c==="O"&&f[1]?.c==="R"){a.push({kind:"or"});continue}let S=f[f.length-1],R=f.length>1&&S!==void 0&&!S.esc&&S.c==="*",k=(R?f.slice(0,-1):f).map((A)=>A.c).join("");if(k)a.push({kind:"term",negated:p,term:G0("word",k,R)})}return a}var BG=/(^|\s)(-?)([A-Za-z]+)[:\uFF1A]("(?:[^"\\]|\\.)*"|\S+)(?=\s|$)/g;function K0(e){let o=[];return{rest:e.replace(BG,(u,m,p,f,h)=>{let I=f.toLowerCase();if(!z0.has(I))return u;let E=h.startsWith('"')&&h.length>=2;return o.push({key:I,value:E?h.slice(1,-1).replace(/\\(["\\])/g,"$1"):h,negated:p==="-",quoted:E}),m}).trim(),filters:o}}var H0={n:`
391
+ `,r:"\r",t:"\t",f:"\f",v:"\v","0":"\x00"};function GG(e){let o=[...e],a=0,u=(S)=>{let R=o.slice(a,a+S).join("");if(R.length!==S||!/^[0-9a-fA-F]+$/.test(R))return;return a+=S,String.fromCodePoint(Number.parseInt(R,16))},m=()=>{let S=o[a++];if(S===void 0)return{kind:"lit",ch:"\\"};if(S in H0)return{kind:"lit",ch:H0[S]};if("dDwWsS".includes(S))return{kind:"any"};if(S==="b"||S==="B")return{kind:"zero"};if(S>="1"&&S<="9"){while(o[a]!==void 0&&/\d/.test(o[a]))a++;return{kind:"any"}}if(S==="k"||S==="p"||S==="P"){let R=o[a];if(R==="<"||R==="{"){let k=R==="<"?">":"}",A=o.indexOf(k,a);a=A<0?o.length:A+1}return{kind:"any"}}if(S==="c")return a++,{kind:"any"};if(S==="x"){let R=u(2);return R===void 0?{kind:"lit",ch:"x"}:{kind:"lit",ch:R}}if(S==="u"){if(o[a]==="{"){let k=o.indexOf("}",a),A=k<0?"":o.slice(a+1,k).join("");if(/^[0-9a-fA-F]{1,6}$/.test(A)&&Number.parseInt(A,16)<=1114111)return a=k+1,{kind:"lit",ch:String.fromCodePoint(Number.parseInt(A,16))};return{kind:"lit",ch:"u"}}let R=u(4);return R===void 0?{kind:"lit",ch:"u"}:{kind:"lit",ch:R}}return{kind:"lit",ch:S}},p=()=>{if(o[a]==="^")a++;while(a<o.length&&o[a]!=="]")a+=o[a]==="\\"?2:1;return a++,{kind:"any"}},f=()=>{let S="capture";if(o[a]==="?"){let k=o[a+1],A=o[a+2];if(k===":")S="plain",a+=2;else if(k==="="||k==="!")S="look",a+=2;else if(k==="<"&&(A==="="||A==="!"))S="look",a+=3;else if(k==="<"){let P=o.indexOf(">",a);a=P<0?o.length:P+1}else{S="opaque";while(a<o.length&&o[a]!==":"&&o[a]!==")")a++;if(o[a]===":")a++}}let R=E();if(o[a]===")")a++;if(S==="look")return{kind:"zero"};return{kind:"group",alts:R,opaque:S==="opaque"}},h=()=>{let S=o[a],R=1,k=!0;if(S==="*"||S==="?")R=0,a++;else if(S==="+")a++;else if(S==="{"){let A=/^\{(\d+)(?:,(\d*))?\}/.exec(o.slice(a,a+24).join(""));if(!A)return{quantified:!1,min:1};R=Number(A[1]),a+=A[0].length}else return{quantified:!1,min:1};if(o[a]==="?")a++;return{quantified:k,min:R}},I=()=>{let S=[];while(a<o.length){let R=o[a];if(R==="|"||R===")")break;a++;let k;if(R==="(")k=f();else if(R==="[")k=p();else if(R==="\\")k=m();else if(R===".")k={kind:"any"};else if(R==="^"||R==="$")k={kind:"zero"};else if(R==="*"||R==="+"||R==="?")k={kind:"zero"};else k={kind:"lit",ch:R};S.push({atom:k,...h()})}return S};function E(){let S=[I()];while(o[a]==="|")a++,S.push(I());return S}return E()}function W0(e){let o=[],a="",u=()=>{if(a)o.push([a]);a=""},m=(p)=>{for(let f of p){let h=f.atom;if(h.kind==="lit")if(f.min>=1){if(a+=h.ch,f.quantified)u()}else u();else if(h.kind==="group"&&!h.opaque&&f.min>=1)if(h.alts.length===1&&!f.quantified)m(h.alts[0]);else u(),o.push(...J0(h.alts));else u()}};return m(e),u(),o}function J0(e){if(e.length===1)return W0(e[0]);let o=[];for(let a of e){let u=W0(a).filter((m)=>m.length===1).map((m)=>m[0]);if(!u.length)return[];o.push(u.reduce((m,p)=>Jc(p)>Jc(m)?p:m))}return[V0(o)]}var KG=/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;function HG(e){return!/^\s*$/.test(e)&&(Jc(e)>=2||KG.test(e))}function WG(e){let o;try{o=J0(GG(e))}catch{return[]}let a=o.filter((I)=>I.every(HG)),u=a.filter((I)=>I.length===1).map((I)=>I[0]),m=a.filter((I)=>{if(I.length!==1)return!0;let E=I[0];return!u.some((S)=>S!==E&&S.includes(E))}),p=new Set,f=m.filter((I)=>{let E=JSON.stringify(I);if(p.has(E))return!1;return p.add(E),!0}),h=(I)=>Math.min(...I.map(Jc));return f.sort((I,E)=>h(E)-h(I))}function zG(e){let o=e.replace(/\\[pPk]\{[^}]*\}|\\k<[^>]*>|\(\?<[^>]*>|\\u\{[0-9a-fA-F]+\}|\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}|\\c.|\\./gs,"");return/\p{Lu}/u.test(o)}function VG(e,o){let a=`m${o?"":"i"}`;try{return new RegExp(e,`${a}u`),{flags:`${a}u`}}catch{}try{return new RegExp(e,a),{flags:a}}catch(u){let m=u instanceof Error?u.message:String(u),p="\u8BF7\u68C0\u67E5\u62EC\u53F7\u3001\u8F6C\u4E49\u548C\u91CF\u8BCD";if(/unterminated.*class|missing.*\]/i.test(m))p="\u5B57\u7B26\u7EC4\u7F3A\u5C11\u53F3\u65B9\u62EC\u53F7";else if(/unterminated.*group|missing.*\)/i.test(m))p="\u5206\u7EC4\u7F3A\u5C11\u53F3\u62EC\u53F7";else if(/nothing to repeat|quantifier/i.test(m))p="\u91CF\u8BCD\u4F7F\u7528\u4E0D\u6B63\u786E";else if(/range/i.test(m))p="\u5B57\u7B26\u8303\u56F4\u4E0D\u6B63\u786E";return{message:`\u6B63\u5219\u8868\u8FBE\u5F0F\u65E0\u6548\uFF1A${p}`}}}function Nl(e,o={}){let a=o.now??Date.now(),u=e.q??"",m=FG(),p=m.diagnostics,f,h=[];if(e.mode==="regex"){let M=K0(u);for(let V of M.filters)sg(m,V.key,V.value,V.negated,V.quoted,a);f=M.rest}else{let M=K0(u),V=/^\/([\s\S]+)\/$/.exec(M.rest);if(V){for(let _ of M.filters)sg(m,_.key,_.value,_.negated,_.quoted,a);f=V[1]}else{h=[{include:[],exclude:[]}];for(let _ of UG(u,p)){let J=h[h.length-1];if(_.kind==="or")h.push({include:[],exclude:[]});else if(_.kind==="filter")sg(m,_.key,_.value,_.negated,_.quoted,a);else(_.negated?J.exclude:J.include).push(_.term)}h=h.filter((_)=>_.include.length||_.exclude.length)}}let I=h.flatMap((M)=>[...M.include,...M.exclude]),E=f!==void 0?zG(f):I.some((M)=>/\p{Lu}/u.test(M.text)),S=e.caseSensitive??E,R=e.caseSensitive===void 0&&E,k,A;if(f){let M=VG(f,S);if("message"in M)A={code:"bad_regex",message:M.message};else{let V=WG(f);k={source:f,flags:M.flags,literals:V,deepScan:V.length===0}}}let P=jG(e.filters,m);return{mode:f!==void 0?"regex":"text",branches:h,...k?{regex:k}:{},filters:P,currentSession:m.currentSession,caseSensitive:S,smartCase:R,wholeWord:e.wholeWord??!1,fuzzy:h.some((M)=>M.include.some((V)=>V.fuzzy)),hasPositive:k!==void 0||h.some((M)=>M.include.length>0),hasFilters:Object.keys(P).length>0||m.currentSession,...A?{error:A}:{},diagnostics:p}}var mg={title:8,user:5,assistant:3,error:3,tool_input:2,notice:2,extension:1,thinking:0.5,tool_output:0.5,attachment:0.5},Q0=new WeakMap;function X0(e){let o=e.query("PRAGMA data_version").get()?.data_version??0,a=Q0.get(e);if(a?.version===o)return a.terms;let u=e.query("SELECT t,n FROM term ORDER BY n DESC,t").all();return Q0.set(e,{version:o,terms:u}),u}var cg=32,JG=1024,Qc=(e)=>`"${e.replaceAll('"','""')}"`;function QG(e,o){let a=Array.from({length:o.length+1},(u,m)=>m);for(let u=0;u<e.length;u++){let m=[u+1];for(let p=0;p<o.length;p++)m.push(Math.min((m[p]??0)+1,(a[p+1]??0)+1,(a[p]??0)+Number(e[u]!==o[p])));a=m}return a[o.length]??e.length}function pg(e,o){let a=Mt(o.trim());if(!a||a.length>64)return[];let u=X0(e),m=u.filter((h)=>h.t.startsWith(a)).slice(0,8).map((h)=>h.t);if(m.length>=8||a.length<4)return m;let p=a.length>=8?2:1,f=[];for(let h of u){if(Math.abs(h.t.length-a.length)>p)continue;if(QG(a,h.t)<=p)f.push(h.t);if(f.length>=8)break}return[...new Set([...m,...f])].slice(0,8)}function Y0(e,o){let a=!1,u=[],m=[],p=o.filters,f=(V,_)=>{if(!_?.length)return;m.push(`${V} IN (${_.map(()=>"?").join(",")})`),u.push(..._)};if(f("s.project_id",p.projectID),p.sessionID?.length){m.push(`(${p.sessionID.map(()=>"(s.id = ? OR s.title = ?)").join(" OR ")})`);for(let V of p.sessionID)u.push(V,V)}if(p.archived!==void 0)m.push(`s.archived_at IS ${p.archived?"NOT ":""}NULL`);let h=m.length?m.join(" AND "):"1",I=[...u];if(f("r.kind",p.fields?.map((V)=>Fe[V])),f("r.tool",p.tools),p.model?.length){m.push(`(${p.model.map(()=>"substr(r.model,1,length(?)) = ?").join(" OR ")})`);for(let V of p.model)u.push(V,V)}if(p.isError!==void 0)m.push("r.err = ?"),u.push(Number(p.isError));if(p.compacted!==void 0)m.push(`(r.seq>0 AND r.seq<=COALESCE((
392
+ SELECT max(json_extract(body,'$.through')) FROM store.entries
393
+ WHERE session_id=r.session_id AND json_extract(body,'$.type')='compaction'
394
+ ),0)) = ?`),u.push(Number(p.compacted));if(p.after!==void 0)m.push("r.time >= ?"),u.push(p.after);if(p.before!==void 0)m.push("r.time < ?"),u.push(p.before);let E=e.query("SELECT v FROM meta WHERE k='layout'").get(),S=E&&JSON.parse(E.v).msg==="trigram",R=!o.hasPositive||Boolean(o.regex?.deepScan),k=(V)=>{let _=(X)=>{let te=Mt(X);if(!V&&S){if([...te].length<3){let Q=[...te].length===2?e.query("SELECT term FROM fts_vocab WHERE term >= ? AND term < ?").all(te,`${te}\uFFFF`):e.query("SELECT term FROM fts_vocab WHERE instr(term,?) > 0 LIMIT 33").all(te);if([...te].length===1&&Q.length>cg)Q.length=cg,a=!0;if(!Q.length)return Qc("__basalt_no_short_match__");return`(${Q.map((ee)=>Qc(ee.term)).join(" OR ")})`}return Qc(te)}let L=/^[\p{Script=Latin}\p{N}]+$/u.test(X)?[te]:ds(X),se=L.filter((Q)=>!/^[a-z0-9]{1,2}$/.test(Q)),he=se.length?se:L;if(!he.length){R=!0;return}let Me=he.map((Q,ee)=>{let be=/^[\u3040-\u30FF\u3400-\u9FFF\uF900-\uFAFF\uAC00-\uD7AF]{2}$/.test(Q),Xe=he.length>2&&ee>0&&ee<he.length-1;if(be||Xe){let Re=e.query("SELECT n FROM term WHERE t=?").get(Q)?.n??0;return{expression:Qc(Q),frequency:Re}}let Ge=[Q],sr=0;for(let Re of X0(e)){if(!Re.t.includes(Q))continue;if(sr+=Re.n,Re.t!==Q)Ge.push(Re.t);if(Ge.length>=cg){a=!0;break}}return{expression:`(${Ge.map(Qc).join(" OR ")})`,frequency:sr}});return Me.sort((Q,ee)=>Q.frequency-ee.frequency),`(${Me.slice(0,(Me[0]?.frequency??1/0)<=JG?1:2).map((Q)=>Q.expression).join(" AND ")})`},J=o.regex?o.regex.literals:o.branches.map((X)=>X.include.map((te)=>te.text));if(o.regex){let X=J.map((te)=>te.map(_));if(X.some((te)=>te.some((L)=>!L)))return;return X.map((te)=>`(${te.join(" OR ")})`).join(" AND ")||void 0}let j=J.map((X)=>{let te=X.filter((L)=>!/^[a-z0-9]{1,2}$/i.test(L));return(te.length?te:X).map(_)});if(j.some((X)=>!X.length||X.some((te)=>!te)))return;return j.map((X)=>`(${X.join(" AND ")})`).join(" OR ")||void 0},A=k(!1),P=k(!0),M=Boolean(e.query("SELECT 1 AS present FROM store.sessions WHERE forked_from_id IS NOT NULL LIMIT 1").get());return{msg:A,out:P,scan:R,where:m.length?m.join(" AND "):"1",bindings:u,forks:M,sessionWhere:h,sessionBindings:I,partial:a,candidateLimit:o.branches.some((V)=>V.include.length>0&&V.include.every((_)=>[..._.text].length<2))?512:void 0}}function Z0(e){let o=1/0,a=-1/0;for(let u of e)o=Math.min(o,u.relevance),a=Math.max(a,u.relevance);return e.map((u)=>({...u,relevance:o===a?-1:-(0.5+0.5*(a-u.relevance)/(a-o))}))}function ql(e){return`(-m.relevance) * (CASE r.kind ${Object.entries(mg).map(([a,u])=>`WHEN ${Fe[a]} THEN ${u}`).join(" ")} ELSE 1 END) *
395
+ (0.3 + 0.7 / (1 + max(0, ${e} - r.time) / 2592000000.0))`}function ev(e,o,a,u){let m=Math.max(0,u-a)/86400000;return Math.max(0.000000001,-e)*mg[o]*(0.3+0.7/(1+m/30))}function lg(e,o){return e.sort((a,u)=>(o==="best"?u.score-a.score:0)||(o==="recent"?u.time-a.time:0)||(a.sessionID<u.sessionID?-1:Number(a.sessionID>u.sessionID))||u.seq-a.seq||a.field.localeCompare(u.field))}var fg=512;function tv(e,o,a){let u=performance.now(),m=o.partial;hg(e,o),e.run("CREATE TEMP TABLE IF NOT EXISTS search_match (doc INTEGER PRIMARY KEY, relevance REAL NOT NULL)"),e.run("DELETE FROM temp.search_match");for(let[p,f]of[["fts",o.msg],["fts_out",o.out]]){if(!f)continue;let h=o.candidateLimit??2000,I=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
396
+ ORDER BY ${o.candidateLimit?"rowid DESC":"rank"} LIMIT ?`).all(f,o.candidateLimit?h+1:h);if(o.candidateLimit&&I.length>h)I.length=h,m=!0;else if(!o.candidateLimit&&I.length===h){let S=e.query(`SELECT rowid AS doc,rank AS relevance FROM ${p} WHERE ${p} MATCH ?
397
+ AND rowid NOT IN (SELECT value FROM json_each(?))`).all(f,JSON.stringify(I.map((R)=>R.doc)));for(let R of S)I.push(R)}let E=Z0(I);e.query(`INSERT INTO temp.search_match SELECT json_extract(value,'$.doc'),json_extract(value,'$.relevance')
398
+ FROM json_each(?) WHERE 1 ON CONFLICT(doc) DO UPDATE SET relevance=min(relevance,excluded.relevance)`).run(JSON.stringify(E))}return a?.("match",performance.now()-u),m}function rv(e,o,a,u,m){let p=performance.now();if(o.candidateLimit){let h=e.query(`
399
+ SELECT r.session_id,r.seq,${ql(u)} AS score
400
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
401
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
402
+ WHERE ${o.where} LIMIT ${o.candidateLimit+1}
403
+ `).all(...o.bindings);if(h.length>o.candidateLimit)h.length=o.candidateLimit,o.partial=!0;let I=new Map;for(let E of h){let S=a?E.seq:0,R=JSON.stringify([E.session_id,S]),k=I.get(R);if(!k||E.score>k.score)I.set(R,{...E,seq:S})}return m?.("filter",performance.now()-p),[...I.values()].sort((E,S)=>S.score-E.score||(E.session_id<S.session_id?-1:Number(E.session_id>S.session_id))||S.seq-E.seq)}let f=e.query(`
404
+ SELECT r.session_id,${a?"r.seq":"0"} AS seq,max(${ql(u)}) AS score
405
+ FROM temp.search_match m CROSS JOIN ref r ON r.doc=m.doc
406
+ ${o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
407
+ WHERE ${o.where}
408
+ GROUP BY r.session_id${a?",r.seq":""}
409
+ ORDER BY score DESC,r.session_id,seq DESC LIMIT ${o.candidateLimit?o.candidateLimit+1:-1}
410
+ `).all(...o.bindings);return m?.("filter",performance.now()-p),f}var nv=new WeakMap,XG=`WITH RECURSIVE lineage(child,ancestor,through) AS (
411
+ SELECT id,forked_from_id,forked_from_seq FROM store.sessions
412
+ WHERE forked_from_id IS NOT NULL AND forked_from_seq IS NOT NULL
413
+ UNION
414
+ SELECT l.child,s.forked_from_id,min(l.through,s.forked_from_seq)
415
+ FROM lineage l JOIN store.sessions s ON s.id=l.ancestor
416
+ WHERE s.forked_from_id IS NOT NULL AND s.forked_from_seq IS NOT NULL
417
+ )`;function hg(e,o){if(!o.forks)return;e.run("CREATE TEMP TABLE IF NOT EXISTS search_lineage (child TEXT,ancestor TEXT,through INTEGER,PRIMARY KEY(child,ancestor)) WITHOUT ROWID"),e.run("CREATE INDEX IF NOT EXISTS temp.search_lineage_ancestor ON search_lineage(ancestor)"),e.run("DELETE FROM temp.search_lineage"),e.run(`${XG} INSERT INTO temp.search_lineage SELECT child,ancestor,max(through) FROM lineage GROUP BY child,ancestor`);let a=e.query("SELECT ancestor,max(through) AS through FROM temp.search_lineage GROUP BY ancestor").all();nv.set(e,new Map(a.map((u)=>[u.ancestor,u.through])))}function dg(e){if(!e.forks)return"1";return`(s.forked_from_id IS NULL OR NOT EXISTS (
418
+ SELECT 1 FROM temp.search_lineage l CROSS JOIN ref pr ON pr.session_id=l.ancestor
419
+ JOIN store.sessions ps ON ps.id=pr.session_id
420
+ WHERE l.child=r.session_id AND r.seq<=l.through AND pr.seq=r.seq
421
+ AND pr.part=r.part AND pr.doc=r.doc AND ${e.where.replaceAll("r.","pr.").replaceAll("s.","ps.")}
422
+ AND ((r.seq=0 AND ps.title=s.title) OR EXISTS (
423
+ SELECT 1 FROM store.entries original JOIN store.entries copied
424
+ ON copied.session_id=r.session_id AND copied.seq=r.seq
425
+ WHERE original.session_id=pr.session_id AND original.seq=pr.seq AND original.body=copied.body
426
+ ))
427
+ ))`}function ov(e,o,a,u,m){let p=performance.now();e.run("CREATE TEMP TABLE IF NOT EXISTS search_window AS SELECT * FROM ref LIMIT 0"),e.run("DELETE FROM temp.search_window");let f=e.query("SELECT coalesce(sum(d.refs),0) AS n FROM temp.search_match m JOIN doc d ON d.id=m.doc").get()?.n??0,h=o.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":"";e.query(`
428
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${f>4000?"INDEXED BY ref_time":""}
429
+ ${h} WHERE r.doc IN (SELECT doc FROM temp.search_match) AND ${o.where} AND ${dg(o)}
430
+ ORDER BY r.time DESC,r.session_id DESC,r.seq DESC,r.part DESC LIMIT ${u} OFFSET ?`).run(...o.bindings,...o.forks?o.bindings:[],a);let I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0;if(I===u){let E=e.query("SELECT session_id,seq FROM temp.search_window ORDER BY time,session_id,seq,part LIMIT 1").get();if(E)e.query(`
431
+ INSERT INTO temp.search_window SELECT r.* FROM ref r ${h}
432
+ WHERE r.session_id=? AND r.seq=? AND r.doc IN (SELECT doc FROM temp.search_match)
433
+ AND ${o.where} AND ${dg(o)} AND NOT EXISTS (
434
+ SELECT 1 FROM temp.search_window w WHERE w.session_id=r.session_id AND w.seq=r.seq AND w.part=r.part
435
+ )`).run(E.session_id,E.seq,...o.bindings,...o.forks?o.bindings:[]),I=e.query("SELECT count(*) AS n FROM temp.search_window").get()?.n??0}return m?.("filter",performance.now()-p),I}function sv(e,o,a,u,m,p,f){let h=performance.now(),I=o.group==="none",E=o.sort==="recent"?"time DESC":"relevance DESC,time DESC",S=e.query(`
436
+ SELECT r.session_id,${I?"r.seq":"0"} AS seq,
437
+ max(${ql(m)}) AS relevance,max(r.time) AS time
438
+ FROM temp.search_window r JOIN temp.search_match m ON m.doc=r.doc
439
+ WHERE r.session_id NOT IN (SELECT value FROM json_each(?))
440
+ GROUP BY r.session_id${I?",r.seq":""}
441
+ ORDER BY ${E},r.session_id,r.seq DESC LIMIT ? OFFSET ?`).all(JSON.stringify(p),u,a);return f?.("group",performance.now()-h),S}function iv(e,o,a,u,m,p){let f=performance.now(),h=m?o:{...o,forks:!1},I=e.query(`
442
+ SELECT r.*,m.relevance FROM ref r JOIN temp.search_match m ON m.doc=r.doc
443
+ ${h.forks||o.where.includes("s.")?"JOIN store.sessions s ON s.id=r.session_id":""}
444
+ WHERE r.session_id=? ${u?"AND r.seq=?":""}
445
+ AND ${o.where} AND ${dg(h)}
446
+ ${o.candidateLimit?`ORDER BY r.time DESC,r.seq DESC,r.part LIMIT ${o.candidateLimit+1}`:""}`).all(a.session_id,...u?[a.seq]:[],...o.bindings,...h.forks?o.bindings:[]);return p?.("filter",performance.now()-f),I}function gg(e,o,a,u){if(!o.forks)return[];let m=nv.get(e)?.get(a.session_id);if(m===void 0||a.seq>m)return[];return e.query(`
447
+ SELECT DISTINCT r.session_id,s.title,e.body
448
+ FROM temp.search_lineage l INDEXED BY search_lineage_ancestor
449
+ CROSS JOIN ref r ON r.session_id=l.child
450
+ JOIN store.sessions s ON s.id=r.session_id
451
+ LEFT JOIN store.entries e ON e.session_id=r.session_id AND e.seq=r.seq
452
+ WHERE l.ancestor=? AND r.seq<=l.through AND r.doc=? AND r.seq=? AND r.part=? AND ${o.where} ORDER BY r.session_id`).all(a.session_id,a.doc,a.seq,a.part,...o.bindings).filter((p)=>{if(a.seq===0)return p.title===u;if(!p.body)return!1;let f=JSON.parse(p.body);return rt(f,!0).some((h)=>h.part===a.part&&h.kind===go[a.kind]&&h.text===u)}).map((p)=>p.session_id)}function YG(e,o){let a=o?e:Mt(e);if(a.length===e.length)return{normalized:a,starts:void 0,ends:void 0};let u="",m=[],p=[],f=0;for(let h of e){let I=o?h:Mt(h);u+=I;for(let E=0;E<I.length;E++)m.push(f),p.push(f+h.length);f+=h.length}return{normalized:u,starts:m,ends:p}}function Dl(e,o){if(o.regex){let I=new RegExp(o.regex.source,`${o.regex.flags}g`),E=[];for(let S of e.matchAll(I)){if(o.wholeWord&&!av(e,S.index,S.index+S[0].length))continue;E.push([S.index,S.index+S[0].length])}return E.length?E:void 0}let{normalized:a,starts:u,ends:m}=YG(e,o.caseSensitive),p=(I)=>{let E=o.caseSensitive?I.text:Mt(I.text),S=[],R=a.indexOf(E);while(R>=0&&E){let k=u?u[R]:R,A=m?m[R+E.length-1]:R+E.length,P=k===0||k!==void 0&&(!/[\p{L}\p{N}_]/u.test(e.slice(k-1,k))||/[a-z0-9][A-Z]/.test(e.slice(k-1,k+1))||/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}]/u.test(I.text));if(k!==void 0&&A!==void 0&&(!I.prefix||P)&&(!o.wholeWord||av(e,k,A)))S.push([k,A]);R=a.indexOf(E,R+Math.max(1,E.length))}return S};if(!o.branches.length)return[];let f=[],h=!1;for(let I of o.branches){if(I.exclude.some((S)=>p(S).length))continue;let E=I.include.map(p);if(E.some((S)=>!S.length))continue;h=!0,f.push(...E.flat())}return h?f:void 0}function av(e,o,a){let u=/[\p{L}\p{N}_]/u;return(o===0||!u.test(e.slice(o-1,o)))&&(a===e.length||!u.test(e.slice(a,a+1)))}function Fl(e,o){let a=e.split(`
453
+ `),u=new Set,m=0,p=a.map((f,h)=>{let I=m;if(o.some(([E,S])=>E<=I+f.length&&S>=I))for(let E=Math.max(0,h-1);E<=Math.min(a.length-1,h+1);E++)u.add(E);return m+=f.length+1,I});if(!u.size)u.add(0);return[...u].sort((f,h)=>f-h).slice(0,5).map((f)=>{let h=a[f]??"",I=p[f]??0,E=o.filter(([A,P])=>P>I&&A<I+h.length),S=Math.max(0,(E[0]?.[0]??I)-I-100),R=h.slice(S,S+300),k=E.map(([A,P])=>[Math.max(0,A-I-S),Math.min(R.length,P-I-S)]);return{text:R,line:f+1,ranges:k.filter(([A,P])=>A<P)}})}var uv=3;function ZG(e){return Boolean(e&&typeof e==="object"&&"score"in e&&typeof e.score==="number"&&Number.isFinite(e.score)&&"sessionID"in e&&typeof e.sessionID==="string"&&e.sessionID.length<=1024&&"seq"in e&&typeof e.seq==="number"&&Number.isSafeInteger(e.seq)&&e.seq>=0)}function cv(e,o){return o.score-e.score||(e.sessionID<o.sessionID?-1:Number(e.sessionID>o.sessionID))||o.seq-e.seq}function eK(e,o){if(!e)return{offset:0,key:o,now:Date.now(),window:0,seen:[],emitted:[]};try{let a=JSON.parse(Buffer.from(e,"base64url").toString());if(a&&typeof a==="object"&&"offset"in a&&"key"in a&&"now"in a&&a.key===o&&typeof a.offset==="number"&&Number.isSafeInteger(a.offset)&&a.offset>=0&&typeof a.now==="number"&&Number.isFinite(a.now)){let u="window"in a?a.window:0,m="seen"in a?a.seen:[],p="emitted"in a?a.emitted:[],f="after"in a?a.after:void 0;if(f!==void 0&&!ZG(f))throw Error("invalid best cursor");let h=(I)=>Array.isArray(I)&&I.every((E)=>typeof E==="string"&&E.length<=1024);if(typeof u==="number"&&Number.isSafeInteger(u)&&u>=0&&h(m)&&h(p))return{offset:a.offset,key:o,now:a.now,window:u,seen:m,emitted:p,after:f}}}catch{}throw Error("invalid search cursor")}function un(e,o){let a=Bun.hash(JSON.stringify({request:{...e,cursor:void 0},sessionID:o})).toString();return eK(e.cursor,a)}async function vr(e,o,a){let u="search"in e?e.search:e,m=performance.now(),p=(Re)=>{if(!a.signal?.aborted)a.onEvent(Re)};if(a.signal?.aborted)return;let f=un(o,a.sessionID);if(o.filters?.sessionID?.length===1)o={...o,group:"none"};let h=Nl(o,{now:f.now});if(h.error){p({type:"error",...h.error});return}if(h.currentSession){if(!a.sessionID){p({type:"error",code:"too_broad",message:"\u5F53\u524D\u4F1A\u8BDD\u641C\u7D22\u9700\u8981 sessionID"});return}h.filters.sessionID=[a.sessionID]}if(!o.deep&&h.regex?.deepScan){p({type:"error",code:"too_broad",message:"\u8BF7\u6DFB\u52A0\u8FC7\u6EE4\u6761\u4EF6\u6216\u542F\u7528 deep \u641C\u7D22"});return}if(await Bun.sleep(0),a.signal?.aborted)return;let I=performance.now(),E=u.withIndex((Re)=>Y0(Re,h));if(!E){p({type:"error",code:"unavailable",message:u.status().state==="disabled"?"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528":"\u641C\u7D22\u7D22\u5F15\u5C1A\u672A\u5C31\u7EEA\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"});return}a.onTiming?.("plan",performance.now()-I);let S=E.partial,R=f.after,k=new Map,A=new Map,P=[],M=!1,V=new Map,_=new WeakMap,J=new Map,j=new Map,{offset:X,window:te}=f,L=[...f.seen],se=[...f.emitted],he=!1,Me=Math.max(1,Math.min(200,o.limit??30)),We=Math.min(E.candidateLimit??2000,o.group==="none"?fg:Math.min(2000,Math.max(fg,Me*32))),Q=(Re,ke)=>{let Wt=k.get(ke);if(Wt)return Wt;let ft=Re.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions WHERE id=?").get(ke);if(ft)k.set(ke,ft);return ft??void 0},ee=(Re,ke,Wt)=>{if(a.allowedSessionIDs&&!a.allowedSessionIDs.has(ke.session_id))return;if(a.excludeEntry?.sessionID===ke.session_id&&a.excludeEntry.seq===ke.seq)return;let ft=Q(Re,ke.session_id);if(!ft)return;let Nt=go[ke.kind];if(!Nt)return;let gr=ft.title;if(ke.seq!==0){let it=`${ke.session_id}:${ke.seq}`,ir=j.get(it);if(!ir){let rn=Wt?void 0:Re.query("SELECT body FROM store.entries WHERE session_id=? AND seq=?").get(ke.session_id,ke.seq);if(!Wt&&!rn)return;let rr=Wt??JSON.parse(rn?.body??"null");ir=rt(rr,!0),j.set(it,ir)}let cr=ir.find((rn)=>rn.part===ke.part&&rn.kind===Nt);if(!cr)return;gr=cr.text}let lr=Dl(gr,h);if(!lr)return;let Zt=A.get(ft.id);if(Zt===void 0)Zt=Re.query("SELECT COALESCE(MAX(json_extract(body,'$.through')),0) AS through FROM store.entries WHERE session_id=? AND instr(body,'compaction')>0 AND json_extract(body,'$.type')='compaction'").get(ft.id)?.through??0,A.set(ft.id,Zt);let ot=ke.seq>0&&ke.seq<=Zt;if(h.filters.compacted!==void 0&&ot!==h.filters.compacted)return;let Ot={sessionID:ft.id,seq:ke.seq,time:ke.time,field:Nt,tool:ke.tool??void 0,isError:Boolean(ke.err),model:ke.model??void 0,snippet:[],score:ev(ke.relevance,Nt,ke.time,f.now),flags:{archived:ft.archived_at!==null,compacted:ot,partial:gr.length>ls+cs}};return V.set(Ot,{text:gr,ranges:lr}),P.push(Ot),M=!0,J.set(Ot,{doc:ke.doc,part:ke.part}),Ot},be=(Re)=>{let ke=performance.now(),Wt=[...Re].sort((ot,Ot)=>ot.time-Ot.time||ot.sessionID.localeCompare(Ot.sessionID)),ft=[],Nt=new Map;for(let ot of Wt){let Ot=J.get(ot),ir=k.get(ot.sessionID),cr=new Set;while(ir?.forked_from_id&&ir.forked_from_seq!==null&&ot.seq<=ir.forked_from_seq&&!cr.has(ir.id))cr.add(ir.id),ir=k.get(ir.forked_from_id)??u.withIndex((No)=>Q(No,ir?.forked_from_id??""));let rn=`${ir?.id??ot.sessionID}:${ot.seq}:${Ot?.part}:${Ot?.doc}`,rr=Nt.get(rn);if(rr){if(rr.sessionID!==ot.sessionID)rr.forks=[...new Set([...rr.forks??[],ot.sessionID])]}else Nt.set(rn,ot),ft.push(ot)}let gr=[],lr=new Map,Zt=new Map;for(let ot of ft){let Ot=`${ot.sessionID}:${ot.seq}`,it=Zt.get(Ot);if(!it){Zt.set(Ot,ot),_.set(ot,[ot]);continue}let ir=[..._.get(it)??[it],ot],cr=ot.score>it.score?ot:it;if(cr.forks=[...new Set([...it.forks??[],...ot.forks??[]])],!cr.forks.length)cr.forks=void 0;cr.flags={archived:it.flags.archived||ot.flags.archived,compacted:it.flags.compacted||ot.flags.compacted,partial:it.flags.partial||ot.flags.partial},Zt.set(Ot,cr),_.set(cr,ir)}for(let ot of lg([...Zt.values()],o.sort??"best")){let Ot=k.get(ot.sessionID);if(!Ot)continue;let it=o.group==="none"?void 0:lr.get(Ot.id);if(!it)it={session:{id:Ot.id,title:Ot.title,projectID:Ot.project_id,updated:Ot.updated},hits:[],more:0,...S&&o.group!=="none"?{moreIsLowerBound:!0}:{}},gr.push(it),lr.set(Ot.id,it);if(it.hits.length<uv||o.group==="none")it.hits.push(ot);else it.more++}return a.onTiming?.("group",performance.now()-ke),gr},Xe=(Re)=>{for(let ke of Re)for(let Wt of ke.hits){if(a.allowedSessionIDs&&Wt.forks)Wt.forks=Wt.forks.filter((gr)=>a.allowedSessionIDs?.has(gr));let ft=performance.now(),Nt=new Map;for(let gr of _.get(Wt)??[Wt]){let lr=V.get(gr);if(!lr)continue;for(let Zt of Fl(lr.text,lr.ranges)){let ot=`${Zt.line}:${Zt.text}`,Ot=Nt.get(ot);if(!Ot)Nt.set(ot,Zt);else Ot.ranges=[...new Map([...Ot.ranges,...Zt.ranges].map((it)=>[it.join(":"),it])).values()]}}Wt.snippet=[...Nt.values()],a.onTiming?.("snippet",performance.now()-ft)}},Ge=o.deep||E.scan,sr=(Re,ke)=>{let Wt=Q(Re,ke.session_id);if(!Wt)return[];let ft=iv(Re,E,ke,o.group==="none",Wt.forked_from_id!==null,a.onTiming);if(E.candidateLimit&&ft.length>E.candidateLimit)ft.length=E.candidateLimit,S=!0;let Nt=P.length,gr=performance.now();for(let lr of ft){if(a.signal?.aborted)break;let Zt=ee(Re,lr);if(!Zt)continue;let ot=gg(Re,E,lr,V.get(Zt)?.text??"");if(ot.length)Zt.forks=ot}return a.onTiming?.("body",performance.now()-gr),P.slice(Nt)};if(Ge){S=!1;let Re=[],ke=new Set,Wt=u.withIndex((it)=>{hg(it,E);for(let rr of it.query("SELECT id,title,project_id,updated,archived_at,forked_from_id,forked_from_seq FROM store.sessions ORDER BY id").all())k.set(rr.id,rr);let ir=new Set(it.query(`SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}`).all(...E.sessionBindings).map((rr)=>rr.id)),cr=(rr)=>{if(ke.has(rr.id))return;ke.add(rr.id);let No=rr.forked_from_id?k.get(rr.forked_from_id):void 0;if(No)cr(No);if(ir.has(rr.id))Re.push(rr)};for(let rr of k.values())cr(rr);return(it.query(`SELECT count(*) AS n FROM store.entries WHERE session_id IN (
454
+ SELECT s.id FROM store.sessions s WHERE ${E.sessionWhere}
455
+ )`).get(...E.sessionBindings)?.n??0)+ir.size})??0,ft=0,Nt=0,gr=0;if(h.regex?.deepScan)p({type:"groups",groups:[]});let lr=new Set,Zt=new Set,ot=new Map,Ot=()=>{let it=be(P),ir=[];for(let cr of it){let rn=cr.session.id,rr=o.group==="none"?void 0:ot.get(rn);if(o.group!=="none"&&Zt.has(rn)&&!rr)continue;if(!rr){if(Zt.add(rn),Nt<f.offset){Nt++;continue}if(gr>=Me){he=!0;break}gr++,X++}if(o.group!=="none"){let No=(rr?.count??0)+cr.hits.length+cr.more;cr.hits=cr.hits.slice(0,uv-(rr?.shown??0));let wu=(rr?.shown??0)+cr.hits.length;cr.more=No-wu,ot.set(rn,{shown:wu,count:No})}ir.push(cr)}if(ir.length)Xe(ir),p({type:"groups",groups:ir});P.length=0,V.clear(),J.clear(),j.clear()};for(let it of Re){if(a.signal?.aborted||he)break;let ir=-1,cr;for(;;){if(a.signal?.aborted||he)break;let rn=u.withIndex((rr)=>{let No=rr.query("SELECT seq,time,body FROM store.entries WHERE session_id=? AND seq>? ORDER BY seq LIMIT 128").all(it.id,Math.max(0,ir));if(ir<0)No.unshift({seq:0,time:it.updated,body:null});for(let Qi of No){if(a.signal?.aborted)break;let Tu=Qi.body?JSON.parse(Qi.body):void 0;if(Tu?.type==="assistant")cr=Tu.model;let lv=Tu?rt(Tu,!0):[{part:0,kind:"title",text:it.title}];for(let Ho of lv){if(a.signal?.aborted)break;let Js={session_id:it.id,seq:Qi.seq,part:Ho.part,doc:Number(BigInt(Bun.hash(Ho.text))&0x1fffffffffffffn),kind:Fe[Ho.kind],tool:Ho.tool??null,err:Number(Ho.err??!1),model:Ho.model??(Ho.tool?cr:void 0)??null,time:Qi.time,relevance:-1};if(!rr.query(`SELECT 1 AS ok FROM (SELECT ? AS session_id,? AS seq,? AS kind,? AS tool,? AS err,? AS model,? AS time) r
456
+ JOIN store.sessions s ON s.id=r.session_id WHERE ${E.where}`).get(Js.session_id,Js.seq,Js.kind,Js.tool,Js.err,Js.model,Js.time,...E.bindings))continue;let yi=it,Ig=new Set;while(yi.forked_from_id&&yi.forked_from_seq!==null&&Qi.seq<=yi.forked_from_seq&&!Ig.has(yi.id)){Ig.add(yi.id);let Ru=k.get(yi.forked_from_id);if(!Ru)break;yi=Ru}let Eg=`${yi.id}:${Qi.seq}:${Ho.part}:${Bun.hash(Ho.text)}`;if(lr.has(Eg))continue;let bg=ee(rr,Js,Tu);if(bg){if(lr.add(Eg),E.forks){let Ru=rr.query("SELECT doc FROM ref WHERE session_id=? AND seq=? AND part=?").get(it.id,Qi.seq,Ho.part);if(Ru){let Sg=gg(rr,E,{...Js,doc:Ru.doc},Ho.text);if(Sg.length)bg.forks=Sg}}}}}let wu=No.at(-1);if(wu)ir=wu.seq;return No.length});if(rn===void 0){p({type:"error",code:"unavailable",message:"\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528"});return}if(ft+=rn,p({type:"progress",scanned:ft,total:Wt}),a.signal?.aborted)return;if(Ot(),!rn||he)break;await Bun.sleep(0)}}}else u.withIndex((Re)=>{if(S=tv(Re,E,a.onTiming)||S,h.regex?h.regex.literals.every((ft)=>ft.some((Nt)=>[...Nt].length<3)):h.branches.some((ft)=>ft.include.length>0&&ft.include.every((Nt)=>[...Nt.text].length<3)))Re.run("INSERT OR IGNORE INTO temp.search_match SELECT id,-1 FROM doc WHERE len<3");if(o.sort!=="recent"){let ft=rv(Re,E,o.group==="none",f.now,a.onTiming);if(S||=E.partial,E.candidateLimit&&ft.length>E.candidateLimit)ft.length=E.candidateLimit,S=!0;let Nt=[];for(let lr of ft){if(a.signal?.aborted)return;let Zt=Nt[Me]?.key.score;if(Zt!==void 0&&lr.score+0.000000000001<Zt)break;let ot=P.length,Ot=sr(Re,lr);P.splice(ot);let it=lg([...Ot],"best")[0];if(!it)continue;let ir={score:it.score,sessionID:it.sessionID,seq:o.group==="none"?it.seq:0};if(f.after&&cv(ir,f.after)<=0)continue;if(Nt.push({key:ir,hits:Ot}),Nt.sort((cr,rn)=>cv(cr.key,rn.key)),Nt.length>Me+1)Nt.length=Me+1}he=Nt.length>Me;let gr=Nt.slice(0,Me);for(let lr of gr)P.push(...lr.hits);R=gr.at(-1)?.key;return}let Wt=0;for(;;){if(a.signal?.aborted)return;let ft=ov(Re,E,te,We,a.onTiming),Nt=E.candidateLimit!==void 0&&te+ft>=E.candidateLimit;S||=Nt;let gr=sv(Re,o,X,Me-Wt+1,f.now,L,a.onTiming);he=gr.length>Me-Wt;let lr=gr.slice(0,Me-Wt);if(!lr.length){if(ft<We||Nt){he=!1;break}te+=ft,X=0,L=[...new Set([...L,...se])],se=[];continue}for(let Zt of lr)if(X++,sr(Re,Zt).length){if(Wt++,o.group!=="none")se.push(Zt.session_id)}if(Wt>=Me){he||=!Nt&&ft>=We;break}if(!he){if(ft<We||Nt)break;te+=ft,X=0,L=[...new Set([...L,...se])],se=[]}}});if(a.signal?.aborted)return;if(!Ge){let Re=be(P);Xe(Re),p({type:"groups",groups:Re})}if(!M){let Re=h.branches.flatMap((ke)=>ke.include).find((ke)=>ke.fuzzy)?.text;if(Re)p({type:"suggest",terms:u.withIndex((ke)=>pg(ke,Re))??[]})}p({type:"done",cursor:he?Buffer.from(JSON.stringify(!Ge&&o.sort!=="recent"?{...f,offset:0,window:0,seen:[],emitted:[],after:R}:{...f,offset:X,window:te,seen:L,emitted:se})).toString("base64url"):void 0,tookMs:performance.now()-m,partial:S,index:u.status()})}function to(e,o){return e.withIndex((a)=>pg(a,o))??[]}function mv(e,o,a){let u=T({name:"database_search",label:"Search database history",description:'Search history with {query:"words"}. Only query is needed; omit other parameters unless needed, never fill empty strings or 0. Query always takes priority. Read a hit with {session,seq} (seq >= 1, around defaults to 3). Scope defaults to project, or all without a project. Use history_grep/history_list for folded current-conversation references.',parameters:l({query:n(g([s({maxLength:2000}),Nn()])),scope:n(g([i("session"),i("project"),i("all"),i(""),Nn()])),fields:n(g([F(Sr({type:"string",enum:[...yn]})),Nn()])),tool:n(g([s(),Nn()])),isError:n(g([N(),Nn()])),after:n(g([s(),re(),Nn()])),before:n(g([s(),re(),Nn()])),limit:n(g([x(),Nn()])),session:n(g([s(),Nn()])),seq:n(g([x(),Nn()])),around:n(g([x(),Nn()]))}),async execute(m,p,f){let h={query:p.query?.trim(),scope:p.scope||void 0,fields:p.fields?.length?p.fields:void 0,tool:p.tool?.trim(),isError:p.isError??void 0,after:p.after??void 0,before:p.before??void 0,limit:p.limit||void 0,session:p.session?.trim(),seq:p.seq??void 0,around:p.around??void 0},I=h.query?.trim(),E=!I&&Boolean(h.session?.trim())&&Number.isSafeInteger(h.seq)&&(h.seq??0)>=1;if(E&&h.around!==void 0&&(!Number.isInteger(h.around)||h.around<0||h.around>10))throw Error("around must be 0\u201310; remove around to read the default context");if(h.scope&&!["session","project","all"].includes(h.scope))throw Error("scope must be session, project or all; remove scope to use the default");if(f?.aborted)throw Error("History search cancelled");let S=e.sessions().find((Q)=>Q.id===a);if(!S)throw Error("History session is unavailable");let R=(Q)=>{if(Q===void 0||Q===0||typeof Q==="string"&&!Q.trim())return;if(typeof Q==="string"&&!/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(Q))throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp");let ee=typeof Q==="number"?Q:Date.parse(Q);if(!Number.isFinite(ee)||Math.abs(ee)>8640000000000000){if(typeof Q==="number")return;throw Error("Remove invalid after/before, or use an ISO date such as 2026-01-01 or a millisecond timestamp")}return ee},k=E?void 0:R(h.after),A=E?void 0:R(h.before);if(k!==void 0&&A!==void 0&&k>=A)throw Error("after must precede before");let P=[];if(E&&h.session&&h.seq!==void 0){if(!e.sessions().find((Ge)=>Ge.id===h.session))throw Error("History source is unavailable; remove session/seq/around and search with query to find a valid reference");let ee=h.around??3,be=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq BETWEEN ? AND ? ORDER BY seq").all(h.session,Math.max(1,h.seq-ee),h.seq+ee);if(!be.some((Ge)=>Ge.seq===h.seq))throw Error("No history entry at seq; remove session/seq/around and search with query for a valid entry");return{content:[{type:"text",text:be.map((Ge)=>{let sr={...JSON.parse(Ge.body),seq:Ge.seq,time:Ge.time};return`[seq=${Ge.seq}]
457
+ ${rt(sr,!0).map((Re)=>`${Re.kind}: ${Re.kind==="error"?Re.text.replace(/^(?:error:\s*)+/i,""):Re.text}`).join(`
458
+ `).slice(0,4000)}`}).join(`
459
+
460
+ `)||"No history content"}],details:{groups:P,count:be.length}}}if(!I)throw Error("Provide a non-empty query to search; remove session/seq/around. To read, provide both session and integer seq >= 1.");let M=Number.isFinite(h.limit)?Math.max(1,Math.min(30,Math.trunc(h.limit??10))):10,V=e.db.query("SELECT seq FROM entries WHERE session_id=? AND json_extract(body,'$.type')='user' ORDER BY seq DESC LIMIT 1").get(a)?.seq,_=new Set(e.sessions().filter((Q)=>{if(h.scope==="session")return Q.id===a;if((h.scope??"project")==="project"&&S.projectID)return Q.projectID===S.projectID;return!0}).map((Q)=>Q.id)),J={q:I,filters:{tools:h.tool?.trim()?[h.tool.trim()]:void 0,isError:h.isError,after:k,before:A},group:"none",limit:M},j=Nl(J);if(j.error)throw Error(j.error.message);if(h.fields?.length){if(j.filters.fields=h.fields.filter((Q)=>(Q in Fe)),j.filters.fields.length!==h.fields.length)throw Error("Unknown search field")}if((h.scope??"project")==="session")j.filters.sessionID=[a];else if((h.scope??"project")==="project"&&S.projectID)j.filters.projectID=[S.projectID];let X=o.status().state!=="ready",te=!1;if(!X){let Q=j.filters.fields??Object.keys(Fe).filter((Xe)=>(Xe in Fe)),ee=Q.filter((Xe)=>Xe!=="title"),be=ee.length?[ee]:[];if(Q.includes("title"))be.push(["title"]);for(let Xe of be){if(P.length>=M&&te)break;if(await vr(o,{...J,limit:Math.max(1,M-P.length),filters:{...j.filters,fields:Xe}},{signal:f,excludeEntry:V===void 0?void 0:{sessionID:a,seq:V},sessionID:a,allowedSessionIDs:_,onEvent(Ge){if(Ge.type==="groups")P.push(...Ge.groups);if(Ge.type==="done")te||=Boolean(Ge.cursor)||Ge.partial;if(Ge.type==="error")if(Ge.code==="unavailable")X=!0;else throw Error(Ge.message)}}),X)break}}let L=[],se=0;if(X){P.length=0;let Q=performance.now()+2000;e:for(let ee of e.sessions()){if(!_.has(ee.id))continue;if(j.filters.sessionID&&!j.filters.sessionID.includes(ee.id))continue;if(j.filters.projectID&&(!ee.projectID||!j.filters.projectID.includes(ee.projectID)))continue;let be=Number.MAX_SAFE_INTEGER,Xe=!0;for(;;){let Ge=e.db.query("SELECT body,seq,time FROM entries WHERE session_id=? AND seq<? ORDER BY seq DESC LIMIT 128").all(ee.id,be);if(Xe)Ge.push({body:"null",seq:0,time:ee.updated}),Xe=!1;if(!Ge.length)break;for(let sr of Ge){if(sr.seq>0)be=sr.seq;if(f?.aborted)throw Error("History search cancelled");if(se>=1e4||performance.now()>Q){te=!0;break e}if(se++,ee.id===a&&sr.seq===V)continue;if(j.filters.after!==void 0&&sr.time<j.filters.after||j.filters.before!==void 0&&sr.time>=j.filters.before)continue;let Re=sr.seq===0?[{part:0,kind:"title",text:ee.title,tool:void 0,err:!1}]:rt(JSON.parse(sr.body),!0);for(let ke of Re){if(j.filters.fields&&!j.filters.fields.includes(ke.kind))continue;if(j.filters.tools&&(!ke.tool||!j.filters.tools.includes(ke.tool)))continue;if(j.filters.isError!==void 0&&Boolean(ke.err)!==j.filters.isError)continue;let Wt=Dl(ke.text,j);if(!Wt)continue;if(P.length>=M&&ke.kind!=="title"){te=!0;break e}(ke.kind==="title"?L:P).push({session:{id:ee.id,title:ee.title,projectID:ee.projectID,updated:ee.updated},more:0,hits:[{sessionID:ee.id,seq:sr.seq,time:sr.time,field:ke.kind,tool:ke.tool,isError:Boolean(ke.err),snippet:Fl(ke.text,Wt),score:0,flags:{archived:!1,compacted:!1,partial:!1}}]})}}await Bun.sleep(0)}}}if(f?.aborted)throw Error("History search cancelled");if(L.length>Math.max(0,M-P.length))te=!0;if(P.push(...L.slice(0,M)),P.sort((Q,ee)=>Number(Q.hits[0]?.field==="title")-Number(ee.hits[0]?.field==="title")),P.length>M)te=!0;P.length=Math.min(P.length,M);let he=new Map;for(let Q of P)for(let ee of Q.hits){let be=he.get(Q.session.id)??[];be.push(`[${Q.session.title.replace(/[\r\n]/g," ")} \xB7 ${ee.sessionID} \xB7 ${ee.seq} \xB7 ${new Date(ee.time).toISOString()} \xB7 ${ee.field}${ee.tool?`/${ee.tool}`:""}]
461
+ ${ee.snippet.slice(0,3).map((Xe)=>{let Ge=Xe.text;for(let[sr,Re]of[...Xe.ranges].sort((ke,Wt)=>Wt[0]-ke[0]))Ge=`${Ge.slice(0,sr)}\u3010${Ge.slice(sr,Re)}\u3011${Ge.slice(Re)}`;return Ge}).join(`
462
+ `)}`),he.set(Q.session.id,be)}let Me="";if(X){if(Me="\u7D22\u5F15\u5EFA\u7ACB\u4E2D\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168",o.status().state==="disabled")Me="\u5386\u53F2\u641C\u7D22\u672A\u542F\u7528\uFF08\u53BB \u8BBE\u7F6E \u2192 \u5386\u53F2\u641C\u7D22 \u5F00\u542F\uFF09\uFF1B\u7D22\u5F15\u672A\u5C31\u7EEA\uFF0C\u7ED3\u679C\u53EF\u80FD\u4E0D\u5168"}let We=P.reduce((Q,ee)=>Q+ee.hits.length,0);return{content:[{type:"text",text:[Me,X&&te?`\u53EA\u626B\u63CF\u4E86\u6700\u8FD1\u7684 ${se} \u6761`:"",[...he.values()].map((Q)=>Q.join(`
463
+
464
+ `)).join(`
465
+
466
+ `),We===0?"\u6CA1\u6709\u5339\u914D\uFF0C\u8BF7\u6362\u7528\u66F4\u77ED\u7684\u5173\u952E\u8BCD\u3001\u540C\u4E49\u8BCD\uFF0C\u6216\u51CF\u5C11\u8FC7\u6EE4\u6761\u4EF6\u3002":"",`\u5171\u8FD4\u56DE ${We} \u6761\uFF1B${te?"\u8FD8\u6709\u66F4\u591A\uFF0C\u8BF7\u6536\u7A84\u65F6\u95F4\u3001\u5B57\u6BB5\u6216\u67E5\u8BE2\u6761\u4EF6":"\u6CA1\u6709\u66F4\u591A\u5339\u914D"}`].filter(Boolean).join(`
467
+ `)}],details:{groups:P,count:We}}}});return Object.assign(u,{source:"history",builtin:!0,defer:"defer"})}var yg="basalt.git-snapshot";async function pv(e,o,a){let u=o.projectID?e.store.project(o.projectID):void 0,m=u?.directory??process.cwd(),f=o.info().kind==="sub",h=()=>f||o.entries(0,["compaction"],!1).length>0,I=e.options.tools??Vt({directory:u?.directory,records:()=>o.records,history:(R)=>e.resolveHistory(o.id,R),onTodos:(R)=>o.setTodos(R),shell:()=>e.serverShell(),hasCompacted:h});if(e.options.tools===void 0)I.push(mv(e.store,e.search,o.id));let E;if(u&&e.options.systemPrompt===void 0){let R=o.entries(0,["compaction"],!1).length,k=e.store.db,A=k.query("SELECT value FROM plugin_kv WHERE namespace = ? AND key = ?").get(yg,o.id),P;try{P=A?JSON.parse(A.value):void 0}catch{P=void 0}if(P?.compactions===R&&(P.summary===void 0||typeof P.summary==="string"))E=P.summary;else if(E=await u0(u.directory,a),!e.isClosed&&!a?.aborted)k.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES (?, ?, ?)").run(yg,o.id,JSON.stringify({compactions:R,summary:E})),k.query("DELETE FROM plugin_kv WHERE namespace = ? AND key NOT IN (SELECT id FROM sessions)").run(yg)}let S=e.options.systemPrompt!==void 0?[{label:"\u7CFB\u7EDF\u63D0\u793A\u8BCD",detail:e.options.systemPrompt}]:a0({project:u,globalInstructions:sK(e),git:E,shell:e.serverShell()});return{systemPrompt:S.map((R)=>R.detail).join(""),systemParts:S,tools:[...I,...e.tools.snapshot()],cwd:m}}var oK=[Su(".basalt","AGENTS.md"),Su(".agents","AGENTS.md"),Su(".opencode","AGENTS.md"),Su(".claude","CLAUDE.md"),Su(".codex","AGENTS.md")];function sK(e){let o=e.options.homeDir??nK();for(let a of oK){let u=Su(o,a);try{if(tK(u))return rK(u,"utf8")}catch{return}}return}class Qo{options;http;connections=new Map;tools;plugins;initialization;initialized=!1;restored=new Set;store;search;sessions=new Map;listeners=new Set;projectOperations;defaultModel;closed=!1;closing;constructor(e){this.options=e;this.projectOperations=new ng(this,this.sessions,(o)=>this.emit(o)),this.defaultModel=e.defaultModel,this.store=new Ol(xg(e.dataDir,"basalt.db")),this.plugins=new Nh(this,e.plugins),this.store.plugins=this.plugins,this.tools=new Ll(this.plugins,()=>this.builtinToolNames()),this.search=new qh({dataDir:e.dataDir,store:this.store,enabled:e.search?.enabled??!0,onStatus:(o)=>this.emit({type:"search_status",status:o})});for(let o of this.store.allSessions()){let a=this.open(o,"restore");this.sessions.set(o.id,a),this.restored.add(a)}}static async create(e){let o=new Qo(e);try{return await o.initialize(),o}catch(a){throw await o.close(),a}}initialize(){return this.initialization??=this.plugins.discover(this.options.plugins?.directories??[xg(this.options.dataDir,"plugins"),...this.projects().map((e)=>xg(e.directory,".basalt","plugins"))],this.options.plugins?.builtins===!1?[]:this.options.builtinPlugins??[]).then(async()=>{for(let e of this.restored)this.plugins.notify("session.open",e);if(this.initialized=!0,await this.plugins.idle(),!this.closed)for(let e of this.restored)e.recover();this.restored.clear()}),this.initialization}get ready(){return this.initialize()}builtinToolNames(){if(this.options.tools)return this.options.tools.map((e)=>e.name);return["read","write","edit","grep","glob","bash","todo","history_grep","history_list"]}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}models(){return F0(this,this.defaultModel)}async idle(){while(!0){let e=[...this.sessions.values()];await Promise.all(e.map((u)=>u.idle())),await this.plugins.idle(),await this.plugins.invokeIdle();let o=[...this.sessions.values()];if(await Promise.all(o.map((u)=>u.noticesIdle())),o.some((u)=>u.status==="busy"||!e.includes(u)))continue;return}}get isClosed(){return this.closed}close(){if(this.closing)return this.closing;this.closed=!0;for(let e of this.sessions.values())e.suspend();return this.closing=(async()=>{if(this.initialization)await Promise.allSettled([this.initialization]);await this.idle(),await this.plugins.close(),await this.search.close(),this.store.close()})(),this.closing}storage(){return{..._l(this.store,this.options.dataDir),search:this.search.status()}}compactStorage(e){return this.search.pause(()=>q0(this.store,this.options.dataDir,e))}searchStatus(){return this.search.status()}async setSearchEnabled(e){return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.search', 'enabled', ?)").run(e?"true":"false"),await this.search.setEnabled(e),this.search.status()}projects(){return this.store.projects()}project(e){return this.store.project(e)}createProject(e){return this.projectOperations.createProject(e)}updateProject(e,o){return this.projectOperations.updateProject(e,o)}reorderProjects(e){this.projectOperations.reorderProjects(e)}deleteProject(e){return this.projectOperations.deleteProject(e)}list(e=!1,o={}){return[...this.sessions.values()].filter((a)=>e||a.info().parentID===null).map((a)=>a.info()).filter((a)=>{let u=o.archive??"active";return u==="all"||a.archivedAt!==null===(u==="archived")}).sort((a,u)=>u.updated-a.updated)}get(e){return this.sessions.get(e)}children(e){return[...this.sessions.values()].filter((o)=>o.info().parentID===e).map((o)=>o.info())}resolveHistory(e,o){let a=this.get(e);if(!a)throw new t("History session is unavailable");return a.resolveHistory(o)}openStoredSession(e,o="restore"){let a=this.open(e,o);return this.sessions.set(e.id,a),this.emit({type:"session",session:a.info()}),a}create(e={}){let o=e.model??this.defaultModel;if(!kn(this.options.models,o))throw new t(`unknown model ${o}`);if(e.projectID)this.projectOperations.requireProject(e.projectID);let a=Date.now(),u={id:ne("s"),title:e.title?.trim()??"",projectID:e.projectID??null,metadata:e.metadata,model:o,thinking:e.thinking?.trim()?e.thinking.trim():null,todos:[],created:a,updated:a,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSession(u);let m=this.open(u);return this.sessions.set(u.id,m),this.emit({type:"session",session:m.info()}),m}copyHistory(e,o,a){o={...o,archivedAt:null},this.store.copySession(e,o,a);let u=this.open(o);return this.sessions.set(o.id,u),this.plugins.notify("session.fork",u),this.emit({type:"session",session:u.info()}),u}exportSession(e){let o=this.get(e);if(!o)throw new y("no such session");let a=o.info(),u=a.projectID?this.store.project(a.projectID):void 0;return E0(a,this.store.records(e),u?{name:u.name,directory:u.directory}:void 0)}importSession(e,o={}){if(o.model!==void 0)this.checkModel(o.model);if(o.projectID)this.projectOperations.requireProject(o.projectID);let a=[o.model,e.model,this.defaultModel].find((f)=>f!==void 0&&kn(this.options.models,f)!==void 0),u=a?kn(this.options.models,a):void 0;if(!a||!u)throw new t("\u6CA1\u6709\u53EF\u7528\u7684\u6A21\u578B\u6765\u627F\u63A5\u5BFC\u5165\u7684\u4F1A\u8BDD");let m={id:ne("s"),title:e.title.trim()||"\u5BFC\u5165\u7684\u4F1A\u8BDD",projectID:o.projectID??null,model:a,thinking:e.thinking??null,todos:e.todos,created:e.created,updated:e.updated,archivedAt:null,parentID:null,forkThroughSeq:null,kind:"main"};this.store.insertSessionWithRecords(m,e.needsRaw?w0(e.records,u):e.records);let p=this.open(m);return this.sessions.set(m.id,p),this.emit({type:"session",session:p.info()}),p}truncateHistory(e,o){let a=this.sessions.get(e.id);if(!a)throw new y("no such session");if(a.assertWritable(),a.status==="busy")throw new oe;if(!kn(this.options.models,e.model))throw new t(`\u4F1A\u8BDD\u4F7F\u7528\u7684\u6A21\u578B ${e.model} \u5DF2\u4E0D\u53EF\u7528\uFF0C\u8BF7\u5148\u5207\u6362\u6A21\u578B\u518D\u64CD\u4F5C`);a.close();for(let f of this.sessions.values()){if(f.info().parentID!==e.id)continue;if(f.status==="busy")f.abort();f.close()}this.store.truncateSession(e,o);let u=[],m=this.store.lastEntry(e.id,"run");if(m?.type==="run"&&m.state==="start"){let f=this.store.records(e.id,m.seq).filter((h)=>h.raw);for(let h of qe(f)){if(h.result)continue;let{body:I,raw:E}=il(h.call,"\u4E4B\u540E\u7684\u6D88\u606F\u88AB\u7528\u6237\u4FEE\u6539\uFF0C\u8FD9\u6B21\u8C03\u7528\u7684\u7ED3\u679C\u5DF2\u968F\u622A\u65AD\u4E22\u5F03\uFF0C\u6267\u884C\u72B6\u6001\u672A\u77E5\u3002\u7EE7\u7EED\u524D\u5148\u6838\u5B9E\u5B9E\u9645\u72B6\u6001\u3002");u.push(this.store.appendEntry(e.id,void 0,I,E))}u.push(this.store.appendEntry(e.id,void 0,{type:"run",state:"end",reason:"aborted"}))}let p=this.open(e,"replay");this.sessions.set(e.id,p),this.emit({type:"truncated",sessionID:e.id,after:o-1,truncationEpoch:this.store.truncationEpoch(e.id)});for(let f of u)this.emit({type:"entry",sessionID:e.id,entry:f});return p}setArchived(e,o){let a=this.sessions.get(e);if(!a)throw new y("no such session");let u=a.info().parentID;if(!o&&u&&this.sessions.get(u)?.isArchived)throw new t("\u8BF7\u5148\u6062\u590D\u6240\u5C5E\u7236\u4F1A\u8BDD");let m=this.sessionTree(a);if(m.some((p)=>p.status==="busy"))throw new oe;if(a.isArchived===o)return a.info();this.store.setArchived(m.map((p)=>p.id),o?Date.now():null);for(let p of m)p.refreshArchive();for(let p of m)p.archiveChanged();return a.info()}sessionTree(e){let o=[e];for(let a=0;a<o.length;a++){let u=o[a];if(!u)continue;for(let m of this.sessions.values())if(m.info().parentID===u.id)o.push(m)}return o}deleteSession(e){let o=this.sessions.get(e);if(!o)throw new y("no such session");if(o.status==="busy")throw new oe;let a=this.sessionTree(o).slice(1),u=()=>{for(let m of a)m.close(),this.plugins.notify("session.delete",m),this.sessions.delete(m.id),this.emit({type:"removed",kind:"session",id:m.id});o.close(),this.store.deleteSession(e),this.plugins.notify("session.delete",o),this.sessions.delete(e),this.emit({type:"removed",kind:"session",id:e})};if(!a.length)return u();o.close();for(let m of a)m.close(),m.abort();return Promise.all(a.map((m)=>m.idle())).then(u)}open(e,o="create"){let a=e.id,u=new kl(e,{store:this.store,plugins:this.plugins,ready:()=>this.ready,initialized:()=>this.initialized||this.options.plugins?.builtins===!1,models:this.options.models,setup:(m,p)=>pv(this,m,p)},{entry:(m)=>{this.emit({type:"entry",sessionID:a,entry:m})},entryRemoved:(m)=>{this.emit({type:"entry_removed",sessionID:a,seq:m})},aborted:()=>{this.emit({type:"aborted",sessionID:a})},draft:(m)=>this.emit({type:"draft",sessionID:a,parts:m}),changed:()=>{let m=this.sessions.get(a);if(m)this.emit({type:"session",session:m.info()})}});if(o!=="restore")this.plugins.notify(o==="create"?"session.create":"session.open",u);return u}get toolLoading(){return new Ji(this.store)}serverShell(){return this.store.db.query("SELECT value FROM plugin_kv WHERE namespace = 'basalt.server' AND key = 'shell'").get()?.value||"auto"}setServerShell(e){if(!Zo.includes(e))throw new t(`Invalid shell type; must be ${Zo.join(", ")}`);return this.store.db.query("INSERT OR REPLACE INTO plugin_kv (namespace, key, value) VALUES ('basalt.server', 'shell', ?)").run(e),e}checkModel(e){return j0(this,e)}emitEvent(e){this.emit(e)}emit(e){if(e.type==="entry"||e.type==="entry_removed"||e.type==="truncated"||e.type==="session"||e.type==="removed")this.search.nudge();for(let o of this.listeners)try{o(e)}catch(a){console.error("runtime listener failed",a)}}}export{Ve,st,Ni,q,zo,Kn,jo,He,F,n,l,Y,Sr,N,x,i,re,s,g,at,Le,Vo,ve,T,kt,Ze,C,qe,W,G,Rt,bt,Ko,Ht,wr,Qn,sn,Ct,Xn,Ce,de,an,ln,xr,Jn,Yn,cn,Di,qt,Ss,Pe,c,le,et,Ui,Bi,Gt,Zn,zt,jt,Vt,tt,oe,eo,Kt,Qt,ne,un,vr,to,Qo};