@fungi.computer/grove 0.15.0 → 0.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{anthropic-messages-Y5WJvyqH.js → anthropic-messages-BoQicMvu.js} +3 -3
- package/dist/assets/{azure-openai-responses-sv5z2oJl.js → azure-openai-responses-FDabgA7u.js} +1 -1
- package/dist/assets/base-face-BYExcFAP.js +1 -0
- package/dist/assets/burger-B7R4zMC1.js +1 -0
- package/dist/assets/cat-IVcMI3Kr.js +1 -0
- package/dist/assets/{classifier-shared-B2W4uvue.js → classifier-shared-Deocnyea.js} +1 -1
- package/dist/assets/{cloudflare-workers-ai-system-one-C77Rn0un.js → cloudflare-workers-ai-system-one-CGH_pK-e.js} +1 -1
- package/dist/assets/{compat-Bg_8DMIR.js → compat-CfHbT1sC.js} +2 -2
- package/dist/assets/conversation-toast-BrxLLwNS.js +32 -0
- package/dist/assets/document-BiiUDQ73.js +1 -0
- package/dist/assets/document-EWUYmKg3.js +1 -0
- package/dist/assets/{extension-hook-CPEDb_dZ.js → extension-hook-Cmt9U0vD.js} +129 -129
- package/dist/assets/{google-generative-ai-BNzk1CE7.js → google-generative-ai-Ceyomei_.js} +1 -1
- package/dist/assets/{google-shared-DKoN-WAL.js → google-shared-Ck6ywoif.js} +1 -1
- package/dist/assets/{google-vertex-Dagxw3QH.js → google-vertex-BnLh-cet.js} +1 -1
- package/dist/assets/index-Du7GFgpE.js +117 -0
- package/dist/assets/{mistral-conversations-BYjaBa0G.js → mistral-conversations-DpJGrx0P.js} +1 -1
- package/dist/assets/{mushroom-a_sE2Lmz.js → mushroom-CjQXC8r7.js} +1 -1
- package/dist/assets/{node.browser-BYMf8Fo1.js → node.browser-CrrUeMCV.js} +1 -1
- package/dist/assets/{openai-codex-responses-C4lIM44a.js → openai-codex-responses-BMXymyOJ.js} +1 -1
- package/dist/assets/{openai-completions-DxCYryWd.js → openai-completions-FGvQd2Wf.js} +1 -1
- package/dist/assets/{openai-decisions-BpFgAsHO.js → openai-decisions-D2COFIXF.js} +1 -1
- package/dist/assets/{openai-responses-shared-DsXiYlmB.js → openai-responses-shared-DpDj6Ky1.js} +1 -1
- package/dist/assets/{openai-responses-CDv4Cp1s.js → openai-responses-ySTmwOIj.js} +1 -1
- package/dist/assets/{openrouter-images-B1WUs1MY.js → openrouter-images-BU5Yii-E.js} +1 -1
- package/dist/assets/parakeet-CXq4unKH.js +36 -0
- package/dist/assets/parakeet-conversation-UnWYlJ1w.js +4 -0
- package/dist/assets/{pi-messages-eptjcUpt.js → pi-messages-RlRIpxdV.js} +1 -1
- package/dist/assets/renderer-DOUDAFcS.js +1 -0
- package/dist/assets/{runtime-core-6IZ-I96h.js → runtime-core-Nu5SPlul.js} +2 -2
- package/dist/assets/{system-one-shared-CPwLZJuH.js → system-one-shared-BncCsH1N.js} +1 -1
- package/dist/assets/{transform-messages-CAKq9CLB.js → transform-messages-DXxBwHSL.js} +1 -1
- package/dist/assets/{typesafe-system-one-FckVj8yv.js → typesafe-system-one-aoUo0GON.js} +1 -1
- package/dist/assets/{website-conversation-sSS2HMor.js → website-conversation-CtgsyFag.js} +1 -1
- package/dist/index.html +6 -6
- package/package.json +9 -9
- package/dist/assets/animation-Ca8A_H2p.js +0 -1
- package/dist/assets/base-face-Biu4f93I.js +0 -1
- package/dist/assets/burger-C1wxdFxE.js +0 -1
- package/dist/assets/cat-CefyF5eq.js +0 -1
- package/dist/assets/conversation-toast-BgNrfhg0.js +0 -31
- package/dist/assets/document-CEriO-BY.js +0 -1
- package/dist/assets/index-CBzvcFvx.js +0 -117
- package/dist/assets/parakeet-Bf0VgpqA.js +0 -36
- package/dist/assets/parakeet-conversation-DghYwq8X.js +0 -4
- package/dist/assets/renderer-BvWy-oBw.js +0 -1
|
@@ -1,24 +1,24 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-CfHbT1sC.js","assets/text-_WthCHzw.js","assets/preload-helper-CfILh1TC.js","assets/openai-codex.models-DXmil0i7.js","assets/provider-env-CcCbsTJq.js","assets/rolldown-runtime-hePW80VL.js","assets/diagnostics-CxvqSC4Q.js","assets/session-resources-CTNtT8Oa.js","assets/streaming-json-Dg-jk7Sx.js","assets/runtime-core-Nu5SPlul.js","assets/Effect-DeiDqvoz.js","assets/index-Du7GFgpE.js","assets/conversation-toast-BrxLLwNS.js","assets/document-EWUYmKg3.js","assets/document-BiiUDQ73.js","assets/base-face-BYExcFAP.js","assets/index-ODpmGtEN.css","assets/estimate-DElUjJag.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{$a as e,$i as t,$n as n,$r as r,$t as i,A as a,Ai as o,An as s,Ar as c,At as l,B as u,Bn as d,Br as f,Bt as p,C as m,Ci as ee,Cn as te,Ct as ne,D as re,Di as ie,Dn as ae,Dr as oe,Dt as se,E as ce,Ei as le,En as ue,Er as de,Et as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Gn as ve,Gr as ye,Gt as be,H as xe,Hr as Se,Ht as Ce,I as we,Ii as Te,In as Ee,Ir as De,It as Oe,J as ke,Jn as Ae,Jr as je,Jt as Me,K as Ne,Kr as Pe,Kt as Fe,L as Ie,Li as Le,Ln as Re,Lr as ze,Lt as Be,M as Ve,Mi as He,Mn as Ue,Mr as We,Mt as Ge,N as Ke,Ni as qe,Nn as Je,Nr as Ye,Nt as Xe,O as Ze,Oi as Qe,On as $e,Or as et,Ot as tt,P as nt,Pi as rt,Pn as it,Pr as at,Pt as ot,Q as st,Qi as ct,Qr as h,Qt as lt,R as ut,Rn as dt,Rr as ft,Rt as pt,S as mt,Sa as ht,Si as gt,Sn as _t,Sr as vt,St as yt,T as bt,Ta as xt,Ti as St,Tn as Ct,Tt as wt,U as Tt,Un as Et,Ur as Dt,Ut as Ot,V as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wn as Pt,Wr as Ft,Wt as It,X as Lt,Xa as Rt,Xn as zt,Xr as Bt,Xt as Vt,Y as Ht,Yi as Ut,Yn as Wt,Yr as Gt,Yt as Kt,Z as qt,Zi as Jt,Zn as Yt,Zt as Xt,_ as Zt,_a as Qt,_i as $t,_n as en,_r as tn,a as g,aa as nn,ai as rn,an,ar as on,at as sn,b as cn,ba as ln,bi as un,bn as dn,br as fn,bt as pn,c as mn,ca as hn,ci as gn,cn as _n,cr as vn,d as yn,da as bn,di as xn,dn as Sn,dr as Cn,ea as wn,en as Tn,er as En,et as Dn,f as On,fa as _,fi as kn,fn as An,ft as jn,g as v,ga as Mn,gi as Nn,gn as Pn,gr as Fn,gt as In,h as Ln,ha as Rn,hi as zn,hn as Bn,hr as Vn,ht as y,i as Hn,ii as Un,in as Wn,ir as Gn,it as Kn,j as b,jr as qn,jt as Jn,k as Yn,ki as Xn,kr as Zn,kt as Qn,l as $n,li as er,ln as tr,lt as nr,m as rr,ma as ir,mi as ar,mn as or,mt as sr,ni as cr,nn as lr,no as ur,nt as dr,o as fr,oa as pr,oi as mr,on as hr,or as gr,ot as _r,p as vr,pa as yr,pi as br,pn as xr,pr as Sr,pt as x,q as Cr,qr as S,qt as wr,r as Tr,ra as Er,ri as Dr,rn as Or,rt as kr,s as Ar,sa as jr,sn as Mr,sr as Nr,st as Pr,t as Fr,ta as Ir,ti as Lr,tn as Rr,tt as zr,u as Br,ua as Vr,ui as Hr,un as Ur,ur as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wa as Qr,wi as $r,wn as ei,wr as ti,wt as C,x as ni,xa as w,xi as ri,xn as ii,xr as ai,xt as oi,y as T,ya as si,yi as ci,yn as li,yr as ui,yt as di,z as fi,zr as pi,zt as mi}from"./Effect-DeiDqvoz.js";import{c as hi,t as gi}from"./preload-helper-CfILh1TC.js";var _i=e=>e>0?Math.floor(e):0,vi=e=>Math.max(1,_i(e)),yi=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},bi=`~effect/BigDecimal`,xi={[bi]:bi,[kn](){let e=ki(this);return gn(xn(String(e.value)),Hr(e.scale))},[mr](e){return Si(e)&&Pi(this,e)===0},toString(){return`BigDecimal(${Ii(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Pe](){return this.toJSON()},pipe(){return Le(this,arguments)}},Si=e=>br(e,bi),Ci=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(xi);return n.value=e,n.scale=t,n},wi=(e,t)=>{let n=Ci(e,t);return n.normalized=n,n},Ti=BigInt(0),Ei=BigInt(1),Di=BigInt(10),Oi=wi(Ti,0),ki=e=>{if(e.normalized===void 0){if(e.value===Ti)e.normalized=Oi;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=wi(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Ai=100,ji=[Ei],Mi=(e,t)=>e===t?0:e<t?-1:1,Ni=(e,t)=>{let n=`${e.value<Ti?-e.value:e.value}`,r=`${t.value<Ti?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Ti)return i<Ti?-1:1;let a=Math.max(n.length,r.length);return Yr(n.padEnd(a,`0`),r.padEnd(a,`0`))},Pi=(e,t)=>{if(e.scale===t.scale)return Mi(e.value,t.value);let n=Fi(e),r=Fi(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>Ai)return n===-1?Ni(t,e):Ni(e,t);let o=ji[a]??=Di**BigInt(a);return i>0?Mi(e.value,t.value*o):Mi(e.value*o,t.value)},Fi=e=>e.value===Ti?0:e.value<Ti?-1:1,Ii=e=>{let t=ki(e);if(Math.abs(t.scale)>=16)return Li(t);let n=t.value<Ti,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},Li=e=>{if(Ri(e))return`0e+0`;let t=ki(e),n=`${t.value}`,r=t.value<Ti?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Ri=e=>e.value===Ti,zi=oe,Bi=`~effect/encoding/EncodingError`,Vi=class extends zi(`EncodingError`){[Bi]=Bi},Hi=f,Ui=qn,Wi=c,Gi=Zn,Ki=Or,qi=Xe,Ji=ge,Yi=lt,Xi=i,Zi=Xt,Qi=lr,$i=ot,ea=ft,ta=We,na=tt;Je()(`effect/Cause/StackTrace`),Je()(`effect/Cause/InterruptorStackTrace`);var ra=ze,ia=De,aa=he,oa=at,sa=be,ca=Ce,la=Mt,ua=It,da=Ot,fa=mi,pa={"~effect/Deferred":{_A:He,_E:He},pipe(){return Le(this,arguments)}},ma=function(){this.resumes=void 0,this.effect=void 0};ma.prototype=pa;var ha=()=>new ma,ga=()=>_t(()=>ha()),_a=e=>Jn(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),_t(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),va=o(2,(e,t)=>_t(()=>xa(e,t))),ya=o(2,(e,t)=>va(e,he(t))),ba=o(2,(e,t)=>va(e,ze(t))),xa=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},Sa=Jr,Ca=Pn,wa=en,Ta=tr,Ea=An,Da=Sn,Oa=or,ka=Bn,Aa=xr,ja=se,Ma=Be,Na=`~effect/DateTime`,Pa=`~effect/DateTime/TimeZone`,Fa={[Na]:Na,pipe(){return Le(this,arguments)},[Pe](){return this.toString()},toJSON(){return Ka(this).toJSON()}},Ia={...Fa,_tag:`Utc`,[kn](){return Hr(this.epochMilliseconds)},[mr](e){return Ra(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ka(this).toJSON()})`}};({...Fa});var La={[Pa]:Pa,[Pe](){return this.toString()}};({...La}),{...La};var Ra=e=>br(e,Na),za=e=>e._tag===`Utc`,Ba=e=>{let t=Object.create(Ia);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Va=e=>{let t=e.getTime();if(Number.isNaN(t))throw new na(`Invalid date`);return Ba(t)},Ha=e=>{if(Ra(e))return e;if(e instanceof Date)return Va(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Va(new Date(e.epochMilliseconds));let t=new Date(0);return qa(t,e),Va(t)}return typeof e==`string`&&!Ua(e)?Va(new Date(e+`Z`)):Va(new Date(e))},Ua=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Wa=vn(Ha),Ga=e=>Ba(e.epochMilliseconds),Ka=e=>new Date(e.epochMilliseconds),qa=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Ja=e=>Ka(e).toISOString();globalThis.Number;var Ya=o(2,(e,t)=>{if(!globalThis.Number.isFinite(e)||!globalThis.Number.isFinite(t)||t===0)return NaN;if(globalThis.Number.isInteger(e)&&globalThis.Number.isInteger(t))return e%t;let[n,r]=Xa(e),[i,a]=Xa(t),o=Math.min(r,a),s=n*BigInt(10)**BigInt(r-o)%(i*BigInt(10)**BigInt(a-o));if(s===BigInt(0))return e<0||Object.is(e,-0)?-0:0;let c=globalThis.Number(`${s}e${o}`);return c===0?Math.sign(e)*globalThis.Number.MIN_VALUE:c});function Xa(e){if(globalThis.Number.isInteger(e))return[BigInt(e),0];let t=Math.abs(e).toExponential(),n=t.indexOf(`e`),r=t.slice(0,n).replace(`.`,``);return[BigInt(r)*(e<0?-BigInt(1):BigInt(1)),globalThis.Number(t.slice(n+1))-r.length+1]}globalThis.String;var Za=e=>e.trim(),Qa=o(2,(e,t)=>Ge(e,no,e=>t(e))),$a=e=>e.reasons.some(eo),eo=e=>e._tag===`Fail`&&ea(e.error),to=e=>{let t,r=!1;for(let n of e.reasons)eo(n)?t??=n.error:n._tag!==`Interrupt`&&(r=!0);return t===void 0?ve(e):r?ve(Ui(e.reasons.filter(e=>!eo(e)))):n(t)},no=e=>{let t=to(e);return Ae(t)?t:n(t.success.value)},ro=e=>{let t=to(e);return Ae(t)?ia(t.failure):ra(t.success.value)},io=Ue(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),ao=Ue(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),oo=`~effect/Metric`,so=class{[oo]=oo;#e;#t=``;id;description;attributes;constructor(e,t,n){this.id=e,this.description=t,this.attributes=n}valueUnsafe(e){return this.hook(e).get(e)}modifyUnsafe(e,t){return this.hook(t).modify(e,t)}updateUnsafe(e,t){return this.hook(t).update(e,t)}hook(e){let t=Ee(e,io);t!==this.#e&&(this.#e=t,this.#t=ho(this,_o(this.attributes,t)));let n=Ee(e,ao),r=n.get(this.#t);return le(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?_o(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return Le(this,arguments)}},co=BigInt(0),lo=class extends so{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,vo(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?co:0,t=this.#t?this.#e?e=>e>=co:e=>e>=0:e=>!0;return go(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},uo=class extends so{type;metric;valueUnsafe;updateUnsafe;modifyUnsafe;constructor(e,t,n,r){super(e.id,e.description,e.attributes),this.metric=e,this.valueUnsafe=t,this.updateUnsafe=n,this.modifyUnsafe=r,this.type=e.type}createHooks(){return this.metric.createHooks()}},fo=(e,t)=>new lo(e,t),po=o(2,(e,t)=>Oe(n=>_t(()=>e.updateUnsafe(t,n)))),mo=o(2,(e,t)=>{let n=yo(t);return new uo(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function ho(e,t){let n=Object.entries(t).sort((e,t)=>e[0]<t[0]?-1:+(e[0]>t[0]));return JSON.stringify([e.type,e.id,e.description,n])}function go(e,t,n){return{get:e,update:t,modify:n??t}}function _o(e,t){return{...vo(e),...vo(t)}}function vo(e){return ci(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(h(e,t,n),e),{}):e}function yo(e){let t,n={};return r=>{let i=Ee(r,io);return i!==t&&(t=i,n=_o(i,e)),it(r,io,n)}}var bo=Ra,xo=za,So=Ha,Co=Wa,wo=Ga;Je()(`effect/DateTime/CurrentTimeZone`);var To=Ja,Eo=e=>Oo(typeof e==`string`?ko.encode(e):e),Do=e=>{let t=Ao(e),r=t.length;if(r%4!=0)return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${r}`}));let i=t.indexOf(`=`);if(i!==-1&&(i<r-2||i===r-2&&t[r-1]!==`=`))return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),i=new Uint8Array(r/4*3-e);for(let e=0,n=0;e<r;e+=4,n+=3){let r=No(t.charCodeAt(e))<<18|No(t.charCodeAt(e+1))<<12|No(t.charCodeAt(e+2))<<6|No(t.charCodeAt(e+3));i[n]=r>>16,i[n+1]=r>>8&255,i[n+2]=r&255}return n(i)}catch(e){return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Oo=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2|e[r]>>6],n+=jo[e[r]&63];return r===t+1&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2],n+=`=`),n},ko=new TextEncoder,Ao=e=>e.replace(/[\n\r]/g,``),jo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Mo=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Mo[jo.charCodeAt(e)]=e;Mo[61]=0;var No=e=>{if(e>=Mo.length||Mo[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Mo[e]};zi(`CookiesError`),{...ye},{...ye};var Po=new WeakMap,Fo=`~effect/Redacted`,Io=e=>br(e,Fo),Lo=(e,t)=>{let n=Object.create(Ro);return t?.label&&(n.label=t.label),Po.set(n,e),n},Ro={[Fo]:{_A:e=>e},label:void 0,...de,toJSON(){return this.toString()},toString(){return`<redacted${$r(this.label)?`:`+this.label:``}>`},[kn](){return er(Po.get(this))},[mr](e){return Io(e)&&Dr(Po.get(this),Po.get(e))}};({...de});function zo(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Bo(e){return t=>zo(t)?.[e]}var Vo=`~structural`,Ho=`~identifier`,Uo=`~sentinels`,Wo=`~constructor`,Go=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],Ko=Bo(`identifier`),qo=Bo(Ho),Jo=Bo(`title`),Yo=Bo(`description`),Xo=qe(e=>{let t=zo(e)?.identifier;return typeof t==`string`?t:e.getExpected(Xo)}),Zo=new Set([Uo,Vo,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),E=Symbol(),Qo=ra,$o=Qo(E),es=Qo(E),ts=e=>e===E?Cn():Sr(e),ns=e=>e._tag===`None`?$o:Qo(e.value),rs=`~effect/SchemaIssue/Issue`;function is(e){return br(e,rs)&&e[rs]===rs}function as(e){return Object.hasOwn(e,`input`)}var os=class{[rs]=rs;constructor(e,t){t?.reportInput===!0&&e!==E&&(this.input=e)}},ss=class extends os{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},cs=class extends os{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},ls=class extends os{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},us=class extends os{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},ds=class extends os{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},fs=class extends os{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ps=class extends os{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},ms=class extends os{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},hs=class extends os{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},gs=class extends os{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},_s=class extends os{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function vs(e,t,n){if(is(e))return e;if(typeof e==`string`)return new ms({message:e},t,n);let r=typeof e.issue==`string`?new ms({message:e.issue},t,n):e.issue;return new ls(e.path,r)}function ys(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new ms(void 0,t,n):vs(e,t,n)}function bs(e,t,n,r){return Array.isArray(t)?At(t)?t.length===1?vs(t[0],n,r):new fs(e,Et(t,e=>vs(e,n,r)),n,r):void 0:ys(t,n,r)}var xs=e=>{let t=Ms(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Es(Xo(e.ast),e);case`InvalidValue`:{let t=Ts(e);if(t!==void 0)return Es(t,e);let n=ws(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=ws(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=ws(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Ss=e=>Ms(e.issue)??Ms(e);function Cs(e){return t=>({issues:Ds(t,[],e?.leafHook??xs,e?.checkHook??Ss)})}function ws(e){return as(e)?S(e.input):void 0}function Ts(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Es(e,t){let n=ws(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Ds(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return Ds(e.issue,t,n,r);let a=Ts(e.issue);return[{path:t,message:a===void 0?Es(Os(e.filter),e):Es(a,e.issue)}]}case`Encoding`:return Ds(e.issue,t,n,r);case`Pointer`:return Ds(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>Ds(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:Ms(e)??Es(Xo(e.ast),e)}]:e.issues.flatMap(e=>Ds(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Os(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>Os(e)).join(` & `)}}function ks(){return e=>js(e,``)}var As=ks();function js(e,t){let n;switch(e._tag){case`Filter`:{let r=Ss(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return js(e.issue,t);let r=Ts(e.issue);n=r===void 0?Es(Os(e.filter),e):Es(r,e.issue)}break}case`Encoding`:return js(e.issue,t);case`Pointer`:return js(e.issue,t+Gt(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>js(e,t)).join(`
|
|
3
|
-
`);n=Ms(e)??Es(Xo(e.ast),e);break;default:n=xs(e)}return t?`${n}\n at ${t}`:n}function Ms(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Ms(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Ns(e){let t;for(let n of e.reasons){if(!Hi(n)||!is(n.error))return;t??=n.error}return t}function Ps(e,t){let n=Ns(e);if(n===void 0)throw Error(t,{cause:e});return n}var Fs=e=>Eo(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Is=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Length should be a multiple of 4, but is ${n}`}));if(!/^[-_A-Z0-9]*?={0,2}$/i.test(t))return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Invalid input`}));let r=n%4==2?`${t}==`:n%4==3?`${t}=`:t;return r=r.replace(/-/g,`+`).replace(/_/g,`/`),Do(r)},Ls=e=>Object.assign(Object.create(Te),e);function Rs(e){return qs((t,n)=>v(e(t,n)))}function zs(e){return Rs((t,n)=>{let r={message:e(t)};return Nr(t)?new hs(r,t.value,n):new hs(r)})}var Bs=zs(()=>`Encoding is not supported`),Vs=Ls({_tag:`Passthrough`});function Hs(){return Vs}function Us(){return Vs}function Ws(e){return Ls({_tag:`Transform`,transform:e})}function Gs(e){return Ls({_tag:`TransformEffect`,transform:e})}function Ks(e){return Ls({_tag:`TransformOptional`,transform:e})}function qs(e){return Ls({_tag:`TransformOptionalEffect`,transform:e})}function Js(){return Ks(()=>Cn())}function Ys(e){return qs(t=>{let n=En(t,ci);return Nr(n)?x(n):Ie(e,Sr)})}function Xs(){return Ws(globalThis.String)}function Zs(){return Ws(globalThis.Number)}function Qs(){return Ws(globalThis.BigInt)}function $s(){return Ws(e=>new globalThis.Date(e))}function ec(){return Ws(Za)}function tc(e){return Gs((t,n)=>oi({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ms({expected:`a valid JSON string`},t,n)}))}function nc(e){return Gs((t,n)=>oi({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new ms({expected:`a JSON-serializable value`},t,n)}))}function rc(){return Ws(Eo)}function ic(){return Gs((e,t)=>fi(a(Do(e)),()=>new ms({expected:`a valid Base64 string`},e,t)))}var ac=class extends pe{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new ac(this.encode,this.decode)}},oc=`~effect/SchemaTransformation/Transformation`,sc=class extends pe{[oc]=oc;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new sc(this.encode,this.decode)}};function cc(e){return br(e,oc)&&e[oc]===oc}var lc=e=>cc(e)?e:new sc(e.decode,e.encode);function uc(e){return new sc(Gs(e.decode),Gs(e.encode))}function dc(){return new sc(ec(),Hs())}var fc=new sc(Hs(),Hs());function pc(){return fc}var mc=new sc(Zs(),Xs()),hc=new sc(Qs(),Xs()),gc=new sc($s(),Ws(je)),_c=new sc(ic(),rc());function vc(e){return new sc(tc(e??{}),nc(e))}function yc(e){return t=>t._tag===e}var bc=yc(`Declaration`),xc=yc(`Null`),Sc=yc(`Undefined`),Cc=yc(`Never`),wc=yc(`String`),Tc=yc(`Number`),Ec=yc(`Boolean`),Dc=yc(`Literal`),Oc=yc(`UniqueSymbol`),kc=yc(`Arrays`),Ac=yc(`Objects`),jc=yc(`Union`),Mc=yc(`Suspend`),Nc=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Pc={},Fc=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Ic=`~effect/Schema`,Lc=class{[Ic]=Ic;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},Rc=class extends Lc{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===E?$o:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=du(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Rc(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},zc=new class extends Lc{_tag=`Null`;getParser(){return Mu(this,null)}getExpected(){return`null`}},Bc=class extends Lc{_tag=`Undefined`;getParser(){return Mu(this,void 0)}toCodecJson(){return $l(this,[Vc])}getExpected(){return`undefined`}},Vc=new Nc(zc,new sc(Ws(()=>void 0),Ws(()=>null))),Hc=new Bc,Uc=new class extends Lc{_tag=`Never`;getParser(){return Nu(this,$t)}getExpected(){return`never`}},Wc=new class extends Lc{_tag=`Unknown`;getParser(){return Nu(this,ie)}getExpected(){return`unknown`}},Gc=class extends Lc{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${S(e)}`);this.literal=e}getParser(){return Mu(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Kc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Kc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Kc(e){let t=globalThis.String(e.literal);return $l(e,[new Nc(new Gc(t),new sc(Ws(()=>e.literal),Ws(()=>t)))])}var qc=new class extends Lc{_tag=`String`;getParser(){return Nu(this,$r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Yu(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Jc=class extends Lc{_tag=`Number`;getParser(){return Nu(this,un)}matchKey(e,t){return this._match(Ru,e,t)}matchPart(e,t){return this._match(Lu,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Yu(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Yc(this.checks,`effect/schema/isFinite`)||Yc(this.checks,`effect/schema/isInt`))?this:$l(this,[Jl])}toCodecStringTree(){return this.toCodecJson()===this?$l(this,[Vu]):$l(this,[Hu])}getExpected(){return`number`}};function Yc(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Yc(e.checks,t))}var Xc=new Jc,Zc=new class extends Lc{_tag=`Boolean`;getParser(){return Nu(this,zn)}getExpected(){return`boolean`}},Qc=new class extends Lc{_tag=`Symbol`;getParser(){return Nu(this,St)}matchKey(e,t){return t.disableChecks||!this.checks?e:Yu(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return $l(this,[qu])}getExpected(){return`symbol`}},$c=new class extends Lc{_tag=`BigInt`;getParser(){return Nu(this,ar)}matchPart(e,t){if(!Uu.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Yu(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return $l(this,[Gu])}getExpected(){return`bigint`}},el=class extends Lc{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Su(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Su(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new ds(n,t[o],i),a=new ls([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return v(new fs(n,[a],t,i))}return e.issues?v(new fs(n,e.issues,t,i)):Qo(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Ur(t.concurrency),f=d===1?rl(i,e,0,u):il(i,e,{concurrency:d,end:u});if(!f)return c(i);if(pt(f))return cn(f,()=>c(i));let p=!0;return sr(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===E)return $o;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):v(new ps(n,e,a))}catch(e){return vr(e)}}}_rebuild(e,t,n){let r=du(this.elements,e),i=du(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new el(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function tl(e,t,n,r){if(n._tag===`Failure`)return al(e,e.ast,r,n);let i=n===es?t:n[et];if(i!==E)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Su(t.ast))return;let n=new ls([r],new us(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return aa(new fs(e.ast,[n],e.input,e.options))}}var nl={onItem(e,t,n){let r=n<e.len?t:E;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:tl},rl=an()(nl),il=Wn()(nl),al=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Ns(r.cause);if(i===void 0)return ia(qi(r.cause,r=>new fs(t,[new ls([n],r)],e.input,e.options)));let a=new ls([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return aa(new fs(t,[a],e.input,e.options))},ol=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function sl(e,t,n=Pc){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(Pu(Ou(t)))}var cl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ll(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ll);default:return!1}}function ul(e){let t=tu(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ul);default:return!1}}function dl(e){return ll(e)&&ul(e)}var fl=class{parameter;type;constructor(e,t){if(!dl(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Su(t)&&!ju(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},pl=class extends Lc{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Nu(n,qr);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(Pu(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return al(t,n,i,s)??sa;let c=s===es?o:s[et];if(a!==E&&c!==E){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return sa;h(t.out,a,c)}return sa},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!pt(t))return T(Ln(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return al(e,n,r,a)??sa;let o=a===es?r:a[et],s=e.input[r],l=i.parserValue(s,e.options);return pt(l)?t(e,r,o,s,l):T(Ln(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return pt(a)?t(e,n,n,i,a):T(Ln(a),r=>t(e,n,n,i,r))},u=i?Wn()({onItem:(e,[t,n])=>n.is.parameter===qc?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return m(function*(t,d){if(t===E)return E;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*v(new ps(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},ee=d.errors===`all`,te=d.onExcessProperty===`error`,ne=d.concurrency===void 0?1:Ur(d.concurrency),re=i&&te?n.indexSignatures.map(e=>sl(f,e.parameter,d)):void 0;if(te){let r=re?new Set(e):e;if(re)for(let e of re)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new ds(n,f[a],d),r=new ls([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*v(new fs(n,[r],t,d))}}}if(r){let e=ne===1?gl(m,a):_l(m,a,{concurrency:ne});e&&(yield*e)}if(i&&ne===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===qc?l:c,r=re?.[e]??(t.is.parameter===qc?Object.keys(f):sl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!pt(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=dt();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===qc?Object.keys(f):sl(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:ne});t&&(yield*t)}return m.issues?yield*v(new fs(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(Ln(n),n=>{let i=ml(e,r,n);if(i)return i;let o=()=>Qo(e.out),s=gl(e,a.slice(t+1));return s?cn(s,o):o()})};return(e,t)=>{if(e===E)return $o;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Ur(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return v(new ps(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=Al(i,s),l=c?i[s]:E,d=n.parser(l,t);if(!pt(d))return u(o,e,d);if(d===es){c&&h(a,s,l);continue}let f=ml(o,n,d);if(f)return f}}catch(e){return vr(e)}return Qo(a)}}_rebuild(e,t,n,r){let i=du(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new cl(t.name,n)}),a=du(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new fl(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new pl(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function ml(e,t,n){if(n._tag===`Failure`)return al(e,e.ast,t.name,n);if(n===es)return;let r=n[et];if(r!==E){h(e.out,t.name,r);return}if(delete e.out[t.name],!Su(t.type)){let n=new ls([t.name],new us(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return aa(new fs(e.ast,[n],e.input,e.options))}}var hl={onItem(e,t){if(!Al(e.input,t.name))return t.parser(E,e.options);let n=e.input[t.name];return h(e.out,t.name,n),t.parser(n,e.options)},step:ml},gl=an()(hl),_l=Wn()(hl);function vl(e,t){return e?t?[...e,...t]:e:t}function yl(e,t,n){return new pl(Reflect.ownKeys(e).map(t=>new cl(t,e[t].ast)),[],n,t)}function bl(e){return e.ast}function xl(e,t=void 0){return new el(!1,e.map(e=>e.ast),[],void 0,t)}function Sl(e,t,n){return new Ml(e.map(bl),t,void 0,n)}function Cl(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new el(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var wl=rt(e=>{for(;;){if(Mc(e))return Wc;let t=e.encoding;if(!t)return e.recur?.(wl,He)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==He))return Wc;e=t[t.length-1].to}});function Tl(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(Tl)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function El(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Uo];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Su(t)){if(Dc(t))return[{key:e.name,literal:t.literal}];if(Oc(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Su(e)){if(Dc(e))return[{key:t,literal:e.literal}];if(Oc(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>El(wl(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return El(e.thunk())}}var Dl=new WeakMap,Ol=Object.freeze([]),kl=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Al=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function jl(e){let t=Dl.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=wl(c);if(Cc(l))continue;if(Dc(l)||Oc(l)){a??=new Map;let e=Dc(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=El(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=Tl(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Ol);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Ol;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(gt(e)){let n=Al(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Ol;if(t)return o}return Ol}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=kl(t);if(!gt(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Al(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=Al(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=Al(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(kl(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Dl.set(e,t),t}var Ml=class extends Lc{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===E)return $o;let i=(o??=jl(n.types))(e,r);if(i.length===0)return v(new gs(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:pt(r)?Nl(n,r.cause,e,t):Pl(n,r,e,t)}return Fl(n,a,i,e,t)}}_rebuild(e,t,n){let r=du(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Ml(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=Ou(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Dc);if(t.length>0)return`${zl(n.isMutable)}[ ${t.map(t=>e(t)+Bl(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Dc(e.type));if(t.length>0)return`{ ${t.map(t=>`${zl(t.type.context?.isMutable)}${Bt(t.name)}${Bl(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Nl(e,t,n,r){let i=Ns(t);return i?aa(new gs(e,[i],n,r)):ia(t)}function Pl(e,t,n,r){return Br(t,t=>Nl(e,t,n,r))}function Fl(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=Ll(a,n);if(!o)return a.out?a.out:v(new gs(e,a.issues??[],r,i));if(pt(o))return Il(o,a);let s=!0;return sr(()=>s?(s=!1,Il(o,a)):Fl(e,t,n,r,i))}function Il(e,t){return cn(e,e=>t.out===es?x(t.input):t.out?t.out:v(new gs(t.ast,t.issues??[],t.input,t.options)))}var Ll=an()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Ns(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),aa(new _s(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return sa}}}),Rl=new Ml([new Gc(`Infinity`),new Gc(`-Infinity`),new Gc(`NaN`)]);function zl(e){return e?``:`readonly `}function Bl(e){return e?`?`:``}var Vl=class extends Lc{_tag=`Suspend`;thunk;constructor(e,t,n,r,i){if(n)throw Error(`Cannot add checks to Suspend`);super(t,void 0,r,i);let a;this.thunk=()=>a??=e()}getParser(e){let t;return(n,r)=>(t??=e(this.thunk()))(n,r)}recur(e){return new Vl(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Hl=class extends pe{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Hl(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Hl(this.run,this.annotations,!0)}and(e,t){return new Ul([this,e],t)}},Ul=class extends pe{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ul(this.checks,{...this.annotations,...e})}and(e,t){return new Ul([this,e],t)}};function Wl(e,t,n=!1){return new Hl((t,n,r)=>bs(n,e(t,n,r),t,r),t,n)}function Gl(e,t){return new Hl((t,n,r)=>e(t)?void 0:new ms(void 0,t,r),t,!0)}function Kl(e){return Wl(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var ql=iu(Xc,[Kl()]),Jl=new Nc(new Ml([ql,Rl]),new sc(Zs(),Ws(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Yl(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Wl(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var Xl=new WeakMap;function Zl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Xl.set(n,Ql(e)),n}function Ql(e){let t=Xl.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Xl.set(e,n),n}function $l(e,t){return e.encoding===t?e:Zl(e,{encoding:t})}function eu(e,t){if(e.context===t)return e;let n=Ql(e);return n.context===t&&n.encoding===e.encoding?n:Zl(e,{context:t})}function tu(e){return e.encoding?tu(e.encoding[e.encoding.length-1].to):e}function nu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return ru(e,Re(e.checks.slice(0,-1),n.annotate(t)))}return Zl(e,{annotations:{...e.annotations,...t}})}function ru(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Zl(e,{checks:t})}function iu(e,t){return ru(e,vl(e.checks,t))}function au(e,t){let n=t(e.to);return n===e.to?e:new Nc(n,e.transformation)}function ou(e,t){let n=e,r=n[n.length-1],i=au(r,t);return i===r?e:Re(e.slice(0,e.length-1),i)}function su(e){return t=>t.encoding?$l(t,ou(t.encoding,e)):t}function cu(e,t){return su(e=>eu(e,t))(e)}function lu(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:$l(r,ou(r.encoding,n))}return e(r)}return rt(n)}function uu(e,t,n){let r=new Nc(e,t);return $l(n,n.encoding?[...n.encoding,r]:[r])}function du(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function fu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Fc(!1,!1,void 0,t))}var pu=rt(e=>mu(eu(e,e.context?e.context.isOptional===!1?new Fc(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!0,!1)))),mu=su(pu),hu=qe(e=>pu(new Ml([e,Hc]))),gu=rt(e=>_u(eu(e,e.context?e.context.isMutable===!1?new Fc(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!1,!0)))),_u=su(gu);function vu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Fc(!1,!1,t))}function yu(e,t,n){return uu(e,n,t)}function bu(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:ee(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function xu(e,t){let{literals:n,parameters:r}=bu(e);return new pl(n.map(e=>new cl(e,t)),r.map(e=>new fl(e,t)))}function Su(e){return e.context?.isOptional??!1}function Cu(e){return e.context?.isMutable??!1}function wu(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(wu)}function Tu(e){function t(e){return wu(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return d(n)?n:void 0}function Eu(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Mc(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var Du=rt(e=>{let t=Ql(e);if(t!==e){let n=Du(t);return n===t&&e.encoding===void 0?e:eu(n,e.context)}let n=`recur`in e?e.recur(Du):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Eu(e)?n.encodingChecks:kc(n)||Ac(n)||bc(n)&&n.typeParameters.length>0?Tu(n.encodingChecks):void 0;return Zl(n,{encodingChecks:void 0,checks:vl(n.checks,t)})}return n}),Ou=rt(e=>Du(Au(e)));function ku(e,t){let n=t,r=n.length,i=n[r-1],a=[new Nc(Au($l(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Nc(Au(n[e-1].to),n[e].transformation.flip()));let o=Au(i.to);return o.encoding?$l(o,[...o.encoding,...a]):$l(o,a)}var Au=qe(e=>{if(e.encoding)return ku(e,e.encoding);let t=Ql(e);if(t!==e){let n=Au(t);return n===t?e:eu(n,e.context)}return`flip`in e?e.flip(Au):`recur`in e?e.recur(Au):e});function ju(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(ju);default:return!1}}function Mu(e,t){let n=t===0?es:Qo(t);return(r,i)=>r===E?$o:r===t?n:v(new ps(e,r,i))}function Nu(e,t){return(n,r)=>n===E?$o:t(n)?es:v(new ps(e,n,r))}var Pu=lu(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Pu)}}),Fu=lu(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Fu)}}),Iu=`[\\s\\S]*?`,Lu=new globalThis.RegExp(`^${ol}$`),Ru=new globalThis.RegExp(`^(?:${ol}|Infinity|-Infinity|NaN)$`);function zu(e){return Yl(Lu,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Lu.source}),...e})}var Bu=iu(qc,[zu()]),Vu=new Nc(Bu,mc),Hu=new Nc(new Ml([Bu,Rl]),mc),Uu=new globalThis.RegExp(`^-?\\d+$`);function Wu(e){return Yl(Uu,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Uu.source}),...e})}var Gu=new Nc(iu(qc,[Wu({expected:`a string representing a bigint`})]),hc),Ku=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),qu=new Nc(iu(qc,[Ju()]),new sc(Ws(e=>globalThis.Symbol.for(Ku.exec(e)[1])),Gs((e,t)=>globalThis.Symbol.keyFor(e)===void 0?v(new hs({message:`cannot serialize to string, Symbol is not registered`},e,t)):x(globalThis.String(e)))));function Ju(e){return Yl(Ku,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:Ku.source}),...e})}function Yu(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Yu(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new ss(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Xu(e){if(!bc(e))return;let t=e.annotations?.[Wo];return Nn(t)?t(e.typeParameters):void 0}var Zu=zo,Qu=Jo,$u=Yo;function ed(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function td(e){return e===void 0||typeof e==`string`}function nd(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function rd(e){return nd(e,ed)}var id=new Rc([],()=>(e,t,n)=>rd(e)?es:v(new ps(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>cd}),ad=new Nc(id,pc()),od=new Nc(new Ml([new el(!1,[],[id]),new pl([],[new fl(qc,id)])]),pc());function sd(e){return nd(e,td)}var cd=new Nc(new Rc([],()=>(e,t,n)=>sd(e)?es:v(new ps(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),pc()),ld=(e,t,n)=>e===es?n(t):cn(e,n);function ud(e){if(e._tag===`Middleware`)return(t,n,r)=>dd(t===es?e.decode(Qo(ts(n)),r):e.decode(Ie(t,ts),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===es?Qo(t):e;case`Transform`:{let e=e=>e===E?$o:Qo(t.transform(e));return(t,n)=>ld(t,n,e)}case`TransformOptional`:{let e=e=>ns(t.transform(ts(e)));return(t,n)=>ld(t,n,e)}case`TransformEffect`:return(e,n,r)=>ld(e,n,e=>e===E?$o:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>ld(e,n,e=>dd(t.transform(ts(e),r)))}}var dd=e=>cn(e,ns),fd=(e,t,n,r)=>Br(r,r=>Kr(()=>qi(r,r=>new cs(e,r,t,n))));function pd(e,t){let n=ud(e.link.transformation),r;return(i,a)=>{if(i===E)return $o;if(e.isConstructed(i))return es;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function md(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==E&&r!==void 0)return t(r,i);let a=n;if(pt(a)&&a._tag===`Success`){let e=t(a[et],i);return e===es?a:e}return cn(fd(e,r,i,a),e=>{let n=t(e,i);return n===es?Qo(e):n})}}function hd(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:md(e,n)}function gd(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Xu(e):void 0,o=a?pd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>ud(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(t!==E&&i!==E){let i=Yu(u,t,void 0,e,n);i&&(r=v(new fs(e,i,t,n)))}}}else r=T(r,r=>{if(t!==E&&r!==E){let r=Yu(u,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(r)})}if(s&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(i===E)return r;let a=Yu(s,i,void 0,e,n);a&&(r=v(new fs(e,a,i,n)))}}else r=T(r,t=>{if(t!==E){let r=Yu(s,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[et],o=t(a,r)):o=cn(o,e=>{let n=t(e,r);return n===es?Qo(e):n})}if(o._tag===`Success`){let e=o[et],t=p(e,r);return t===es?o:t}return o=fd(e,n,r,o),cn(o,e=>{let t=p(e,r);return t===es?Qo(e):t})}:p}var _d=Symbol(),vd=new WeakMap,yd=e=>Cd(e).parser,bd=e=>Cd(e).makeEffect,xd=e=>hd(e,bd),Sd=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=gd(this.ast,yd)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=gd(this.ast,bd,xd)}};function Cd(e){let t=vd.get(e);if(t!==void 0)return t;let n=new Sd(e);return vd.set(e,n),n}function wd(e){let t=e.ast,n;return(e,r)=>(n??=Vd(Jd,Du(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Td(e){let t=wd(e);return(e,n)=>{let r=Pr(t(e,n));return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Ed(e){return Kd(Du(e.ast))}function Dd(e){return kd(e.ast)}function Od(e){{let t=Hd(zd(e));return e=>{let n=t(e,Pc);return ca(n)?!0:(Ps(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function kd(e){let t=Du(e),n=e=>(n=Od(t),n(e));return e=>n(e)}function Ad(e,t){let n=zd(e.ast);return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function jd(e,t){return Hd(Ad(e,t))}function Md(e,t){return Ud(Ad(e,t))}function Nd(e,t){return Wd(Ad(e,t))}function Pd(e,t){let n=zd(Au(e.ast));return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function Fd(e,t){return Hd(Pd(e,t))}function Id(e,t){return Wd(Pd(e,t))}var Ld=(e,t)=>t?{...e,...t}:e,Rd=e=>e===E?v(new ms):x(e);function zd(e){return Vd(qd,e)}function Bd(e,t){return e===es?x(t):pt(e)?e[et]===E?Rd(E):e:cn(e,Rd)}function Vd(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Pc);return a===es?x(r):pt(a)?a[et]===E?Rd(E):a:cn(a,Rd)}}function Hd(e){return(t,n)=>Pr(e(t,n))}function Ud(e){let t=Hd(e);return(e,n)=>{let r=t(e,n);return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Wd(e){let t=Hd(e);return(e,r)=>{let i=t(e,r);return ca(i)?n(i.value):ve(Ps(i.cause,`Result adapter can only return schema issues`))}}function Gd(e,t){let n=Pr(e);if(ca(n))return n.value;let r=Ps(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Kd(e){let t,n;return(r,i)=>{t??=Cd(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Pc,o=t.make;if(o!==void 0&&r!==E){let e;try{e=o(r,a)}catch(e){throw Ps(Gi(e),`Constructor adapter can only throw schema issues`),e}if(e!==_d&&e!==E)return e}return Gd(Bd((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var qd=e=>Cd(e).parser,Jd=e=>Cd(e).makeEffect,Yd=`~effect/Schema/Schema`,Xd=Symbol(),Zd={[Yd]:Yd,get make(){let e=Ed(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=wd(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Td(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Le(this,arguments)},annotate(e){return this.rebuild(nu(this.ast,e))},annotateKey(e){return this.rebuild(fu(this.ast,e))},check(...e){return this.rebuild(iu(this.ast,e))},rebuild(e){return Qd(e,this[Xd])}};function Qd(e,t){function n(){}let r=Object.setPrototypeOf(n,Zd);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Xd]=t,r.ast=e,r}function $d(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ef(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function tf(e){return encodeURI($d(e)).replace(/#/g,`%23`)}function nf(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function rf(e){let t=nf(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(ef)}function af(e){return e.reduce((e,t)=>`${e}/${tf(t)}`,`#`)}var of=`http://json-schema.org/draft-07/schema#`;function sf(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function cf(e){return{dialect:`draft-07`,...bf(e,Mf)}}function lf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!ri(e))return e;let a=r||!i&&yf(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=ff(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}h(o,t,i)}return t(o,a),o}}function uf(e,t){return lf(e,e=>{df(e,t)})}function df(e,t){typeof e.$ref==`string`&&h(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&h(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function ff(e,t){if(!ri(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function pf(e,t,n){let r=new Map,i=[],a=mf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=gf(ri(e)?u(e):void 0,mf)??mf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=hf(t,n);if(a!==void 0){let e=rf(a.hash);if(a.hash=``,e!==void 0){let n=r.get(vf(a.href,e));n!==void 0&&(i=_f(t,n))}}h(e,`$ref`,i)}}let c=n(o);return s(),c;function l(n,r,a,o){if(typeof n==`boolean`)return d(r,a,o),t?.booleanAdapter?.(n)??n;if(!ri(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&yf(c)){let e=gf(c,o.uri);e!==void 0&&(s={parent:o,sourceRoot:r,targetRoot:a,uri:e})}d(r,a,s);let f=s.uri;return e(n,{isDocumentRoot:r.length===0,schema(e,t,n=t){return l(e,[...r,t],[...a,n],s)},schemaAt(e,t,n){return l(e,[...r,...t],[...a,...n],s)},schemaArray(e,t,n=t){return Array.isArray(e)?e.map((e,i)=>l(e,[...r,t,String(i)],[...a,n,String(i)],s)):e},schemaMap(e,t,n=t){return ri(e)?ff(e,(e,i)=>l(e,[...r,t,i],[...a,n,i],s)):e},reference(e,t){typeof t==`string`?i.push([e,t,f]):h(e,`$ref`,t)}})}function u(e){return t?.ignoreRefSiblings===!0&&typeof e.$ref==`string`?void 0:e.$id}function d(e,t,n){n.parent!==void 0&&d(e,t,n.parent),r.set(vf(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var mf=`https://effect.invalid/.json-schema/`;function hf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function gf(e,t){if(typeof e!=`string`)return;let n=hf(e,t);if(n!==void 0)return n.hash=``,n.href}function _f(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${af(t)}`}function vf(e,t){return`${e}\u0000${JSON.stringify(t)}`}function yf(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function bf(e,t,n){return pf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:ff(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var xf=new Set([`properties`,`patternProperties`]),Sf=new Set([`allOf`,`anyOf`,`oneOf`]),Cf=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function wf(e,t,n,r,i,a=xf){let o;if(a.has(t))o=r.schemaMap(n,t);else if(Sf.has(t))o=r.schemaArray(n,t);else if(i.has(t))o=r.schema(n,t);else return!1;return h(e,t,o),!0}var Tf=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Tf],[...Tf];var Ef=/^[A-Za-z_][-A-Za-z0-9._]*$/,Df=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Of(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function kf(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Of(i,n,`it is not active in ${r} but would become active in the target`)}var Af=[`additionalItems`,`definitions`,`dependencies`];function jf(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,sf(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):sf(t,`https://json-schema.org/draft/2020-12/schema`)||Of(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Mf(e,t){kf(e,Af,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!wf(n,o,s,t,Cf))switch(o){case`$ref`:r=s;break;case`$schema`:jf(n,s,t,of,`Draft-07`);break;case`$id`:case`$anchor`:break;case`$defs`:h(n,`definitions`,t.schemaMap(s,o,`definitions`));break;case`prefixItems`:i=s;break;case`items`:a=s;break;case`dependentRequired`:case`dependentSchemas`:case`minContains`:case`maxContains`:break;case`$dynamicRef`:case`$dynamicAnchor`:case`$vocabulary`:case`unevaluatedProperties`:case`unevaluatedItems`:Of(o,`Draft-07`,`the target dialect has no equivalent`);case`required`:if(Array.isArray(s)&&s.length===0)break;h(n,o,s);break;default:h(n,o,s)}}if(Nf(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Of(`minContains/maxContains`,`Draft-07`,`contains cardinality cannot be represented`),Object.hasOwn(e,`minContains`)&&h(n,`minContains`,t)}else Object.hasOwn(e,`minContains`)&&h(n,`minContains`,e.minContains),Object.hasOwn(e,`maxContains`)&&h(n,`maxContains`,e.maxContains);return Ff(e,n,t,`draft-07`),Lf(e,n,`$id`,`Draft-07`),Pf(n,r,t),n}function Nf(e,t,n,r){if(t===void 0){n!==void 0&&h(e,`items`,r.schema(n,`items`));return}h(e,`items`,r.schemaArray(t,`prefixItems`,`items`)),n!==void 0&&h(e,`additionalItems`,r.schema(n,`items`,`additionalItems`))}function Pf(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),If(e,r)}else n.reference(e,t)}}function Ff(e,t,n,r){let i=ri(e.dependentRequired)?e.dependentRequired:void 0,a=ri(e.dependentSchemas)?e.dependentSchemas:void 0;if(i===void 0&&a===void 0)return;let o={},s=new Set([...Object.keys(i??{}),...Object.keys(a??{})]);for(let e of s){let t=i?.[e],s=a?.[e],c=r===`draft-04`&&Array.isArray(t)&&t.length===0;s===void 0?c||h(o,e,t):t===void 0||c?h(o,e,n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e])):h(o,e,{allOf:[n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e,`allOf`,`0`]),{required:t}]})}Object.keys(o).length>0&&h(t,`dependencies`,o)}function If(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function Lf(e,t,n,r){let i=e.$id,a=e.$anchor;if(a===void 0){i!==void 0&&h(t,n,i);return}(typeof a!=`string`||!Ef.test(a))&&Of(`$anchor`,r,`the anchor is not valid`),Df.test(a)||Of(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):Of(`$anchor`,r,`it cannot be combined with the schema $id`)}function Rf(e){return Qd(zf(e.ast),{schema:e})}var zf=lu(e=>{let t=Wf(e,zf),n=e.context;return t===e||n===void 0?t:cu(t,Bf(n))});function Bf(e){return e.constructorDefault===void 0?e:new Fc(e.isOptional,e.isMutable,void 0,e.annotations)}function Vf(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Hf(e){return t=>{let n=[...t].sort((t,n)=>e(Ou(t))-e(Ou(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Uf=Hf(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wf(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Nn(n))return $l(e,[ad]);let r=n(e.typeParameters.map(e=>Qd(Ou(e))));return r===void 0?e:$l(e,[au(r,t)])}case`Unknown`:return $l(e,[ad]);case`ObjectKeyword`:return $l(e,[od]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Vf(e),e.recur(t,Fu);case`Union`:{let n=Uf(e.types);return n===e.types?e.recur(t):new Ml(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}globalThis.RegExp;var Gf=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Kf(e,t){return t.length>0&&(e+=`\n at ${Gt(t)}`),Error(e)}function qf(e){return`#/$defs/${tf(e)}`}var Jf=new Set([...Zo,Ho,...Go]);function Yf(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;rd(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&rd(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(rd(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))Jf.has(r)||!t.includeAnnotationKey(r)||rd(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function Xf(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=Xf(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function Zf(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}var Qf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function $f(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function ep(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var tp=`|title|description|default|examples|readOnly|writeOnly|`,np=Qf+tp;function rp(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Zf(e);if(i!==void 0||a){let r=Xf(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:$f(r.schema,tp)&&ep(o,s)?{...o,...r.schema}:rp(o,r.schema,n)}}if(n&&ep(e,r))return{...e,...t};let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function ip(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>ip(e,t)))}function ap(e){return Array.isArray(e)}function op(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=Et(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!ip(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=te(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Dr(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Et(u,ee),f={};for(let e of l)a.has(e)||h(f,e,ee(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw Kf(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=re(n[e],[`references`,e],a[1]),a}function ee(e){return uf(e,e=>{let t=nf(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(ef(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,qf(r))})}function te(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[Ho]:void 0}function ne(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>re(e,[...n,`representation`,`schemas`,t],i))??[]}),c=ap(s);c&&i.push(!1);let l=c?s[0]:s,u=Yf(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Qf:np;return[d,e._tag===`Filter`&&$f(d,f)&&(u===void 0||$f(u,tp))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=ne(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Yf(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function re(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:qf(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=ie(e,t,a),c=Yf(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&sp(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=rp(s,...i))}return o.set(e,[s,a]),p(s)}function ie(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return re(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw Kf(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(lp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Kf(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=re(e.type,[...t,`elements`,i,`type`],n),s=Yf(e.annotations,r);return s===void 0?o:p(rp(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=re(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw Kf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=Yf(s.annotations,r);h(a,c,u===void 0?l:p(rp(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=re(i.type,[...t,`indexSignatures`,r,`type`],n);Dr(a,{not:{}})&&(a=!1),l.push(a);let o=ae(i.parameter,[...t,`indexSignatures`,r,`parameter`],new Set);if(o===void 0){u=!0,n.push(!1);continue}if(o.length===0)c.push(a);else for(let e of o){let t=s[e];h(s,e,t===void 0?a:t===!1||a===!1?!1:p(rp(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(re(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>re(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=cp(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function ae(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw Kf(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ae(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=re(e,t,n);return ip(n)&&r.type===`string`&&typeof r.pattern==`string`&&$f(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lp).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=ae(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw Kf(`Invalid schema representation document`,t)}}}function sp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function cp(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function lp(e){switch(e._tag){case`Literal`:return Gf(globalThis.String(e.literal));case`String`:return Iu;case`Number`:return ol;case`TemplateLiteral`:return e.parts.map(lp).join(``);case`Union`:return`(?:${e.types.map(lp).join(`|`)})`;default:throw Kf(`Invalid schema representation document`,[])}}function up(e,t){let n=op([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var dp=({identifier:e})=>e;function fp(e){return e===void 0?void 0:{annotations:e}}function pp(e,t){let{references:n,representations:r}=mp([e],t);return{representation:r[0],references:n}}function mp(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)f(t);let s=t?.referencePolicy??dp;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:Et(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:nu(e,{identifier:n}):qo(e)===r?e:nu(e,{[Ho]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=ee(t);i.delete(e),h(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=tu(e),n=Ql(t),r=Ko(t),i=r===void 0?(t===e?void 0:Ko(e))??qo(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t)){t.isRecursive=!0;return}if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(Du(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?ee(n):u(r,t.identifier===void 0?n:l(n,t,r))}function ee(e){let t=te(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...re(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...fp(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...fp(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...fp(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...fp(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=tu(e),n=t.context?.annotations;return{isOptional:Su(t),type:m(e),...fp(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=tu(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Su(t),isMutable:Cu(t),...fp(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...fp(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...fp(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...fp(e.annotations)}}}function te(e){return e?.map(ne)??[]}function ne(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...ie(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:Et(e.checks,ne),...ie(e.annotations)}}}function re(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function ie(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(Du(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function hp(e){return ca(e)?e.value:{issues:[{message:$i(e.cause)}]}}function gp(e,t){let n=Ad(e),r={errors:`all`,...t?.parseOptions},i=Cs(t),a=e=>{let t=new Ct(`sync`),a=dr(u(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?hp(o):new Promise(e=>{a.addObserver(t=>{e(hp(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}function _p(e){return up(pp(zf(e)))}function vp(e,t){let n=_p(e);if(t===`draft-2020-12`){let e=n.schema;return Object.keys(n.definitions).length>0&&(e.$defs=n.definitions),e}if(t===`draft-07`){let e=cf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function yp(e){let t={input(t){return vp(e.ast,t.target)},output(t){return vp(Du(e.ast),t.target)}};if(Object.hasOwn(e,`~standard`)){let n=e;return`jsonSchema`in n[`~standard`]||Object.assign(n[`~standard`],{jsonSchema:t}),n}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,jsonSchema:t}})}var bp=qe(e=>xp(e));function xp(e){let t=zo(e)?.toEquivalence;if(t)return t(bc(e)?e.typeParameters.map(xp):[]);switch(e._tag){case`Never`:return cr();case`Declaration`:return Sp(e);case`Null`:case`Undefined`:case`Void`:case`Unknown`:case`Any`:case`String`:case`Number`:case`Boolean`:case`BigInt`:case`Symbol`:case`Literal`:case`UniqueSymbol`:case`ObjectKeyword`:case`Enum`:case`TemplateLiteral`:return Dr;case`Arrays`:{let t=e.elements.map(xp),n=e.rest.map(xp),[r,...i]=n,a=i.length;return Lr((o,s)=>{if(!Array.isArray(o)||!Array.isArray(s))return!1;let c=o.length;if(c!==s.length)return!1;let l=0;for(;l<Math.min(c,e.elements.length);l++)if(!t[l](o[l],s[l]))return!1;if(n.length>0){for(;l<c-a;l++)if(!r(o[l],s[l]))return!1;for(let e=0;e<a;e++)if(!i[e](o[l+e],s[l+e]))return!1}return!0})}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Dr;let t=e.propertySignatures.map(e=>xp(e.type)),n=e.indexSignatures.map(e=>xp(e.type));return Lr((r,i)=>{if(!ri(r)||!ri(i))return!1;for(let n=0;n<t.length;n++){let a=e.propertySignatures[n],o=a.name,s=Object.hasOwn(r,o),c=Object.hasOwn(i,o);if(Su(a.type)&&s!==c||s&&c&&!t[n](r[o],i[o]))return!1}for(let t=0;t<n.length;t++){let a=e.indexSignatures[t],o=sl(r,a.parameter),s=sl(i,a.parameter);if(o.length!==s.length)return!1;for(let e=0;e<o.length;e++){let a=o[e];if(!Object.hasOwn(i,a)||!n[t](r[a],i[a]))return!1}}return!0})}case`Union`:{let t=Du(e).types,n=jl(t),r=t.map((t,n)=>[kd(t),xp(e.types[n])]);return Lr((e,t)=>{let i=n(e,!1);for(let n=0;n<i.length;n++){let[a,o]=r[i[n]];if(a(e)&&a(t))return o(e,t)}return!1})}case`Suspend`:{let t;return Lr((n,r)=>(t??=bp(e.thunk()))(n,r))}}}function Sp(e){let t=e.annotations?.representation;if(t===void 0)return Dr;switch(t.id){case`effect/schema/Option`:{let[t]=Cp(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=Cp(e);return(e,r)=>e._tag===r._tag&&(e._tag===`Success`?t(e.success,r.success):n(e.failure,r.failure))}case`effect/schema/CauseReason`:{let[t,n]=Cp(e);return wp(t,n)}case`effect/schema/Cause`:{let[t,n]=Cp(e);return Tp(t,n)}case`effect/schema/Exit`:{let[t,n,r]=Cp(e),i=Tp(n,r);return(e,n)=>e._tag===n._tag&&(e._tag===`Success`?t(e.value,n.value):i(e.cause,n.cause))}case`effect/schema/ReadonlyMap`:{let[t,n]=Cp(e);return Un(t,n)}case`effect/schema/ReadonlySet`:return rn(Cp(e)[0]);case`effect/schema/RegExp`:return(e,t)=>e.source===t.source&&e.flags===t.flags;case`effect/schema/URL`:return(e,t)=>e.toString()===t.toString();default:return Dr}}function Cp(e){return e.typeParameters.map(xp)}function wp(e,t){return(n,r)=>{if(n._tag!==r._tag)return!1;switch(n._tag){case`Fail`:return e(n.error,r.error);case`Die`:return t(n.defect,r.defect);case`Interrupt`:return n.fiberId===r.fiberId}}}function Tp(e,t){let n=r(wp(e,t));return(e,t)=>n(e.reasons,t.reasons)}var Ep=o(2,(e,t)=>({...e,...t})),Dp=e=>e,Op=`~effect/Schema/SchemaError`;function kp(e){return br(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var Ap=Yd;function jp(){return(e,t,n)=>$p(new Rc(e.map(bl),e=>t(e.map(e=>$p(e))),n))}function Mp(e,t){return jp()([],()=>(t,n,r)=>e(t)?x(t):v(new ps(n,t,r)),t)}var Np=class extends zi(`SchemaError`){[Op]=Op;constructor(e){let t=Dt();Ft(0);try{super({issue:e})}finally{Ft(t)}}get message(){return As(this.issue)}toString(){return`SchemaError(${this.message})`}};function Pp(e){return kp(e)}function Fp(e){return pt(e)?Ip(e):Br(e,e=>Kr(()=>qi(e,e=>new Np(e))))}function Ip(e){return ca(e)?e:ia(qi(e.cause,e=>new Np(e)))}function Lp(e,t){let n;for(let r of e.reasons){if(!Hi(r)||!Pp(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function Rp(e){let t=Pr(e);if(ca(t))return t.value;throw Lp(t.cause,`Sync adapter can only throw schema errors`)}function zp(e,t){return gp(e,t)}function Bp(e){return yp(e)}var Vp=Dd;function Hp(e,t){let n=Ad(e,t);return(e,t)=>Fp(n(e,t))}function Up(e,t){let n=jd(e,t);return(e,t)=>Ip(n(e,t))}var Wp=Md;function D(e,t){let n=Nd(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Gp=D;function O(e,t){let n=Hp(e,t);return(e,t)=>Rp(n(e,t))}var Kp=O;function qp(e,t){let n=Pd(e,t);return(e,t)=>Fp(n(e,t))}function Jp(e,t){let n=Fd(e,t);return(e,t)=>Ip(n(e,t))}function Yp(e,t){let n=Id(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Xp=Yp;function Zp(e,t){let n=qp(e,t);return(e,t)=>Rp(n(e,t))}var Qp=Zp,$p=Qd;function em(e){return br(e,Ap)&&e[Ap]===Ap}var k=Dp(e=>$p(pu(e.ast),{schema:e})),A=Dp(e=>{let t=vm(e);return $p(hu(e.ast),{schema:t})}),tm=Dp(e=>$p(gu(e.ast),{schema:e})),nm=Dp(e=>$p(Du(e.ast),{schema:e})),rm=Dp(e=>$p(Ou(e.ast),{schema:e}));function j(e){let t=$p(new Gc(e),{literal:e,transform(n){return t.pipe(Sm(j(n),{decode:Ws(()=>n),encode:Ws(()=>e)}))}});return t}var im=$p(Uc),am=$p(Wc),om=$p(zc),sm=$p(Hc),M=$p(qc),N=$p(Xc),cm=$p(Zc),lm=$p(Qc),um=$p($c);function dm(e,t){return $p(e,{fields:t,mapFields(e,t){let n=e(this.fields);return dm(yl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e){return dm(yl(e,void 0),e)}function fm(e,t){return $p(xu(e.ast,t.ast),{key:e,value:t})}function pm(e,t){return $p(e,{elements:t,mapElements(e,t){let n=e(this.elements);return pm(xl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function mm(e){return pm(xl(e),e)}var F=Dp(e=>$p(new el(!1,[],[e.ast]),{value:e})),hm=Dp(e=>$p(new el(!1,[e.ast],[e.ast]),{value:e})),gm=Dp(e=>$p(Cl(e.ast),{schema:e}));function _m(e,t){return $p(e,{members:t,mapMembers(e,t){let n=e(this.members);return _m(Sl(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function I(e,t){return _m(Sl(e,t,void 0),e)}function L(e){let t=e.map(j);return $p(Sl(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return I(e(this.members))},pick(e){return L(e)},transform(e){return I(t.map((t,n)=>t.transform(e[n])))}})}var R=Dp(e=>I([e,om])),vm=Dp(e=>I([e,sm]));function ym(e){return $p(new Vl(()=>e().ast))}function z(...e){return t=>t.check(...e)}function bm(e,t){return n=>$p(iu(n.ast,[Gl(e,t)]),{schema:n})}function xm(e){return t=>$p(t.ast,{schema:t,identifier:e})}function Sm(e,t){return n=>$p(yu(n.ast,e.ast,t?lc(t):pc()),{from:n,to:e})}function Cm(){return(e,t)=>jm()(e,{decode:t,encode:Bs})}function wm(e,t){return n=>t?Sm(n,t)(e):Sm(n)(e)}function Tm(e){return t=>$p(vu(t.ast,e),{schema:t})}function Em(e){return Br(e,e=>Kr(()=>qi(e,e=>e.issue)))}function Dm(e,t){let n=t?.encodingStrategy===`omit`?Js():Hs();return t=>A(rm(t)).pipe(Sm(t,{decode:Ys(Em(e)),encode:n}))}function Om(e,t){return n=>nm(n).pipe(Dm(e,t),wm(A(n)))}function km(e){return j(e).pipe(Tm(x(e)))}function Am(e,t){return Mp(t=>t instanceof e,t)}function jm(){return(e,t)=>new Nc(e.ast,lc(t))}var B=Wl,Mm=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Nm(e){let t=new globalThis.RegExp(Mm);return B(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:Mm,flags:``}]},...e})}function Pm(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${S(n)})`:`new RegExp(${S(n)}, ${S(r)})`;return Yl(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var Fm=e=>e?new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;function Im(e,t){let n=Fm(e);return Pm(n,{expected:e?`a UUID v${e}`:`a UUID`,representation:{id:`effect/schema/isUUID`,payload:{version:e??null}},toJsonSchema:()=>({pattern:n.source,format:`uuid`}),toCode:()=>({runtime:e===void 0?`Schema.isUUID()`:`Schema.isUUID(${e})`}),...t})}function Lm(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Pm(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Rm(e,t,n){if(e.length===0)return t.length===0?{}:[{},!0];let r={pattern:new globalThis.RegExp(n).source};return e===t?r:[r,!0]}function zm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${Gf(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return B(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>Rm(i,e,`^${Gf(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Bm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${Gf(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return B(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>Rm(i,e,`${Gf(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Vm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(Gf(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return B(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>Rm(i,e,Gf(i)),toCode:()=>({runtime:`Schema.isIncluding(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Hm=$p(ql),Um=Kl;function Wm(e){let t=ui(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function Gm(e){let t=fn(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function Km(e){let t=ai(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function qm(e){let t=vt(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function Jm(e){let t=fn(e.order),n=ui(e.order),r=vt(e.order),i=ai(e.order),a=e.formatter??S;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return B(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function Ym(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${S(e)}`);return e}var Xm=Wm({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Ym(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${S(e)})`})})}),V=Gm({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Ym(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${S(e)})`})})}),Zm=Km({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Ym(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${S(e)})`})})}),Qm=qm({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Ym(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${S(e)})`})})}),$m=Jm({order:tn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Ym(e.minimum),maximum:Ym(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function eh(e,t){if(!globalThis.Number.isFinite(e)||e===0)throw new globalThis.RangeError(`Expected a finite non-zero number, got ${globalThis.String(e)}`);return e=globalThis.Math.abs(e),B(t=>Ya(t,e)===0,{expected:`a value that is a multiple of ${e}`,representation:{id:`effect/schema/isMultipleOf`,payload:{divisor:e}},toJsonSchema:()=>({multipleOf:e}),toCode:()=>({runtime:`Schema.isMultipleOf(${S(e)})`}),...t})}function th(e){return B(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var H=N.check(th()),nh=H.check(V(0));function rh(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${S(e)}`);return e.toISOString()}function ih(e){return`new Date(${S(e.getTime())})`}var ah=Wm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${ih(e)})`})})}),oh=Gm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${ih(e)})`})})}),sh=Km({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${ih(e)})`})})}),ch=qm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${ih(e)})`})})}),lh=Jm({order:Fn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:rh(e.minimum),maximum:rh(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${ih(e.minimum)}, maximum: ${ih(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}}),uh=Wm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${S(e)})`})})}),dh=Gm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${S(e)})`})})}),fh=Km({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${S(e)})`})})}),ph=qm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${S(e)})`})})}),mh=Jm({order:Vn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenBigInt`,payload:{minimum:e.minimum.toString(10),maximum:e.maximum.toString(10),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenBigInt({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function hh(e,t){return e=wh(e),gh(e,Math.ceil(e/2),t)}function gh(e,t,n){return B(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Vo]:!0,arbitraryConstraint:{minLength:e},...n})}function _h(e){return gh(1,1,e)}function vh(e,t){return e=wh(e),B(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Vo]:!0,arbitraryConstraint:{maxLength:e},...t})}function yh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.length>=e&&n.length<=t,{expected:e===t?`a value with a length of ${e}`:`a value with a length between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenLength`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`string`?t===0||Math.ceil(e/2)>t?{minLength:Math.ceil(e/2),maxLength:t}:[{minLength:Math.ceil(e/2),maxLength:t},!0]:n===`array`?{minItems:e,maxItems:t}:n===void 0?[{minLength:Math.ceil(e/2),maxLength:t,minItems:e,maxItems:t},!0]:[{},!0],toCode:()=>({runtime:`Schema.isBetweenLength(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function bh(e,t){return e=wh(e),B(t=>Ch(t,e)>=e,{expected:`a string with at least ${e} code points`,representation:{id:`effect/schema/isMinCodePoints`,payload:{minCodePoints:e}},toJsonSchema:()=>({minLength:e}),toCode:()=>({runtime:`Schema.isMinCodePoints(${e})`}),arbitraryConstraint:{minCodePoints:e},...t})}function xh(e,t){return e=wh(e),B(t=>Ch(t,e+1)<=e,{expected:`a string with at most ${e} code points`,representation:{id:`effect/schema/isMaxCodePoints`,payload:{maxCodePoints:e}},toJsonSchema:()=>({maxLength:e}),toCode:()=>({runtime:`Schema.isMaxCodePoints(${e})`}),arbitraryConstraint:{maxCodePoints:e},...t})}function Sh(e,t,n){return e=wh(e),t=wh(t),B(n=>{let r=Ch(n,t+1);return r>=e&&r<=t},{expected:e===t?`a string with ${e} code points`:`a string with between ${e} and ${t} code points`,representation:{id:`effect/schema/isBetweenCodePoints`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>({allOf:[{minLength:e},{maxLength:t}]}),toCode:()=>({runtime:`Schema.isBetweenCodePoints(${e}, ${t})`}),arbitraryConstraint:{minCodePoints:e,maxCodePoints:t},...n})}function Ch(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function wh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Th(e,t){return e=wh(e),B(t=>t.size>=e,{expected:`a value with a size of at least ${e}`,representation:{id:`effect/schema/isMinSize`,payload:{minSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMinSize(${e})`}),[Vo]:!0,arbitraryConstraint:{minSize:e},...t})}function Eh(e,t){return e=wh(e),B(t=>t.size<=e,{expected:`a value with a size of at most ${e}`,representation:{id:`effect/schema/isMaxSize`,payload:{maxSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMaxSize(${e})`}),[Vo]:!0,arbitraryConstraint:{maxSize:e},...t})}function Dh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.size>=e&&n.size<=t,{expected:e===t?`a value with a size of ${e}`:`a value with a size between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenSize`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenSize(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function Oh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e},...t})}function kh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length<=e,{expected:`a value with at most ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMaxProperties`,payload:{maxProperties:e}},toJsonSchema:({type:t})=>t===`object`?{maxProperties:e}:[{maxProperties:e},!0],toCode:()=>({runtime:`Schema.isMaxProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function Ah(e,t,n){return e=wh(e),t=wh(t),B(n=>Reflect.ownKeys(n).length>=e&&Reflect.ownKeys(n).length<=t,{expected:e===t?`a value with exactly ${e===1?`1 entry`:`${e} entries`}`:`a value with between ${e} and ${t} entries`,representation:{id:`effect/schema/isBetweenProperties`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`object`?{minProperties:e,maxProperties:t}:[{minProperties:e,maxProperties:t},!0],toCode:()=>({runtime:`Schema.isBetweenProperties(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var jh=M.check(_h());globalThis.RegExp,globalThis.URL;var Mh=M.annotate({expected:`a string that will be decoded as a Date`}),Nh=Mp(e=>e instanceof globalThis.Date&&!globalThis.Number.isNaN(e.getTime()),{representation:{id:`effect/schema/Date`,payload:null},toCode:()=>({runtime:`Schema.Date`,Type:`globalThis.Date`}),expected:`a valid Date`,toCodecJson:()=>jm()(Mh,gc)}),Ph=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function U(e,t){return Ph.pipe(Sm(e,vc(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var Fh=M.annotate({expected:`a string that will be decoded as a number`}).pipe(Sm(N,mc)),Ih=M.check(Nm()),Lh=M.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(Sm(Ih,dc())),Rh=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),zh=Am(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>jm()(Rh,_c)}),Bh=uc({decode:(e,t)=>Wr(Co(e),{onNone:()=>v(new ms({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>x(wo(e))}),encode:e=>x(To(e))}),Vh=-864e13,Hh=864e13;function Uh(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function Wh(e,t){return H.check($m({minimum:e,maximum:t}))}var Gh=Mp(e=>bo(e)&&xo(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=Uh(e,Vh,Hh);return Cm()(Wh(t,n),Ws(So))},toCodecJson:()=>jm()(M,Bh),toFormatter:()=>e=>e.toString()}),Kh=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(Sm(Gh,Bh));function qh(e){return bp(e.ast)}function Jh(e,t){return pp(e.ast,t)}function Yh(e,t){return up(pp(zf(e.ast),t),t)}var Xh=Rf,Zh=$p(nu(id,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),Qh=fm(M,Zh),$h=e=>crypto.getRandomValues(new Uint8Array(e)),eg=(e,t,n)=>{let r=256-256%e.length;if(r===256){let r=e.length-1;return(i=t)=>{if(!i)return``;let a=``;for(;;){let t=n(i),o=i;for(;o--;)if(a+=e[t[o]&r],a.length>=i)return a}}}let i=Math.ceil(409.6*t/r);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(t[s]<r&&(o+=e[t[s]%e.length],o.length>=a))return o}}},tg=(e,t=21)=>eg(e,t|0,$h),ng=`abcdefghijklmnopqrstuvwxyz0123456789`;function rg(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return tg(ng,e)()}var ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ag=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,og=w().min(1).max(64).regex(ig),sg=w().min(1).max(64).regex(ig),cg=w().min(1).max(32).regex(ag),lg=Qt({prefix:cg}),ug=Qt({family:og,version:yr(1),kinds:si(sg,lg)}).superRefine((e,t)=>{let n=Object.entries(e.kinds);if(n.length<1||n.length>64){t.addIssue({code:`custom`,message:`Identifier families must declare between one and 64 kinds`});return}let r=new Set;for(let[,e]of n){if(r.has(e.prefix)){t.addIssue({code:`custom`,message:`Identifier kind prefixes must be distinct`});return}r.add(e.prefix)}}),dg=w(),fg=/^[a-z0-9]+$/,pg=new TextEncoder;function mg(e){return e===32||e>=9&&e<=13}function hg(e){let t=0,n=e.length;for(;t<n&&mg(e.charCodeAt(t));)t+=1;for(;n>t&&mg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function gg(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&fg.test(n)}let r=_(()=>jr(e=>{let t=dg.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=pg.encode(o).byteLength,c=r.safeParse(o),l=o.startsWith(t)?o.slice(t.length):void 0;if(s<3||s>96)a=`bounds`;else if(l!==void 0&&Array.from(l).length!==21)a=`bounds`;else if(c.success)return{ok:!0,value:c.data};else a=n(hg(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=_(()=>dg.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),ur)}));function o(){let n;try{n=rg(21)}catch{throw e.entropyUnavailable()}return r.parse(`${t}${n}`)}return{family:e.family,kind:e.kind,version:1,generate:o,schema:a,parse:i,is:e=>i(e).ok}}var _g=si(w(),Qt({family:w(),kind:w(),version:yr(1),generate:ct(),schema:t(Ut),parse:ct(),is:ct()})),vg=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},yg=class extends Error{name=`CairnGenerationError`;code=`entropy_unavailable`;family;kind;version=1;constructor(e){super(`Cairn entropy source is unavailable`),this.family=e.family,this.kind=e.kind}};function bg(e){let t;try{t=ug.safeParse(e)}catch{throw new vg}if(!t.success)throw new vg;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=gg({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new yg({family:n.family,kind:t})})}let i=jr(e=>{let t=_g.safeParse(e);if(!t.success)return!1;let r=Object.entries(t.data);return r.length===Object.keys(n.kinds).length&&r.every(([e,t])=>Object.hasOwn(n.kinds,e)&&t.kind===e&&t.family===n.family)}).safeParse(r);if(!i.success)throw new vg;return i.data}var xg=_(()=>ln({id:w().min(1).max(256),name:w().min(1).max(128),kind:yr(`agent`).optional()})),Sg=_(()=>w().min(1).max(256)),Cg=_(()=>ln({agentId:Sg,sessionId:Sg,commandId:Sg,outcome:Jt([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:w().min(1).max(200).optional(),waitingOnYou:Er(ln({itemId:Sg,kind:w().min(1).max(64),summary:w().min(1).max(200)})).min(1).max(8).optional()})),wg=ln({author:xg.optional(),sourceRequestId:Sg.optional(),delegation:ln({ancestors:Er(Sg).max(8),maxDepth:Mn().int().min(1).max(8),steer:yr(!0).optional(),goal:Qr([w().min(1).max(4e3),yr(!1)]).optional(),reply:Cg.optional()}).optional()});function Tg(e){let t=wg.safeParse(e);return t.success?t.data.author:void 0}var Eg=Symbol.for(`effect/MutableList/Empty`),Dg=()=>({head:void 0,tail:void 0,length:0}),Og=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},kg=()=>({array:[],mutable:!0,offset:0,next:void 0}),Ag=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=kg(),e.tail=e.tail.next):e.head=e.tail=kg(),e.tail.array.push(t),e.length++},jg=e=>{e.head=e.tail=void 0,e.length=0},Mg=(e,t)=>{if(t=_i(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return jg(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?jg(e):Og(e),n;i=i.next}return jg(e),n},Ng=e=>Mg(e,e.length),Pg=e=>{if(!e.head)return Eg;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:jg(e):Og(e),t},Fg=`~effect/Queue`,Ig=`~effect/Queue/Enqueue`,Lg=`~effect/Queue/Dequeue`,Rg={_A:He,_E:He},zg={[Fg]:Rg,[Ig]:Rg,[Lg]:Rg,...de,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:n_(this)}}},Bg=e=>Se(t=>{let n=Object.create(zg);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=Dg(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},li(n)}),Vg=e=>Bg({capacity:e}),Hg=e=>Bg({capacity:e,strategy:`dropping`}),Ug=o(2,(e,t)=>ii(()=>Wg(e,t)?i_:e.state._tag===`Open`&&e.strategy===`suspend`?p_(e,t):r_)),Wg=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Pg(e.messages),Ag(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(Ag(e.messages,t),s_(e),!0):(Ag(e.messages,t),c_(e),!0):!1,Gg=o(2,(e,t)=>Kg(e,c(t))),Kg=o(2,(e,t)=>_t(()=>qg(e,t))),qg=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=De(t),r=Fe(n,a_);return e.state.offers.size===0&&e.messages.length===0?(y_(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},c_(e),!0)},Jg=e=>qg(e,c(ti())),Yg=e=>_t(()=>Xg(e)),Xg=e=>{if(e.state._tag===`Done`)return!1;jg(e.messages);let t=e.state.offers;y_(e,e.state._tag===`Open`?o_:e.state.exit);for(let e of t)h_(e);return!0},Zg=e=>u_(()=>{if(e.state._tag===`Done`)return Qa(e.state.exit,()=>li([]));let t=v_(e);return __(e),li(t)}),Qg=e=>$g(e,1,1/0),$g=o(3,(e,t,n)=>(t=_i(t),n=_i(n),u_(()=>l_(e,t,n)??Qn(f_(e,()=>d_(e,t)),$g(e,t,n))))),e_=e=>u_(()=>t_(e)??Qn(f_(e,()=>d_(e,1)),e_(e))),t_=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Pg(e.messages);return __(e),ze(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=g_(e.state.offers);return __(e),ze(t)}},n_=e=>e.state._tag===`Done`?0:e.messages.length,r_=ze(!1),i_=ze(!0),a_=he(ti()),o_=p(),s_=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(be),e.messages.length===0))break}},c_=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,s_(e)},0))},l_=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return ze([]);if(!d_(e,t))return;let r=e.messages.length>0?Mg(e.messages,n):[g_(e.state.offers)];return __(e),ze(r)},u_=jt({op:`QueueTake`,[Ye](e){let t=this[et]();return pi(t)?t[Ye](e):t}}),d_=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,f_=(e,t)=>Jn(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(be);let r={ready:t,resume:n};return e.state.takers.add(r),_t(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),p_=(e,t)=>Jn(n=>Wg(e,t)?n(i_):m_(e,{_tag:`Single`,message:t,resume:n})),m_=(e,t)=>{if(e.state._tag!==`Open`)return h_(t);let n=e.state.offers;return n.add(t),_t(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&y_(e,e.state.exit))})},h_=e=>e._tag===`Single`?e.resume(r_):e.resume(ze(e.remaining.slice(e.offset))),g_=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(i_),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(ze([]))),n},__=e=>{if(e.state._tag===`Done`)return $a(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(y_(e,e.state.exit),$a(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)Ag(e.messages,t.message),e.state.offers.delete(t),t.resume(i_);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;Ag(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(ze([]))}let r=e.state;if(r._tag===`Done`)return $a(r.exit.cause)}return!1},v_=e=>{if(e.messages.length>0){let t=Ng(e.messages);return __(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[g_(e.state.offers)];return __(e),t}return[]},y_=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},b_=wr,x_=Kt,S_=Me,C_=Rr,w_=Vt,T_=Mr,E_=hr,D_=e=>new k_(e),O_=(e,t,n)=>Jn(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),_t(()=>{e.waiters.delete(i)})}),k_=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=ii(()=>this.free<e?O_(this,e,t):(this.taken+=e,li(e)));return t}takeIfAvailable(e){return ii(()=>this.free<e?li(!1):(this.taken+=e,li(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Se(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ei))}release(e){return Se(t=>li(this.releaseUnsafe(t,e)))}get releaseAll(){return Se(e=>li(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>te(n=>{let r=ii(()=>{if(this.free<e){let t=O_(this,e,ei);return Tn(n(t),()=>r)}return this.taken+=e,_n(n(t),()=>{this.releaseUnsafe(Rr(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>te(n=>this.free<e?dn:(this.taken+=e,_n(n(l(t)),()=>{this.releaseUnsafe(Rr(),e)},!0)))}},A_=e=>_t(()=>new k_(e)),j_=`~effect/Channel`,M_=e=>br(e,j_),N_={[j_]:{_Env:He,_InErr:He,_InElem:He,_OutErr:He,_OutElem:He},pipe(){return Le(this,arguments)}},P_=e=>{let t=Object.create(N_);return t.transform=(t,n)=>Br(e(t,n),e=>x(Zt(e))),t},F_=(e,t)=>P_((n,r)=>T(R_(e)(n,r),e=>t(e,r))),I_=e=>P_((t,n)=>e),L_=e=>P_(mt(function*(t,n){let r=ka(n),i=e=>Aa(r,ro(e)),a=yield*_e(e(t,n,r),i);return _e(a,i)})),R_=e=>e.transform,z_=4096,B_=(e,t,n)=>Bg({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(In(t=>Da(e,Yg(t))),In(n=>Ta(t(n),e).pipe(Br(e=>Kg(n,e)),Ze(e)))),V_=(e,t)=>P_((n,r)=>we(B_(r,e,t),Qg)),H_=e=>P_((t,n)=>sr(()=>R_(e())(t,n))),U_=e=>I_(y(()=>{let t=e();return sr(()=>{let e=t.next();return e.done?ta(e.value):x(e.value)})})),W_=(e,t=z_)=>{let n=vi(t);return I_(y(()=>{let t=e(),r=Cn();return sr(()=>{if(r._tag===`Some`)return ta(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return ta(n.value);r=Sr(n.value);break}e.push(n.value)}return x(e)})}))},G_=(e,t=z_)=>W_(()=>e[Symbol.iterator](),t),K_=e=>X_(x(e)),q_=I_(x(ta())),J_=e=>I_(x(v(e))),Y_=e=>I_(Zt(e)),X_=e=>I_(y(()=>{let t=!1;return sr(()=>t?ta():(t=!0,e))})),Z_=e=>I_(x(Qg(e))),Q_=(e,t)=>P_(mt(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*Da(r,qt(()=>i.return()))),T(pn({try:()=>i.next(),catch:t}),e=>e.done?ta(e.value):x(e.value))})),$_=(e,t)=>ev(Q_(e,t),Pt),ev=o(2,(e,t)=>F_(e,e=>y(()=>{let n=0;return we(e,e=>t(e,n++))}))),tv=e=>e===void 0||e!==`unbounded`&&e<=1,nv=o(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?rv(e,t):iv(e,t,n)),rv=(e,t)=>P_((n,r)=>{let i=0;return we(R_(e)(n,r),T(e=>t(e,i++)))}),iv=(e,t,n)=>L_(mt(function*(r,i,a){let o=0,s=yield*R_(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Vg(0);yield*Da(a,Yg(l));let u=kr(yield*On()),d=w_(a);if(n.unordered){let e=D_(c),n=Xn(e.release(1)),r=kt({onFailure:e=>T(Kg(l,e),n),onSuccess:e=>T(Ug(l,e),n)});yield*e.take(1).pipe(T(()=>s),T(e=>{let n=o++;return d(u(r(sr(()=>t(e,n))))),C}),bt({disableYield:!0}),Br(t=>e.withPermits(c-1)(Kg(l,t))),Ze(a))}else{let e=yield*Vg(c-2);yield*Da(a,Yg(e)),yield*e_(e).pipe(ni,T(e=>Ug(l,e)),bt({disableYield:!0}),Br(e=>Kg(l,e)),Ze(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,qg(l,e.cause))};yield*s.pipe(T(i=>{if(n)return Zt(n);let a=o++,s=u(sr(()=>t(i,a)));return d(s),s.addObserver(r),Ug(e,x_(s))}),bt({disableYield:!0}),Br(t=>Ug(e,ia(t)).pipe(g(Kg(e,t)))),Ze(a))}return e_(l)})),av=o(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?ov(e,t):sv(e,t,n)),ov=(e,t)=>P_((n,r)=>we(R_(e)(n,r),e=>{let i,a,o=T(e,e=>(a??=ka(r),cn(R_(t(e))(n,a),e=>(i=s(e),i)))),s=Qa(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Aa(a,sa);return a=void 0,T(t,()=>o)});return sr(()=>i??o)})),sv=(e,t,n)=>e.pipe(ev(t),mv(n)),cv=e=>av(e,He),lv=e=>F_(e,e=>{let t,n=0,r=sr(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return x(e[0]);default:return t=e,x(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),x(i)});return x(r)}),uv=o(2,(e,t)=>F_(e,e=>x(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return At(i)?x(i):T(e,n)})))),dv=o(2,(e,t)=>P_((n,r)=>{let i=ka(r);return we(R_(e)(n,i),e=>{let a=e.pipe(Br(e=>{if($a(e))return Zt(e);let o=i;return i=ka(r),Aa(o,ia(e)).pipe(g(R_(t(e))(n,i)),T(e=>(a=e,e)))}));return sr(()=>a)})})),fv=o(3,(e,t,n)=>dv(e,e=>{let r=t(e);return Ae(r)?Y_(r.failure):n(r.success,e)})),pv=o(2,(e,t)=>fv(e,Yi,e=>t(e))),mv=o(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>L_(mt(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:D_(s),l=yield*E_(!0),u=new Set,d=yield*Vg(t);yield*Da(o,Yg(d));let f=yield*R_(e)(i,a);return yield*b(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*ce(f),yield*Dn(c.take(1),g(x_(e),Nt))));let t=e===void 0?yield*f:yield*x_(e),n=ka(o),r=yield*R_(t)(i,n);for(;u.size>=s;){let e=yi(u);u.delete(e),u.size===0&&(yield*l.open),yield*S_(e)}let a=yield*r.pipe(In(()=>fe),T(e=>Ug(d,e)),bt({disableYield:!0}),_e(mt(function*(e){let t=ro(e),r=yield*Ln(Aa(n,t));if(!u.has(a))return;let i=fa([t,r]);la(i)&&(yield*Kg(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),ce);l.closeUnsafe(),u.add(a)}}).pipe(Br(e=>{let t=to(e);return Wt(t)?l.whenOpen(Kg(d,e)):Kg(d,e)}),Ze(o)),e_(d)}))),hv=o(e=>M_(e[0])&&M_(e[1]),(e,t,n)=>L_(mt(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Vg(0);yield*Da(a,Yg(s));let c=0;function l(e,t){if(c++,!$a(t))return Kg(s,t);switch(o){case`both`:return c===2?Kg(s,t):C;case`left`:case`right`:return e===o?Kg(s,t):C;case`either`:return Kg(s,t)}}let u=(e,t,n)=>R_(t)(r,n).pipe(T(e=>e.pipe(T(e=>Ug(s,e)),bt)),_e(t=>Cr(ro(t),e=>Aa(n,e)).pipe(kt({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Ze(a));return yield*u(`left`,e,ka(a)),yield*u(`right`,t,ka(a)),e_(s)}))),gv=e=>P_((t,n)=>{let r;return x(sr(()=>r||e.pipe(Ta(n),T(e=>R_(e)(t,n)),T(e=>r=e))))}),_v=o(2,(e,t)=>hv(e,I_(x(T(t,ta))),{haltStrategy:`either`})),vv=o(2,(e,t)=>L_((n,r,i)=>Ea(i,t).pipe(g(R_(e)(n,r))))),yv=o(2,(e,t)=>vv(e,e=>t)),bv=(e,t,n)=>sr(()=>{let r=wa(),i=R_(e)(ta(),r);return Qa(T(i,t),n||x).pipe(Ne(e=>Aa(r,e)))}),xv=o(2,(e,t)=>bv(e,e=>bt(T(e,t),{disableYield:!0}))),Sv=mt(function*(e){let t=D_(1),n=yield*On(),r=Ee(n,Sa);return(yield*R_(e)(ta(),r)).pipe(st(n),t.withPermits(1))},Br(e=>x(Zt(e)))),Cv=(e,t)=>R_(e)(ta(),t),wv=`~effect/Stream`,Tv={_R:He,_E:He,_A:He},Ev=function(e){this.channel=e};Ev.prototype={[wv]:Tv,pipe(){return Le(this,arguments)}};var Dv=e=>new Ev(e),Ov=`~effect/Sink`,kv={_A:He,_In:He,_L:He,_E:He,_R:He},Av={[Ov]:kv,pipe(){return Le(this,arguments)}},jv=e=>{let t=Object.create(Av);return t.transform=e,t},Mv=((e,t,n)=>jv(r=>{let i=e(),a;return t(i)?r.pipe(T(e=>{for(let r=0;r<e.length;r++)if(i=n(i,e[r]),!t(i))return r+1<e.length&&(a=e.slice(r+1)),ta();return C}),bt({disableYield:!0}),Qa(()=>x([i,a]))):x([i])}))(Cn,on,(e,t)=>Sr(t)),Nv=()=>Mv,Pv=`~effect/Stream`,Fv=e=>br(e,Pv),Iv=Dv,Lv=e=>Iv(X_(we(e,Pt))),Rv=e=>Bv(x(T(e,()=>ta()))),zv=e=>Bv(x(we(e,Pt))),Bv=e=>Iv(I_(e)),Vv=(e,t)=>Iv(P_((n,r)=>T(Cv(e.channel,r),e=>t(e,r)))),Hv=e=>e.channel,Uv=(e,t)=>Iv(V_(e,t)),Wv=Iv(q_),Gv=e=>Iv(K_(Pt(e))),Kv=e=>Iv(H_(()=>e().channel)),qv=e=>Iv(J_(e)),Jv=e=>Iv(Y_(e)),Yv=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Xv(e):Iv(G_(e,t?.chunkSize)),Xv=e=>At(e)?Iv(K_(e)):Wv,Zv=e=>Iv(Z_(e)),Qv=(e,t)=>Iv($_(e,t)),$v=(e,t)=>Bv(y(()=>{let n=e,r=!1;return sr(function e(){return r?ta():T(t(n),([t,i])=>(on(i)?r=!0:n=i.value,At(t)?x(t):e()))})})),ey=e=>Iv(gv(we(e,Hv))),ty=o(2,(e,t)=>Kv(()=>{let n=0;return Iv(ev(e.channel,Et(e=>t(e,n++))))})),ny=o(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,nv(t,n),ev(Pt),Iv)),ry=e=>e.pipe(ty(n),my(e=>Gv(ve(e)))),iy=o(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,av(e=>t(e).channel,n),Iv)),ay=o(2,(e,t)=>{let n=ue(t.duration);if(!ae(n))return e;if($e(n))return Kv(t.orElse);let r=Symbol();return py(Kv(()=>{let t=C_().getRef(ja),i=s(n),a,o=T_(!1);return uy(Vv(e,(e,n)=>sr(()=>(a=t.currentTimeMillisUnsafe()+i,o.openUnsafe(),e)).pipe(we(e=>(o.closeUnsafe(),a=void 0,e)),x)),Rv(b(function*(){for(;;)if(yield*o.await,a!==void 0&&(yield*jn(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*vr(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Jv(e))}),oy=e=>iy(e,Yv),sy=o(2,(e,t)=>{let n=Iv(cv(U_(()=>ly(e,t))));return cy.set(n,[e,t]),n}),cy=new WeakMap;function*ly(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=cy.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var uy=o(e=>Fv(e[0])&&Fv(e[1]),(e,t,n)=>Iv(hv(Hv(e),Hv(t),n))),dy=o(2,(e,t)=>Iv(uv(Hv(e),t))),fy=o(2,mt(function*(e,t){let n,r=yield*Sv(e.channel),i=Br(r,e=>(n=e,Zt(e))),[a,o]=yield*Gr(e=>t.transform(i,e)),s=n?Wv:Bv(x(r));return o&&(s=sy(Xv(o),s)),[a,s]})),py=o(2,(e,t)=>e.channel.pipe(dv(e=>t(e).channel),Iv)),my=o(2,(e,t)=>Iv(pv(e.channel,e=>t(e).channel))),hy=o(e=>Fv(e[0]),(e,t,n)=>Vv(e,(e,r)=>y(()=>{let r=0,i=!1;return T(sr(()=>i?ta():e),e=>{let a=e.findIndex(e=>t(e,r++));if(a>=0){i=!0;let t=e.slice(0,n?.excludeLast?a:a+1);return At(t)?x(t):ta()}return x(e)})}))),gy=o(2,(e,t)=>Iv(_v(e.channel,t))),_y=o(2,(e,t)=>Iv(yv(e.channel,t))),vy=o(2,(e,t)=>xv(e.channel,e=>{let n=0;return wt({while:()=>n<e.length,body:()=>t(e[n++]),step:Qe})})),yy=o(2,(e,t)=>({[Symbol.asyncIterator](){let n=sn(t),r=kr(t),i=wa(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Ar(g(t?S_(t):C,Aa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(nt(`Suppressed error while closing Stream async iterator`,e))}};return{async next(){if(c)return c;if(o){let e=o.next();if(!e.done)return e;o=void 0}let t=r(a??T(Cv(e.channel,i),e=>(a=e,e)));s=t;let d=await n(b_(t));if(s===t&&(s=void 0),ca(d))return o=d.value[Symbol.iterator](),o.next();if($a(d.cause))return l(sa);if(c&&Ki(d.cause))return c;throw await u(d),Ji(d.cause)},return(){return l(sa)},async throw(e){throw await u(oa(e)),e}}}})),by=e=>yy(e,me()),xy=15e3,Sy=45e3,Cy=jh.check(vh(256)),wy=H.check(V(0)),Ty=P({agentId:Cy,sessionId:Cy,name:Cy}),Ey=P({by:Ty,reason:L([`escalated`,`sender_archived`,`sender_absent`]),note:k(M.check(vh(1e3)))}),Dy=P({id:Cy,kind:jh.check(vh(64)),summary:jh.check(vh(200)),since:wy,expiresAt:A(wy),inbox:A(j(!1)),waitingOn:A(Ty),escalated:A(Ey)}),Oy=Dy.mapFields(e=>({...e,extensionId:Cy})),ky=4096,Ay=F(Oy).check(vh(64)),jy=M.pipe(z(hh(1)),z(vh(256))),My=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Ny=P({providerId:jy,modelId:jy,reasoning:A(L(My))}),Py=O(R(Ny)),Fy=O(U(R(Ny))),Iy=L([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),Ly=L([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),Ry=M.pipe(z(hh(1)),z(vh(256))),zy=P({_tag:j(`ShiitakeError`),boundary:Iy,cause:Ly,message:M,requestId:k(Ry)}),W=class extends Error{boundary;requestId;_tag=`ShiitakeError`;cause;underlying;constructor(e,t,n,r,i){super(n),this.boundary=e,this.requestId=r,this.name=`ShiitakeError`,this.cause=t,this.underlying=i}},By=new TextEncoder;function Vy(e){return M.check(hh(1),vh(e),B(t=>By.encode(t).byteLength<=e))}var Hy=/\p{Cs}/u,Uy=Vy(256).check(B(e=>!Hy.test(e))),Wy=Vy(262144),Gy=P({type:j(`image`),data:M.check(hh(1),vh(1048576),Lm()),mimeType:M.check(B(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),Ky=F(Gy).check(hh(1),vh(8)),qy=L([`steer`,`followUp`]),Jy=Uy,Yy=D(P({commandId:Uy,timeoutMs:H.check(V(0),Qm(3e4))}),{onExcessProperty:`error`});D(P({commandId:Uy,timeoutMs:Fh.check(th(),$m({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Xy=D(Vy(512)),Zy=P({requestId:Uy}),Qy=P({delivery:qy,requestId:Uy,type:j(`prompt`),text:M.check(vh(262144),B(e=>By.encode(e).byteLength<=262144)),images:k(Ky)}).check(B(e=>(e.text.length>0||(e.images?.length??0)>0)&&By.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),$y=P({type:j(`abort`)}),eb=P({commandId:Uy,onlyIfPending:A(cm),type:j(`cancel`)}),tb=P({type:j(`operator`),requestId:Uy,author:L([`operator`,`party`]),text:Wy}),nb=P({type:j(`branch`),entryId:Uy}),rb=P({type:j(`fork`),entryId:Uy}),ib=M.check(hh(1),vh(4096)),ab=P({type:j(`compact`),requestId:Uy,instructions:k(ib)}),ob=I([Qy,ab]),sb=M.check(B(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),cb=I([Qy,$y,eb,nb,rb,tb,ab,P({type:j(`title`),title:R(sb)})]),lb=P({command:cb}),ub=P({includeSandboxFailures:A(cm),limit:A(H.check($m({minimum:1,maximum:200}))),before:A(Vy(512))}),db=P({includeSandboxFailures:A(j(`true`)),limit:A(Fh.check(th(),$m({minimum:1,maximum:200}))),before:A(Vy(512))}),fb=P({includeSandboxFailures:A(cm),after:A(M)}),pb=P({includeSandboxFailures:A(j(`true`)),mode:A(j(`subscribe`)),after:A(M),limit:A(Fh.check(th(),$m({minimum:1,maximum:200})))}),mb={onExcessProperty:`error`},hb=D(Jy,mb),gb=D(Zy,mb),_b=D(ob,mb);D(Uy);var vb=D(cb,mb);D(lb,mb);var yb=D(I([ub,sm]),mb);D(db,mb);var bb=D(fb,mb);D(pb,mb);function xb(e){let t=hb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session id is invalid`);return t.success}function Sb(e){let t=Xy(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function Cb(e){let t=gb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function wb(e){let t=yb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Read options are invalid`);let n=t.success??{},r={limit:n.limit??200};return n.before!==void 0&&(r={...r,before:n.before}),n.includeSandboxFailures!==void 0&&(r={...r,includeSandboxFailures:n.includeSandboxFailures}),Object.freeze(r)}function Tb(e){let t=bb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Subscribe options are invalid`);let n={};return t.success.after!==void 0&&(n={...n,after:t.success.after}),t.success.includeSandboxFailures!==void 0&&(n={...n,includeSandboxFailures:t.success.includeSandboxFailures}),Object.freeze(n)}function Eb(e,t){if(Ae(e))throw new W(`contract`,`invalid`,t);return e.success}var Db=bn();function Ob(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function kb(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e.charCodeAt(r)-t.charCodeAt(r);if(n!==0)return n}return e.length-t.length}function Ab(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[_./:-]/g,` `).toLowerCase().trim()}function jb(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var Mb=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function Nb(e){return Mb.has(e)}function Pb(e){let t=[],n=n=>{n!==e&&n.length>=3&&!t.includes(n)&&t.push(n)};return e.endsWith(`ing`)&&e.length>4&&n(e.slice(0,-3)),e.endsWith(`ed`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`ation`)&&e.length>6&&n(`${e.slice(0,-3)}e`),e.endsWith(`ies`)&&e.length>4&&(n(e.slice(0,-3)),n(`${e.slice(0,-3)}y`)),e.endsWith(`es`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`s`)&&!e.endsWith(`ss`)&&e.length>3&&n(e.slice(0,-1)),t}function Fb(e){let t=8997,n=33826,r=40164,i=52210;for(let a=0;a<e.length;a+=1){let o=t^e.charCodeAt(a),s=o*435,c=n*435+(s>>>16),l=r*435+(c>>>16)+(o<<8),u=i*435+(l>>>16)+(n<<8);t=s&65535,n=c&65535,r=l&65535,i=u&65535}return i.toString(16).padStart(4,`0`)+r.toString(16).padStart(4,`0`)+n.toString(16).padStart(4,`0`)+t.toString(16).padStart(4,`0`)}function Ib(e){return e.slice(e.indexOf(`.`)+1)}function Lb(e){return e.slice(0,e.indexOf(`.`))}var Rb=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,zb=1e3,Bb=221;function Vb(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Vb(r,t+1));return n}if(!Ob(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Vb(r,t+1));return n}var Hb=_(()=>si(w(),bn()).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:`custom`,message:`Sample exceeds the entry bound`}),JSON.stringify(e).length>4e3&&t.addIssue({code:`custom`,message:`Sample exceeds the byte bound`}),Vb(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Ub=_(()=>Qt({query:w().max(200),maxResults:Mn().int().min(1).max(50).default(50)})),Wb=_(()=>Qt({path:w().max(160),detail:Jt([`index`,`full`]).default(`full`),methods:Er(w().max(80)).max(50).optional()})),Gb=Qt({cursor:w().max(400).optional(),limit:Mn().int().min(1).max(50).default(50),namespace:w().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),Kb=_(()=>Qt({path:w().max(160),capabilityNotes:w().max(500).optional()})),qb=Qt({path:w().max(160),description:w().max(1e3).optional(),score:Mn().min(0).max(Bb),matchReason:w().max(500).optional(),sample:Hb.optional(),capabilityNotes:w().max(500).optional(),peers:Er(Kb).max(1e3).optional()}),Jb=_(()=>Qt({results:Er(qb).max(50),total:Mn().int().min(0).max(zb),truncated:pr(),topScore:Mn().min(0).max(Bb),margin:Mn().min(0).max(Bb),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)})),Yb=Qt({results:Er(qb).max(50),total:Mn().int().min(0).max(zb),nextCursor:w().max(400).nullable(),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)}),Xb=_(()=>Qt({path:w().max(160),description:w().max(1e3).optional(),types:w().max(2e4),inputSchema:bn().refine(e=>JSON.stringify(e).length<=2e4&&Vb(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:Jt([`module`,`operation`]),usage:w().max(300).optional()}));_(()=>Qt({code:Jt([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:w().max(1e3)}));var Zb=_(()=>Qt({"~standard":Qt({jsonSchema:Qt({input:t(Function),output:t(Function)})})})),Qb=_(()=>jr(e=>Zb.safeParse(e).success,`Expected a Standard JSON Schema`)),$b=_(()=>Qt({path:w().min(3).max(160).regex(Rb),description:w().max(1e3).optional(),input:Qb,output:Qb.optional(),capabilityNotes:w().max(500).optional(),instructions:w().max(1e3).optional()})),ex=_(()=>Qt({revision:w().min(1).max(160),operations:Er($b).max(zb)})),tx=class extends Error{code;failure;constructor(e,t,n){let r=t.slice(0,1e3);super(r,n),this.name=`ForageError`,this.code=e,this.failure={code:e,message:r}}},nx=Qr([ir({$ref:w().optional(),$defs:si(w(),xt()).optional(),definitions:si(w(),xt()).optional(),const:xt().optional(),enum:Er(xt()).optional(),oneOf:Er(xt()).optional(),anyOf:Er(xt()).optional(),allOf:Er(xt()).optional(),type:Qr([w(),Er(w())]).optional(),properties:si(w(),xt()).optional(),additionalProperties:xt().optional(),required:Er(w()).optional(),prefixItems:Er(xt()).optional(),items:xt().optional(),examples:Er(xt()).optional(),default:xt().optional()}),pr()]),rx=new WeakMap;function ix(e,t){let n=rx.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`})}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}sx(i);let a={raw:i};return n===void 0&&(n={},rx.set(e,n)),n[t]=a,a}function ax(e,t){return ix(e,t).raw}function ox(e,t){let n=ix(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function sx(e){let t=nx.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var cx=256,lx=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function ux(e,t,n){let r=lx.exec(e)?.[1];if(r===void 0||n.expanding.has(r))return`unknown`;let i=n.definitions[r];if(i===void 0)return`unknown`;if(n.budget.expansions+=1,n.budget.expansions>cx)throw new tx(`invalid_input`,`Schema references expand more than ${String(cx)} times; flatten its shared definitions`);return fx(sx(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function dx(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=lx.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&dx(sx(r),{definitions:t.definitions,expanding:new Set([...t.expanding,n]),budget:t.budget})}return e.const===void 0?e.enum!==void 0&&e.enum.length>1||e.oneOf!==void 0&&e.oneOf.length>1||e.anyOf!==void 0&&e.anyOf.length>1:!1}function fx(e,t,n){if(t>12||e===!0||e===!1)return`unknown`;let r=n??{definitions:{...e.definitions,...e.$defs},expanding:new Set,budget:{expansions:0}};if(e.$ref)return ux(e.$ref,t,r);if(e.const!==void 0)return JSON.stringify(e.const);if(e.enum)return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(e.oneOf)return e.oneOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=sx(e),i=fx(n,t+1,r);return dx(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>kb(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${fx(sx(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
4
|
-
${n.map(([e,n])=>{let a=
|
|
3
|
+
`);n=Ms(e)??Es(Xo(e.ast),e);break;default:n=xs(e)}return t?`${n}\n at ${t}`:n}function Ms(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Ms(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Ns(e){let t;for(let n of e.reasons){if(!Hi(n)||!is(n.error))return;t??=n.error}return t}function Ps(e,t){let n=Ns(e);if(n===void 0)throw Error(t,{cause:e});return n}var Fs=e=>Eo(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Is=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Length should be a multiple of 4, but is ${n}`}));if(!/^[-_A-Z0-9]*?={0,2}$/i.test(t))return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Invalid input`}));let r=n%4==2?`${t}==`:n%4==3?`${t}=`:t;return r=r.replace(/-/g,`+`).replace(/_/g,`/`),Do(r)},Ls=e=>Object.assign(Object.create(Te),e);function Rs(e){return qs((t,n)=>v(e(t,n)))}function zs(e){return Rs((t,n)=>{let r={message:e(t)};return Nr(t)?new hs(r,t.value,n):new hs(r)})}var Bs=zs(()=>`Encoding is not supported`),Vs=Ls({_tag:`Passthrough`});function Hs(){return Vs}function Us(){return Vs}function Ws(e){return Ls({_tag:`Transform`,transform:e})}function Gs(e){return Ls({_tag:`TransformEffect`,transform:e})}function Ks(e){return Ls({_tag:`TransformOptional`,transform:e})}function qs(e){return Ls({_tag:`TransformOptionalEffect`,transform:e})}function Js(){return Ks(()=>Cn())}function Ys(e){return qs(t=>{let n=En(t,ci);return Nr(n)?x(n):Ie(e,Sr)})}function Xs(){return Ws(globalThis.String)}function Zs(){return Ws(globalThis.Number)}function Qs(){return Ws(globalThis.BigInt)}function $s(){return Ws(e=>new globalThis.Date(e))}function ec(){return Ws(Za)}function tc(e){return Gs((t,n)=>oi({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ms({expected:`a valid JSON string`},t,n)}))}function nc(e){return Gs((t,n)=>oi({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new ms({expected:`a JSON-serializable value`},t,n)}))}function rc(){return Ws(Eo)}function ic(){return Gs((e,t)=>fi(a(Do(e)),()=>new ms({expected:`a valid Base64 string`},e,t)))}var ac=class extends pe{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new ac(this.encode,this.decode)}},oc=`~effect/SchemaTransformation/Transformation`,sc=class extends pe{[oc]=oc;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new sc(this.encode,this.decode)}};function cc(e){return br(e,oc)&&e[oc]===oc}var lc=e=>cc(e)?e:new sc(e.decode,e.encode);function uc(e){return new sc(Gs(e.decode),Gs(e.encode))}function dc(){return new sc(ec(),Hs())}var fc=new sc(Hs(),Hs());function pc(){return fc}var mc=new sc(Zs(),Xs()),hc=new sc(Qs(),Xs()),gc=new sc($s(),Ws(je)),_c=new sc(ic(),rc());function vc(e){return new sc(tc(e??{}),nc(e))}function yc(e){return t=>t._tag===e}var bc=yc(`Declaration`),xc=yc(`Null`),Sc=yc(`Undefined`),Cc=yc(`Never`),wc=yc(`String`),Tc=yc(`Number`),Ec=yc(`Boolean`),Dc=yc(`Literal`),Oc=yc(`UniqueSymbol`),kc=yc(`Arrays`),Ac=yc(`Objects`),jc=yc(`Union`),Mc=yc(`Suspend`),Nc=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Pc={},Fc=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Ic=`~effect/Schema`,Lc=class{[Ic]=Ic;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},Rc=class extends Lc{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===E?$o:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=du(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Rc(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},zc=new class extends Lc{_tag=`Null`;getParser(){return Mu(this,null)}getExpected(){return`null`}},Bc=class extends Lc{_tag=`Undefined`;getParser(){return Mu(this,void 0)}toCodecJson(){return $l(this,[Vc])}getExpected(){return`undefined`}},Vc=new Nc(zc,new sc(Ws(()=>void 0),Ws(()=>null))),Hc=new Bc,Uc=new class extends Lc{_tag=`Never`;getParser(){return Nu(this,$t)}getExpected(){return`never`}},Wc=new class extends Lc{_tag=`Unknown`;getParser(){return Nu(this,ie)}getExpected(){return`unknown`}},Gc=class extends Lc{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${S(e)}`);this.literal=e}getParser(){return Mu(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Kc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Kc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Kc(e){let t=globalThis.String(e.literal);return $l(e,[new Nc(new Gc(t),new sc(Ws(()=>e.literal),Ws(()=>t)))])}var qc=new class extends Lc{_tag=`String`;getParser(){return Nu(this,$r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Yu(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Jc=class extends Lc{_tag=`Number`;getParser(){return Nu(this,un)}matchKey(e,t){return this._match(Ru,e,t)}matchPart(e,t){return this._match(Lu,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Yu(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Yc(this.checks,`effect/schema/isFinite`)||Yc(this.checks,`effect/schema/isInt`))?this:$l(this,[Jl])}toCodecStringTree(){return this.toCodecJson()===this?$l(this,[Vu]):$l(this,[Hu])}getExpected(){return`number`}};function Yc(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Yc(e.checks,t))}var Xc=new Jc,Zc=new class extends Lc{_tag=`Boolean`;getParser(){return Nu(this,zn)}getExpected(){return`boolean`}},Qc=new class extends Lc{_tag=`Symbol`;getParser(){return Nu(this,St)}matchKey(e,t){return t.disableChecks||!this.checks?e:Yu(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return $l(this,[qu])}getExpected(){return`symbol`}},$c=new class extends Lc{_tag=`BigInt`;getParser(){return Nu(this,ar)}matchPart(e,t){if(!Uu.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Yu(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return $l(this,[Gu])}getExpected(){return`bigint`}},el=class extends Lc{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Su(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Su(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new ds(n,t[o],i),a=new ls([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return v(new fs(n,[a],t,i))}return e.issues?v(new fs(n,e.issues,t,i)):Qo(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Ur(t.concurrency),f=d===1?rl(i,e,0,u):il(i,e,{concurrency:d,end:u});if(!f)return c(i);if(pt(f))return cn(f,()=>c(i));let p=!0;return sr(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===E)return $o;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):v(new ps(n,e,a))}catch(e){return vr(e)}}}_rebuild(e,t,n){let r=du(this.elements,e),i=du(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new el(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function tl(e,t,n,r){if(n._tag===`Failure`)return al(e,e.ast,r,n);let i=n===es?t:n[et];if(i!==E)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Su(t.ast))return;let n=new ls([r],new us(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return aa(new fs(e.ast,[n],e.input,e.options))}}var nl={onItem(e,t,n){let r=n<e.len?t:E;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:tl},rl=an()(nl),il=Wn()(nl),al=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Ns(r.cause);if(i===void 0)return ia(qi(r.cause,r=>new fs(t,[new ls([n],r)],e.input,e.options)));let a=new ls([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return aa(new fs(t,[a],e.input,e.options))},ol=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function sl(e,t,n=Pc){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(Pu(Ou(t)))}var cl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ll(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ll);default:return!1}}function ul(e){let t=tu(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ul);default:return!1}}function dl(e){return ll(e)&&ul(e)}var fl=class{parameter;type;constructor(e,t){if(!dl(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Su(t)&&!ju(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},pl=class extends Lc{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Nu(n,qr);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(Pu(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return al(t,n,i,s)??sa;let c=s===es?o:s[et];if(a!==E&&c!==E){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return sa;h(t.out,a,c)}return sa},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!pt(t))return T(Ln(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return al(e,n,r,a)??sa;let o=a===es?r:a[et],s=e.input[r],l=i.parserValue(s,e.options);return pt(l)?t(e,r,o,s,l):T(Ln(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return pt(a)?t(e,n,n,i,a):T(Ln(a),r=>t(e,n,n,i,r))},u=i?Wn()({onItem:(e,[t,n])=>n.is.parameter===qc?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return m(function*(t,d){if(t===E)return E;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*v(new ps(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},ee=d.errors===`all`,te=d.onExcessProperty===`error`,ne=d.concurrency===void 0?1:Ur(d.concurrency),re=i&&te?n.indexSignatures.map(e=>sl(f,e.parameter,d)):void 0;if(te){let r=re?new Set(e):e;if(re)for(let e of re)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new ds(n,f[a],d),r=new ls([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*v(new fs(n,[r],t,d))}}}if(r){let e=ne===1?gl(m,a):_l(m,a,{concurrency:ne});e&&(yield*e)}if(i&&ne===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===qc?l:c,r=re?.[e]??(t.is.parameter===qc?Object.keys(f):sl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!pt(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=dt();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===qc?Object.keys(f):sl(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:ne});t&&(yield*t)}return m.issues?yield*v(new fs(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(Ln(n),n=>{let i=ml(e,r,n);if(i)return i;let o=()=>Qo(e.out),s=gl(e,a.slice(t+1));return s?cn(s,o):o()})};return(e,t)=>{if(e===E)return $o;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Ur(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return v(new ps(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=Al(i,s),l=c?i[s]:E,d=n.parser(l,t);if(!pt(d))return u(o,e,d);if(d===es){c&&h(a,s,l);continue}let f=ml(o,n,d);if(f)return f}}catch(e){return vr(e)}return Qo(a)}}_rebuild(e,t,n,r){let i=du(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new cl(t.name,n)}),a=du(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new fl(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new pl(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function ml(e,t,n){if(n._tag===`Failure`)return al(e,e.ast,t.name,n);if(n===es)return;let r=n[et];if(r!==E){h(e.out,t.name,r);return}if(delete e.out[t.name],!Su(t.type)){let n=new ls([t.name],new us(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return aa(new fs(e.ast,[n],e.input,e.options))}}var hl={onItem(e,t){if(!Al(e.input,t.name))return t.parser(E,e.options);let n=e.input[t.name];return h(e.out,t.name,n),t.parser(n,e.options)},step:ml},gl=an()(hl),_l=Wn()(hl);function vl(e,t){return e?t?[...e,...t]:e:t}function yl(e,t,n){return new pl(Reflect.ownKeys(e).map(t=>new cl(t,e[t].ast)),[],n,t)}function bl(e){return e.ast}function xl(e,t=void 0){return new el(!1,e.map(e=>e.ast),[],void 0,t)}function Sl(e,t,n){return new Ml(e.map(bl),t,void 0,n)}function Cl(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new el(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var wl=rt(e=>{for(;;){if(Mc(e))return Wc;let t=e.encoding;if(!t)return e.recur?.(wl,He)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==He))return Wc;e=t[t.length-1].to}});function Tl(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(Tl)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function El(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Uo];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Su(t)){if(Dc(t))return[{key:e.name,literal:t.literal}];if(Oc(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Su(e)){if(Dc(e))return[{key:t,literal:e.literal}];if(Oc(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>El(wl(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return El(e.thunk())}}var Dl=new WeakMap,Ol=Object.freeze([]),kl=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Al=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function jl(e){let t=Dl.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=wl(c);if(Cc(l))continue;if(Dc(l)||Oc(l)){a??=new Map;let e=Dc(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=El(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=Tl(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Ol);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Ol;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(gt(e)){let n=Al(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Ol;if(t)return o}return Ol}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=kl(t);if(!gt(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Al(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=Al(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=Al(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(kl(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Dl.set(e,t),t}var Ml=class extends Lc{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===E)return $o;let i=(o??=jl(n.types))(e,r);if(i.length===0)return v(new gs(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:pt(r)?Nl(n,r.cause,e,t):Pl(n,r,e,t)}return Fl(n,a,i,e,t)}}_rebuild(e,t,n){let r=du(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Ml(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=Ou(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Dc);if(t.length>0)return`${zl(n.isMutable)}[ ${t.map(t=>e(t)+Bl(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Dc(e.type));if(t.length>0)return`{ ${t.map(t=>`${zl(t.type.context?.isMutable)}${Bt(t.name)}${Bl(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Nl(e,t,n,r){let i=Ns(t);return i?aa(new gs(e,[i],n,r)):ia(t)}function Pl(e,t,n,r){return Br(t,t=>Nl(e,t,n,r))}function Fl(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=Ll(a,n);if(!o)return a.out?a.out:v(new gs(e,a.issues??[],r,i));if(pt(o))return Il(o,a);let s=!0;return sr(()=>s?(s=!1,Il(o,a)):Fl(e,t,n,r,i))}function Il(e,t){return cn(e,e=>t.out===es?x(t.input):t.out?t.out:v(new gs(t.ast,t.issues??[],t.input,t.options)))}var Ll=an()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Ns(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),aa(new _s(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return sa}}}),Rl=new Ml([new Gc(`Infinity`),new Gc(`-Infinity`),new Gc(`NaN`)]);function zl(e){return e?``:`readonly `}function Bl(e){return e?`?`:``}var Vl=class extends Lc{_tag=`Suspend`;thunk;constructor(e,t,n,r,i){if(n)throw Error(`Cannot add checks to Suspend`);super(t,void 0,r,i);let a;this.thunk=()=>a??=e()}getParser(e){let t;return(n,r)=>(t??=e(this.thunk()))(n,r)}recur(e){return new Vl(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Hl=class extends pe{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Hl(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Hl(this.run,this.annotations,!0)}and(e,t){return new Ul([this,e],t)}},Ul=class extends pe{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ul(this.checks,{...this.annotations,...e})}and(e,t){return new Ul([this,e],t)}};function Wl(e,t,n=!1){return new Hl((t,n,r)=>bs(n,e(t,n,r),t,r),t,n)}function Gl(e,t){return new Hl((t,n,r)=>e(t)?void 0:new ms(void 0,t,r),t,!0)}function Kl(e){return Wl(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var ql=iu(Xc,[Kl()]),Jl=new Nc(new Ml([ql,Rl]),new sc(Zs(),Ws(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Yl(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Wl(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var Xl=new WeakMap;function Zl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Xl.set(n,Ql(e)),n}function Ql(e){let t=Xl.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Xl.set(e,n),n}function $l(e,t){return e.encoding===t?e:Zl(e,{encoding:t})}function eu(e,t){if(e.context===t)return e;let n=Ql(e);return n.context===t&&n.encoding===e.encoding?n:Zl(e,{context:t})}function tu(e){return e.encoding?tu(e.encoding[e.encoding.length-1].to):e}function nu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return ru(e,Re(e.checks.slice(0,-1),n.annotate(t)))}return Zl(e,{annotations:{...e.annotations,...t}})}function ru(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Zl(e,{checks:t})}function iu(e,t){return ru(e,vl(e.checks,t))}function au(e,t){let n=t(e.to);return n===e.to?e:new Nc(n,e.transformation)}function ou(e,t){let n=e,r=n[n.length-1],i=au(r,t);return i===r?e:Re(e.slice(0,e.length-1),i)}function su(e){return t=>t.encoding?$l(t,ou(t.encoding,e)):t}function cu(e,t){return su(e=>eu(e,t))(e)}function lu(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:$l(r,ou(r.encoding,n))}return e(r)}return rt(n)}function uu(e,t,n){let r=new Nc(e,t);return $l(n,n.encoding?[...n.encoding,r]:[r])}function du(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function fu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Fc(!1,!1,void 0,t))}var pu=rt(e=>mu(eu(e,e.context?e.context.isOptional===!1?new Fc(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!0,!1)))),mu=su(pu),hu=qe(e=>pu(new Ml([e,Hc]))),gu=rt(e=>_u(eu(e,e.context?e.context.isMutable===!1?new Fc(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!1,!0)))),_u=su(gu);function vu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Fc(!1,!1,t))}function yu(e,t,n){return uu(e,n,t)}function bu(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:ee(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function xu(e,t){let{literals:n,parameters:r}=bu(e);return new pl(n.map(e=>new cl(e,t)),r.map(e=>new fl(e,t)))}function Su(e){return e.context?.isOptional??!1}function Cu(e){return e.context?.isMutable??!1}function wu(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(wu)}function Tu(e){function t(e){return wu(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return d(n)?n:void 0}function Eu(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Mc(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var Du=rt(e=>{let t=Ql(e);if(t!==e){let n=Du(t);return n===t&&e.encoding===void 0?e:eu(n,e.context)}let n=`recur`in e?e.recur(Du):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Eu(e)?n.encodingChecks:kc(n)||Ac(n)||bc(n)&&n.typeParameters.length>0?Tu(n.encodingChecks):void 0;return Zl(n,{encodingChecks:void 0,checks:vl(n.checks,t)})}return n}),Ou=rt(e=>Du(Au(e)));function ku(e,t){let n=t,r=n.length,i=n[r-1],a=[new Nc(Au($l(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Nc(Au(n[e-1].to),n[e].transformation.flip()));let o=Au(i.to);return o.encoding?$l(o,[...o.encoding,...a]):$l(o,a)}var Au=qe(e=>{if(e.encoding)return ku(e,e.encoding);let t=Ql(e);if(t!==e){let n=Au(t);return n===t?e:eu(n,e.context)}return`flip`in e?e.flip(Au):`recur`in e?e.recur(Au):e});function ju(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(ju);default:return!1}}function Mu(e,t){let n=t===0?es:Qo(t);return(r,i)=>r===E?$o:r===t?n:v(new ps(e,r,i))}function Nu(e,t){return(n,r)=>n===E?$o:t(n)?es:v(new ps(e,n,r))}var Pu=lu(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Pu)}}),Fu=lu(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Fu)}}),Iu=`[\\s\\S]*?`,Lu=new globalThis.RegExp(`^${ol}$`),Ru=new globalThis.RegExp(`^(?:${ol}|Infinity|-Infinity|NaN)$`);function zu(e){return Yl(Lu,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Lu.source}),...e})}var Bu=iu(qc,[zu()]),Vu=new Nc(Bu,mc),Hu=new Nc(new Ml([Bu,Rl]),mc),Uu=new globalThis.RegExp(`^-?\\d+$`);function Wu(e){return Yl(Uu,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Uu.source}),...e})}var Gu=new Nc(iu(qc,[Wu({expected:`a string representing a bigint`})]),hc),Ku=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),qu=new Nc(iu(qc,[Ju()]),new sc(Ws(e=>globalThis.Symbol.for(Ku.exec(e)[1])),Gs((e,t)=>globalThis.Symbol.keyFor(e)===void 0?v(new hs({message:`cannot serialize to string, Symbol is not registered`},e,t)):x(globalThis.String(e)))));function Ju(e){return Yl(Ku,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:Ku.source}),...e})}function Yu(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Yu(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new ss(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Xu(e){if(!bc(e))return;let t=e.annotations?.[Wo];return Nn(t)?t(e.typeParameters):void 0}var Zu=zo,Qu=Jo,$u=Yo;function ed(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function td(e){return e===void 0||typeof e==`string`}function nd(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function rd(e){return nd(e,ed)}var id=new Rc([],()=>(e,t,n)=>rd(e)?es:v(new ps(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>cd}),ad=new Nc(id,pc()),od=new Nc(new Ml([new el(!1,[],[id]),new pl([],[new fl(qc,id)])]),pc());function sd(e){return nd(e,td)}var cd=new Nc(new Rc([],()=>(e,t,n)=>sd(e)?es:v(new ps(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),pc()),ld=(e,t,n)=>e===es?n(t):cn(e,n);function ud(e){if(e._tag===`Middleware`)return(t,n,r)=>dd(t===es?e.decode(Qo(ts(n)),r):e.decode(Ie(t,ts),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===es?Qo(t):e;case`Transform`:{let e=e=>e===E?$o:Qo(t.transform(e));return(t,n)=>ld(t,n,e)}case`TransformOptional`:{let e=e=>ns(t.transform(ts(e)));return(t,n)=>ld(t,n,e)}case`TransformEffect`:return(e,n,r)=>ld(e,n,e=>e===E?$o:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>ld(e,n,e=>dd(t.transform(ts(e),r)))}}var dd=e=>cn(e,ns),fd=(e,t,n,r)=>Br(r,r=>Kr(()=>qi(r,r=>new cs(e,r,t,n))));function pd(e,t){let n=ud(e.link.transformation),r;return(i,a)=>{if(i===E)return $o;if(e.isConstructed(i))return es;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function md(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==E&&r!==void 0)return t(r,i);let a=n;if(pt(a)&&a._tag===`Success`){let e=t(a[et],i);return e===es?a:e}return cn(fd(e,r,i,a),e=>{let n=t(e,i);return n===es?Qo(e):n})}}function hd(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:md(e,n)}function gd(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Xu(e):void 0,o=a?pd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>ud(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(t!==E&&i!==E){let i=Yu(u,t,void 0,e,n);i&&(r=v(new fs(e,i,t,n)))}}}else r=T(r,r=>{if(t!==E&&r!==E){let r=Yu(u,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(r)})}if(s&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(i===E)return r;let a=Yu(s,i,void 0,e,n);a&&(r=v(new fs(e,a,i,n)))}}else r=T(r,t=>{if(t!==E){let r=Yu(s,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[et],o=t(a,r)):o=cn(o,e=>{let n=t(e,r);return n===es?Qo(e):n})}if(o._tag===`Success`){let e=o[et],t=p(e,r);return t===es?o:t}return o=fd(e,n,r,o),cn(o,e=>{let t=p(e,r);return t===es?Qo(e):t})}:p}var _d=Symbol(),vd=new WeakMap,yd=e=>Cd(e).parser,bd=e=>Cd(e).makeEffect,xd=e=>hd(e,bd),Sd=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=gd(this.ast,yd)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=gd(this.ast,bd,xd)}};function Cd(e){let t=vd.get(e);if(t!==void 0)return t;let n=new Sd(e);return vd.set(e,n),n}function wd(e){let t=e.ast,n;return(e,r)=>(n??=Vd(Jd,Du(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Td(e){let t=wd(e);return(e,n)=>{let r=Pr(t(e,n));return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Ed(e){return Kd(Du(e.ast))}function Dd(e){return kd(e.ast)}function Od(e){{let t=Hd(zd(e));return e=>{let n=t(e,Pc);return ca(n)?!0:(Ps(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function kd(e){let t=Du(e),n=e=>(n=Od(t),n(e));return e=>n(e)}function Ad(e,t){let n=zd(e.ast);return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function jd(e,t){return Hd(Ad(e,t))}function Md(e,t){return Ud(Ad(e,t))}function Nd(e,t){return Wd(Ad(e,t))}function Pd(e,t){let n=zd(Au(e.ast));return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function Fd(e,t){return Hd(Pd(e,t))}function Id(e,t){return Wd(Pd(e,t))}var Ld=(e,t)=>t?{...e,...t}:e,Rd=e=>e===E?v(new ms):x(e);function zd(e){return Vd(qd,e)}function Bd(e,t){return e===es?x(t):pt(e)?e[et]===E?Rd(E):e:cn(e,Rd)}function Vd(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Pc);return a===es?x(r):pt(a)?a[et]===E?Rd(E):a:cn(a,Rd)}}function Hd(e){return(t,n)=>Pr(e(t,n))}function Ud(e){let t=Hd(e);return(e,n)=>{let r=t(e,n);return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Wd(e){let t=Hd(e);return(e,r)=>{let i=t(e,r);return ca(i)?n(i.value):ve(Ps(i.cause,`Result adapter can only return schema issues`))}}function Gd(e,t){let n=Pr(e);if(ca(n))return n.value;let r=Ps(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Kd(e){let t,n;return(r,i)=>{t??=Cd(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Pc,o=t.make;if(o!==void 0&&r!==E){let e;try{e=o(r,a)}catch(e){throw Ps(Gi(e),`Constructor adapter can only throw schema issues`),e}if(e!==_d&&e!==E)return e}return Gd(Bd((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var qd=e=>Cd(e).parser,Jd=e=>Cd(e).makeEffect,Yd=`~effect/Schema/Schema`,Xd=Symbol(),Zd={[Yd]:Yd,get make(){let e=Ed(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=wd(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Td(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Le(this,arguments)},annotate(e){return this.rebuild(nu(this.ast,e))},annotateKey(e){return this.rebuild(fu(this.ast,e))},check(...e){return this.rebuild(iu(this.ast,e))},rebuild(e){return Qd(e,this[Xd])}};function Qd(e,t){function n(){}let r=Object.setPrototypeOf(n,Zd);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Xd]=t,r.ast=e,r}function $d(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ef(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function tf(e){return encodeURI($d(e)).replace(/#/g,`%23`)}function nf(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function rf(e){let t=nf(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(ef)}function af(e){return e.reduce((e,t)=>`${e}/${tf(t)}`,`#`)}var of=`http://json-schema.org/draft-07/schema#`;function sf(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function cf(e){return{dialect:`draft-07`,...bf(e,Mf)}}function lf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!ri(e))return e;let a=r||!i&&yf(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=ff(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}h(o,t,i)}return t(o,a),o}}function uf(e,t){return lf(e,e=>{df(e,t)})}function df(e,t){typeof e.$ref==`string`&&h(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&h(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function ff(e,t){if(!ri(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function pf(e,t,n){let r=new Map,i=[],a=mf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=gf(ri(e)?u(e):void 0,mf)??mf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=hf(t,n);if(a!==void 0){let e=rf(a.hash);if(a.hash=``,e!==void 0){let n=r.get(vf(a.href,e));n!==void 0&&(i=_f(t,n))}}h(e,`$ref`,i)}}let c=n(o);return s(),c;function l(n,r,a,o){if(typeof n==`boolean`)return d(r,a,o),t?.booleanAdapter?.(n)??n;if(!ri(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&yf(c)){let e=gf(c,o.uri);e!==void 0&&(s={parent:o,sourceRoot:r,targetRoot:a,uri:e})}d(r,a,s);let f=s.uri;return e(n,{isDocumentRoot:r.length===0,schema(e,t,n=t){return l(e,[...r,t],[...a,n],s)},schemaAt(e,t,n){return l(e,[...r,...t],[...a,...n],s)},schemaArray(e,t,n=t){return Array.isArray(e)?e.map((e,i)=>l(e,[...r,t,String(i)],[...a,n,String(i)],s)):e},schemaMap(e,t,n=t){return ri(e)?ff(e,(e,i)=>l(e,[...r,t,i],[...a,n,i],s)):e},reference(e,t){typeof t==`string`?i.push([e,t,f]):h(e,`$ref`,t)}})}function u(e){return t?.ignoreRefSiblings===!0&&typeof e.$ref==`string`?void 0:e.$id}function d(e,t,n){n.parent!==void 0&&d(e,t,n.parent),r.set(vf(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var mf=`https://effect.invalid/.json-schema/`;function hf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function gf(e,t){if(typeof e!=`string`)return;let n=hf(e,t);if(n!==void 0)return n.hash=``,n.href}function _f(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${af(t)}`}function vf(e,t){return`${e}\u0000${JSON.stringify(t)}`}function yf(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function bf(e,t,n){return pf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:ff(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var xf=new Set([`properties`,`patternProperties`]),Sf=new Set([`allOf`,`anyOf`,`oneOf`]),Cf=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function wf(e,t,n,r,i,a=xf){let o;if(a.has(t))o=r.schemaMap(n,t);else if(Sf.has(t))o=r.schemaArray(n,t);else if(i.has(t))o=r.schema(n,t);else return!1;return h(e,t,o),!0}var Tf=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Tf],[...Tf];var Ef=/^[A-Za-z_][-A-Za-z0-9._]*$/,Df=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Of(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function kf(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Of(i,n,`it is not active in ${r} but would become active in the target`)}var Af=[`additionalItems`,`definitions`,`dependencies`];function jf(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,sf(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):sf(t,`https://json-schema.org/draft/2020-12/schema`)||Of(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Mf(e,t){kf(e,Af,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!wf(n,o,s,t,Cf))switch(o){case`$ref`:r=s;break;case`$schema`:jf(n,s,t,of,`Draft-07`);break;case`$id`:case`$anchor`:break;case`$defs`:h(n,`definitions`,t.schemaMap(s,o,`definitions`));break;case`prefixItems`:i=s;break;case`items`:a=s;break;case`dependentRequired`:case`dependentSchemas`:case`minContains`:case`maxContains`:break;case`$dynamicRef`:case`$dynamicAnchor`:case`$vocabulary`:case`unevaluatedProperties`:case`unevaluatedItems`:Of(o,`Draft-07`,`the target dialect has no equivalent`);case`required`:if(Array.isArray(s)&&s.length===0)break;h(n,o,s);break;default:h(n,o,s)}}if(Nf(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Of(`minContains/maxContains`,`Draft-07`,`contains cardinality cannot be represented`),Object.hasOwn(e,`minContains`)&&h(n,`minContains`,t)}else Object.hasOwn(e,`minContains`)&&h(n,`minContains`,e.minContains),Object.hasOwn(e,`maxContains`)&&h(n,`maxContains`,e.maxContains);return Ff(e,n,t,`draft-07`),Lf(e,n,`$id`,`Draft-07`),Pf(n,r,t),n}function Nf(e,t,n,r){if(t===void 0){n!==void 0&&h(e,`items`,r.schema(n,`items`));return}h(e,`items`,r.schemaArray(t,`prefixItems`,`items`)),n!==void 0&&h(e,`additionalItems`,r.schema(n,`items`,`additionalItems`))}function Pf(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),If(e,r)}else n.reference(e,t)}}function Ff(e,t,n,r){let i=ri(e.dependentRequired)?e.dependentRequired:void 0,a=ri(e.dependentSchemas)?e.dependentSchemas:void 0;if(i===void 0&&a===void 0)return;let o={},s=new Set([...Object.keys(i??{}),...Object.keys(a??{})]);for(let e of s){let t=i?.[e],s=a?.[e],c=r===`draft-04`&&Array.isArray(t)&&t.length===0;s===void 0?c||h(o,e,t):t===void 0||c?h(o,e,n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e])):h(o,e,{allOf:[n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e,`allOf`,`0`]),{required:t}]})}Object.keys(o).length>0&&h(t,`dependencies`,o)}function If(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function Lf(e,t,n,r){let i=e.$id,a=e.$anchor;if(a===void 0){i!==void 0&&h(t,n,i);return}(typeof a!=`string`||!Ef.test(a))&&Of(`$anchor`,r,`the anchor is not valid`),Df.test(a)||Of(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):Of(`$anchor`,r,`it cannot be combined with the schema $id`)}function Rf(e){return Qd(zf(e.ast),{schema:e})}var zf=lu(e=>{let t=Wf(e,zf),n=e.context;return t===e||n===void 0?t:cu(t,Bf(n))});function Bf(e){return e.constructorDefault===void 0?e:new Fc(e.isOptional,e.isMutable,void 0,e.annotations)}function Vf(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Hf(e){return t=>{let n=[...t].sort((t,n)=>e(Ou(t))-e(Ou(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Uf=Hf(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wf(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Nn(n))return $l(e,[ad]);let r=n(e.typeParameters.map(e=>Qd(Ou(e))));return r===void 0?e:$l(e,[au(r,t)])}case`Unknown`:return $l(e,[ad]);case`ObjectKeyword`:return $l(e,[od]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Vf(e),e.recur(t,Fu);case`Union`:{let n=Uf(e.types);return n===e.types?e.recur(t):new Ml(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}globalThis.RegExp;var Gf=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Kf(e,t){return t.length>0&&(e+=`\n at ${Gt(t)}`),Error(e)}function qf(e){return`#/$defs/${tf(e)}`}var Jf=new Set([...Zo,Ho,...Go]);function Yf(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;rd(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&rd(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(rd(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))Jf.has(r)||!t.includeAnnotationKey(r)||rd(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function Xf(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=Xf(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function Zf(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}var Qf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function $f(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function ep(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var tp=`|title|description|default|examples|readOnly|writeOnly|`,np=Qf+tp;function rp(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Zf(e);if(i!==void 0||a){let r=Xf(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:$f(r.schema,tp)&&ep(o,s)?{...o,...r.schema}:rp(o,r.schema,n)}}if(n&&ep(e,r))return{...e,...t};let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function ip(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>ip(e,t)))}function ap(e){return Array.isArray(e)}function op(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=Et(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!ip(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=te(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Dr(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Et(u,ee),f={};for(let e of l)a.has(e)||h(f,e,ee(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw Kf(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=re(n[e],[`references`,e],a[1]),a}function ee(e){return uf(e,e=>{let t=nf(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(ef(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,qf(r))})}function te(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[Ho]:void 0}function ne(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>re(e,[...n,`representation`,`schemas`,t],i))??[]}),c=ap(s);c&&i.push(!1);let l=c?s[0]:s,u=Yf(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Qf:np;return[d,e._tag===`Filter`&&$f(d,f)&&(u===void 0||$f(u,tp))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=ne(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Yf(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function re(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:qf(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=ie(e,t,a),c=Yf(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&sp(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=rp(s,...i))}return o.set(e,[s,a]),p(s)}function ie(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return re(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw Kf(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(lp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Kf(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=re(e.type,[...t,`elements`,i,`type`],n),s=Yf(e.annotations,r);return s===void 0?o:p(rp(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=re(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw Kf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=Yf(s.annotations,r);h(a,c,u===void 0?l:p(rp(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=re(i.type,[...t,`indexSignatures`,r,`type`],n);Dr(a,{not:{}})&&(a=!1),l.push(a);let o=ae(i.parameter,[...t,`indexSignatures`,r,`parameter`],new Set);if(o===void 0){u=!0,n.push(!1);continue}if(o.length===0)c.push(a);else for(let e of o){let t=s[e];h(s,e,t===void 0?a:t===!1||a===!1?!1:p(rp(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(re(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>re(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=cp(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function ae(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw Kf(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ae(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=re(e,t,n);return ip(n)&&r.type===`string`&&typeof r.pattern==`string`&&$f(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lp).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=ae(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw Kf(`Invalid schema representation document`,t)}}}function sp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function cp(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function lp(e){switch(e._tag){case`Literal`:return Gf(globalThis.String(e.literal));case`String`:return Iu;case`Number`:return ol;case`TemplateLiteral`:return e.parts.map(lp).join(``);case`Union`:return`(?:${e.types.map(lp).join(`|`)})`;default:throw Kf(`Invalid schema representation document`,[])}}function up(e,t){let n=op([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var dp=({identifier:e})=>e;function fp(e){return e===void 0?void 0:{annotations:e}}function pp(e,t){let{references:n,representations:r}=mp([e],t);return{representation:r[0],references:n}}function mp(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)f(t);let s=t?.referencePolicy??dp;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:Et(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:nu(e,{identifier:n}):qo(e)===r?e:nu(e,{[Ho]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=ee(t);i.delete(e),h(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=tu(e),n=Ql(t),r=Ko(t),i=r===void 0?(t===e?void 0:Ko(e))??qo(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t)){t.isRecursive=!0;return}if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(Du(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?ee(n):u(r,t.identifier===void 0?n:l(n,t,r))}function ee(e){let t=te(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...re(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...fp(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...fp(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...fp(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...fp(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=tu(e),n=t.context?.annotations;return{isOptional:Su(t),type:m(e),...fp(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=tu(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Su(t),isMutable:Cu(t),...fp(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...fp(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...fp(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...fp(e.annotations)}}}function te(e){return e?.map(ne)??[]}function ne(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...ie(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:Et(e.checks,ne),...ie(e.annotations)}}}function re(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function ie(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(Du(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function hp(e){return ca(e)?e.value:{issues:[{message:$i(e.cause)}]}}function gp(e,t){let n=Ad(e),r={errors:`all`,...t?.parseOptions},i=Cs(t),a=e=>{let t=new Ct(`sync`),a=dr(u(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?hp(o):new Promise(e=>{a.addObserver(t=>{e(hp(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}function _p(e){return up(pp(zf(e)))}function vp(e,t){let n=_p(e);if(t===`draft-2020-12`){let e=n.schema;return Object.keys(n.definitions).length>0&&(e.$defs=n.definitions),e}if(t===`draft-07`){let e=cf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function yp(e){let t={input(t){return vp(e.ast,t.target)},output(t){return vp(Du(e.ast),t.target)}};if(Object.hasOwn(e,`~standard`)){let n=e;return`jsonSchema`in n[`~standard`]||Object.assign(n[`~standard`],{jsonSchema:t}),n}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,jsonSchema:t}})}var bp=qe(e=>xp(e));function xp(e){let t=zo(e)?.toEquivalence;if(t)return t(bc(e)?e.typeParameters.map(xp):[]);switch(e._tag){case`Never`:return cr();case`Declaration`:return Sp(e);case`Null`:case`Undefined`:case`Void`:case`Unknown`:case`Any`:case`String`:case`Number`:case`Boolean`:case`BigInt`:case`Symbol`:case`Literal`:case`UniqueSymbol`:case`ObjectKeyword`:case`Enum`:case`TemplateLiteral`:return Dr;case`Arrays`:{let t=e.elements.map(xp),n=e.rest.map(xp),[r,...i]=n,a=i.length;return Lr((o,s)=>{if(!Array.isArray(o)||!Array.isArray(s))return!1;let c=o.length;if(c!==s.length)return!1;let l=0;for(;l<Math.min(c,e.elements.length);l++)if(!t[l](o[l],s[l]))return!1;if(n.length>0){for(;l<c-a;l++)if(!r(o[l],s[l]))return!1;for(let e=0;e<a;e++)if(!i[e](o[l+e],s[l+e]))return!1}return!0})}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Dr;let t=e.propertySignatures.map(e=>xp(e.type)),n=e.indexSignatures.map(e=>xp(e.type));return Lr((r,i)=>{if(!ri(r)||!ri(i))return!1;for(let n=0;n<t.length;n++){let a=e.propertySignatures[n],o=a.name,s=Object.hasOwn(r,o),c=Object.hasOwn(i,o);if(Su(a.type)&&s!==c||s&&c&&!t[n](r[o],i[o]))return!1}for(let t=0;t<n.length;t++){let a=e.indexSignatures[t],o=sl(r,a.parameter),s=sl(i,a.parameter);if(o.length!==s.length)return!1;for(let e=0;e<o.length;e++){let a=o[e];if(!Object.hasOwn(i,a)||!n[t](r[a],i[a]))return!1}}return!0})}case`Union`:{let t=Du(e).types,n=jl(t),r=t.map((t,n)=>[kd(t),xp(e.types[n])]);return Lr((e,t)=>{let i=n(e,!1);for(let n=0;n<i.length;n++){let[a,o]=r[i[n]];if(a(e)&&a(t))return o(e,t)}return!1})}case`Suspend`:{let t;return Lr((n,r)=>(t??=bp(e.thunk()))(n,r))}}}function Sp(e){let t=e.annotations?.representation;if(t===void 0)return Dr;switch(t.id){case`effect/schema/Option`:{let[t]=Cp(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=Cp(e);return(e,r)=>e._tag===r._tag&&(e._tag===`Success`?t(e.success,r.success):n(e.failure,r.failure))}case`effect/schema/CauseReason`:{let[t,n]=Cp(e);return wp(t,n)}case`effect/schema/Cause`:{let[t,n]=Cp(e);return Tp(t,n)}case`effect/schema/Exit`:{let[t,n,r]=Cp(e),i=Tp(n,r);return(e,n)=>e._tag===n._tag&&(e._tag===`Success`?t(e.value,n.value):i(e.cause,n.cause))}case`effect/schema/ReadonlyMap`:{let[t,n]=Cp(e);return Un(t,n)}case`effect/schema/ReadonlySet`:return rn(Cp(e)[0]);case`effect/schema/RegExp`:return(e,t)=>e.source===t.source&&e.flags===t.flags;case`effect/schema/URL`:return(e,t)=>e.toString()===t.toString();default:return Dr}}function Cp(e){return e.typeParameters.map(xp)}function wp(e,t){return(n,r)=>{if(n._tag!==r._tag)return!1;switch(n._tag){case`Fail`:return e(n.error,r.error);case`Die`:return t(n.defect,r.defect);case`Interrupt`:return n.fiberId===r.fiberId}}}function Tp(e,t){let n=r(wp(e,t));return(e,t)=>n(e.reasons,t.reasons)}var Ep=o(2,(e,t)=>({...e,...t})),Dp=e=>e,Op=`~effect/Schema/SchemaError`;function kp(e){return br(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var Ap=Yd;function jp(){return(e,t,n)=>$p(new Rc(e.map(bl),e=>t(e.map(e=>$p(e))),n))}function Mp(e,t){return jp()([],()=>(t,n,r)=>e(t)?x(t):v(new ps(n,t,r)),t)}var Np=class extends zi(`SchemaError`){[Op]=Op;constructor(e){let t=Dt();Ft(0);try{super({issue:e})}finally{Ft(t)}}get message(){return As(this.issue)}toString(){return`SchemaError(${this.message})`}};function Pp(e){return kp(e)}function Fp(e){return pt(e)?Ip(e):Br(e,e=>Kr(()=>qi(e,e=>new Np(e))))}function Ip(e){return ca(e)?e:ia(qi(e.cause,e=>new Np(e)))}function Lp(e,t){let n;for(let r of e.reasons){if(!Hi(r)||!Pp(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function Rp(e){let t=Pr(e);if(ca(t))return t.value;throw Lp(t.cause,`Sync adapter can only throw schema errors`)}function zp(e,t){return gp(e,t)}function Bp(e){return yp(e)}var Vp=Dd;function Hp(e,t){let n=Ad(e,t);return(e,t)=>Fp(n(e,t))}function Up(e,t){let n=jd(e,t);return(e,t)=>Ip(n(e,t))}var Wp=Md;function D(e,t){let n=Nd(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Gp=D;function O(e,t){let n=Hp(e,t);return(e,t)=>Rp(n(e,t))}var Kp=O;function qp(e,t){let n=Pd(e,t);return(e,t)=>Fp(n(e,t))}function Jp(e,t){let n=Fd(e,t);return(e,t)=>Ip(n(e,t))}function Yp(e,t){let n=Id(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Xp=Yp;function Zp(e,t){let n=qp(e,t);return(e,t)=>Rp(n(e,t))}var Qp=Zp,$p=Qd;function em(e){return br(e,Ap)&&e[Ap]===Ap}var k=Dp(e=>$p(pu(e.ast),{schema:e})),A=Dp(e=>{let t=vm(e);return $p(hu(e.ast),{schema:t})}),tm=Dp(e=>$p(gu(e.ast),{schema:e})),nm=Dp(e=>$p(Du(e.ast),{schema:e})),rm=Dp(e=>$p(Ou(e.ast),{schema:e}));function j(e){let t=$p(new Gc(e),{literal:e,transform(n){return t.pipe(Sm(j(n),{decode:Ws(()=>n),encode:Ws(()=>e)}))}});return t}var im=$p(Uc),am=$p(Wc),om=$p(zc),sm=$p(Hc),M=$p(qc),N=$p(Xc),cm=$p(Zc),lm=$p(Qc),um=$p($c);function dm(e,t){return $p(e,{fields:t,mapFields(e,t){let n=e(this.fields);return dm(yl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e){return dm(yl(e,void 0),e)}function fm(e,t){return $p(xu(e.ast,t.ast),{key:e,value:t})}function pm(e,t){return $p(e,{elements:t,mapElements(e,t){let n=e(this.elements);return pm(xl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function mm(e){return pm(xl(e),e)}var F=Dp(e=>$p(new el(!1,[],[e.ast]),{value:e})),hm=Dp(e=>$p(new el(!1,[e.ast],[e.ast]),{value:e})),gm=Dp(e=>$p(Cl(e.ast),{schema:e}));function _m(e,t){return $p(e,{members:t,mapMembers(e,t){let n=e(this.members);return _m(Sl(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function I(e,t){return _m(Sl(e,t,void 0),e)}function L(e){let t=e.map(j);return $p(Sl(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return I(e(this.members))},pick(e){return L(e)},transform(e){return I(t.map((t,n)=>t.transform(e[n])))}})}var R=Dp(e=>I([e,om])),vm=Dp(e=>I([e,sm]));function ym(e){return $p(new Vl(()=>e().ast))}function z(...e){return t=>t.check(...e)}function bm(e,t){return n=>$p(iu(n.ast,[Gl(e,t)]),{schema:n})}function xm(e){return t=>$p(t.ast,{schema:t,identifier:e})}function Sm(e,t){return n=>$p(yu(n.ast,e.ast,t?lc(t):pc()),{from:n,to:e})}function Cm(){return(e,t)=>Mm()(e,{decode:t,encode:Bs})}function wm(e,t){return n=>t?Sm(n,t)(e):Sm(n)(e)}function Tm(e){return t=>$p(vu(t.ast,e),{schema:t})}function Em(e){return Br(e,e=>Kr(()=>qi(e,e=>e.issue)))}function Dm(e,t){let n=t?.encodingStrategy===`omit`?Js():Hs();return t=>k(rm(t)).pipe(Sm(t,{decode:Ys(Em(e)),encode:n}))}function Om(e,t){let n=t?.encodingStrategy===`omit`?Js():Hs();return t=>A(rm(t)).pipe(Sm(t,{decode:Ys(Em(e)),encode:n}))}function km(e,t){return n=>nm(n).pipe(Om(e,t),wm(A(n)))}function Am(e){return j(e).pipe(Tm(x(e)))}function jm(e,t){return Mp(t=>t instanceof e,t)}function Mm(){return(e,t)=>new Nc(e.ast,lc(t))}var B=Wl,Nm=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Pm(e){let t=new globalThis.RegExp(Nm);return B(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:Nm,flags:``}]},...e})}function Fm(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${S(n)})`:`new RegExp(${S(n)}, ${S(r)})`;return Yl(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var Im=e=>e?new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;function Lm(e,t){let n=Im(e);return Fm(n,{expected:e?`a UUID v${e}`:`a UUID`,representation:{id:`effect/schema/isUUID`,payload:{version:e??null}},toJsonSchema:()=>({pattern:n.source,format:`uuid`}),toCode:()=>({runtime:e===void 0?`Schema.isUUID()`:`Schema.isUUID(${e})`}),...t})}function Rm(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Fm(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function zm(e,t,n){if(e.length===0)return t.length===0?{}:[{},!0];let r={pattern:new globalThis.RegExp(n).source};return e===t?r:[r,!0]}function Bm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${Gf(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return B(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>zm(i,e,`^${Gf(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Vm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${Gf(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return B(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>zm(i,e,`${Gf(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Hm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(Gf(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return B(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>zm(i,e,Gf(i)),toCode:()=>({runtime:`Schema.isIncluding(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Um=$p(ql),Wm=Kl;function Gm(e){let t=ui(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function Km(e){let t=fn(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function qm(e){let t=ai(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function Jm(e){let t=vt(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function Ym(e){let t=fn(e.order),n=ui(e.order),r=vt(e.order),i=ai(e.order),a=e.formatter??S;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return B(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function Xm(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${S(e)}`);return e}var Zm=Gm({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Xm(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${S(e)})`})})}),V=Km({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Xm(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${S(e)})`})})}),Qm=qm({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Xm(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${S(e)})`})})}),$m=Jm({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Xm(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${S(e)})`})})}),eh=Ym({order:tn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Xm(e.minimum),maximum:Xm(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function th(e,t){if(!globalThis.Number.isFinite(e)||e===0)throw new globalThis.RangeError(`Expected a finite non-zero number, got ${globalThis.String(e)}`);return e=globalThis.Math.abs(e),B(t=>Ya(t,e)===0,{expected:`a value that is a multiple of ${e}`,representation:{id:`effect/schema/isMultipleOf`,payload:{divisor:e}},toJsonSchema:()=>({multipleOf:e}),toCode:()=>({runtime:`Schema.isMultipleOf(${S(e)})`}),...t})}function nh(e){return B(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var H=N.check(nh()),rh=H.check(V(0));function ih(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${S(e)}`);return e.toISOString()}function ah(e){return`new Date(${S(e.getTime())})`}var oh=Gm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:ih(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${ah(e)})`})})}),sh=Km({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:ih(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${ah(e)})`})})}),ch=qm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:ih(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${ah(e)})`})})}),lh=Jm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:ih(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${ah(e)})`})})}),uh=Ym({order:Fn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:ih(e.minimum),maximum:ih(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${ah(e.minimum)}, maximum: ${ah(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}}),dh=Gm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${S(e)})`})})}),fh=Km({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${S(e)})`})})}),ph=qm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${S(e)})`})})}),mh=Jm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${S(e)})`})})}),hh=Ym({order:Vn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenBigInt`,payload:{minimum:e.minimum.toString(10),maximum:e.maximum.toString(10),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenBigInt({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function gh(e,t){return e=Th(e),_h(e,Math.ceil(e/2),t)}function _h(e,t,n){return B(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Vo]:!0,arbitraryConstraint:{minLength:e},...n})}function vh(e){return _h(1,1,e)}function yh(e,t){return e=Th(e),B(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Vo]:!0,arbitraryConstraint:{maxLength:e},...t})}function bh(e,t,n){return e=Th(e),t=Th(t),B(n=>n.length>=e&&n.length<=t,{expected:e===t?`a value with a length of ${e}`:`a value with a length between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenLength`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`string`?t===0||Math.ceil(e/2)>t?{minLength:Math.ceil(e/2),maxLength:t}:[{minLength:Math.ceil(e/2),maxLength:t},!0]:n===`array`?{minItems:e,maxItems:t}:n===void 0?[{minLength:Math.ceil(e/2),maxLength:t,minItems:e,maxItems:t},!0]:[{},!0],toCode:()=>({runtime:`Schema.isBetweenLength(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function xh(e,t){return e=Th(e),B(t=>wh(t,e)>=e,{expected:`a string with at least ${e} code points`,representation:{id:`effect/schema/isMinCodePoints`,payload:{minCodePoints:e}},toJsonSchema:()=>({minLength:e}),toCode:()=>({runtime:`Schema.isMinCodePoints(${e})`}),arbitraryConstraint:{minCodePoints:e},...t})}function Sh(e,t){return e=Th(e),B(t=>wh(t,e+1)<=e,{expected:`a string with at most ${e} code points`,representation:{id:`effect/schema/isMaxCodePoints`,payload:{maxCodePoints:e}},toJsonSchema:()=>({maxLength:e}),toCode:()=>({runtime:`Schema.isMaxCodePoints(${e})`}),arbitraryConstraint:{maxCodePoints:e},...t})}function Ch(e,t,n){return e=Th(e),t=Th(t),B(n=>{let r=wh(n,t+1);return r>=e&&r<=t},{expected:e===t?`a string with ${e} code points`:`a string with between ${e} and ${t} code points`,representation:{id:`effect/schema/isBetweenCodePoints`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>({allOf:[{minLength:e},{maxLength:t}]}),toCode:()=>({runtime:`Schema.isBetweenCodePoints(${e}, ${t})`}),arbitraryConstraint:{minCodePoints:e,maxCodePoints:t},...n})}function wh(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function Th(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Eh(e,t){return e=Th(e),B(t=>t.size>=e,{expected:`a value with a size of at least ${e}`,representation:{id:`effect/schema/isMinSize`,payload:{minSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMinSize(${e})`}),[Vo]:!0,arbitraryConstraint:{minSize:e},...t})}function Dh(e,t){return e=Th(e),B(t=>t.size<=e,{expected:`a value with a size of at most ${e}`,representation:{id:`effect/schema/isMaxSize`,payload:{maxSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMaxSize(${e})`}),[Vo]:!0,arbitraryConstraint:{maxSize:e},...t})}function Oh(e,t,n){return e=Th(e),t=Th(t),B(n=>n.size>=e&&n.size<=t,{expected:e===t?`a value with a size of ${e}`:`a value with a size between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenSize`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenSize(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function kh(e,t){return e=Th(e),B(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e},...t})}function Ah(e,t){return e=Th(e),B(t=>Reflect.ownKeys(t).length<=e,{expected:`a value with at most ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMaxProperties`,payload:{maxProperties:e}},toJsonSchema:({type:t})=>t===`object`?{maxProperties:e}:[{maxProperties:e},!0],toCode:()=>({runtime:`Schema.isMaxProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function jh(e,t,n){return e=Th(e),t=Th(t),B(n=>Reflect.ownKeys(n).length>=e&&Reflect.ownKeys(n).length<=t,{expected:e===t?`a value with exactly ${e===1?`1 entry`:`${e} entries`}`:`a value with between ${e} and ${t} entries`,representation:{id:`effect/schema/isBetweenProperties`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`object`?{minProperties:e,maxProperties:t}:[{minProperties:e,maxProperties:t},!0],toCode:()=>({runtime:`Schema.isBetweenProperties(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var Mh=M.check(vh());globalThis.RegExp,globalThis.URL;var Nh=M.annotate({expected:`a string that will be decoded as a Date`}),Ph=Mp(e=>e instanceof globalThis.Date&&!globalThis.Number.isNaN(e.getTime()),{representation:{id:`effect/schema/Date`,payload:null},toCode:()=>({runtime:`Schema.Date`,Type:`globalThis.Date`}),expected:`a valid Date`,toCodecJson:()=>Mm()(Nh,gc)}),Fh=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function U(e,t){return Fh.pipe(Sm(e,vc(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var Ih=M.annotate({expected:`a string that will be decoded as a number`}).pipe(Sm(N,mc)),Lh=M.check(Pm()),Rh=M.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(Sm(Lh,dc())),zh=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),Bh=jm(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>Mm()(zh,_c)}),Vh=uc({decode:(e,t)=>Wr(Co(e),{onNone:()=>v(new ms({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>x(wo(e))}),encode:e=>x(To(e))}),Hh=-864e13,Uh=864e13;function Wh(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function Gh(e,t){return H.check(eh({minimum:e,maximum:t}))}var Kh=Mp(e=>bo(e)&&xo(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=Wh(e,Hh,Uh);return Cm()(Gh(t,n),Ws(So))},toCodecJson:()=>Mm()(M,Vh),toFormatter:()=>e=>e.toString()}),qh=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(Sm(Kh,Vh));function Jh(e){return bp(e.ast)}function Yh(e,t){return pp(e.ast,t)}function Xh(e,t){return up(pp(zf(e.ast),t),t)}var Zh=Rf,Qh=$p(nu(id,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),$h=fm(M,Qh),eg=e=>crypto.getRandomValues(new Uint8Array(e)),tg=(e,t,n)=>{let r=256-256%e.length;if(r===256){let r=e.length-1;return(i=t)=>{if(!i)return``;let a=``;for(;;){let t=n(i),o=i;for(;o--;)if(a+=e[t[o]&r],a.length>=i)return a}}}let i=Math.ceil(409.6*t/r);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(t[s]<r&&(o+=e[t[s]%e.length],o.length>=a))return o}}},ng=(e,t=21)=>tg(e,t|0,eg),rg=`abcdefghijklmnopqrstuvwxyz0123456789`;function ig(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return ng(rg,e)()}var ag=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,og=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,sg=w().min(1).max(64).regex(ag),cg=w().min(1).max(64).regex(ag),lg=w().min(1).max(32).regex(og),ug=Qt({prefix:lg}),dg=Qt({family:sg,version:yr(1),kinds:si(cg,ug)}).superRefine((e,t)=>{let n=Object.entries(e.kinds);if(n.length<1||n.length>64){t.addIssue({code:`custom`,message:`Identifier families must declare between one and 64 kinds`});return}let r=new Set;for(let[,e]of n){if(r.has(e.prefix)){t.addIssue({code:`custom`,message:`Identifier kind prefixes must be distinct`});return}r.add(e.prefix)}}),fg=w(),pg=/^[a-z0-9]+$/,mg=new TextEncoder;function hg(e){return e===32||e>=9&&e<=13}function gg(e){let t=0,n=e.length;for(;t<n&&hg(e.charCodeAt(t));)t+=1;for(;n>t&&hg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function _g(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&pg.test(n)}let r=_(()=>jr(e=>{let t=fg.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=mg.encode(o).byteLength,c=r.safeParse(o),l=o.startsWith(t)?o.slice(t.length):void 0;if(s<3||s>96)a=`bounds`;else if(l!==void 0&&Array.from(l).length!==21)a=`bounds`;else if(c.success)return{ok:!0,value:c.data};else a=n(gg(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=_(()=>fg.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),ur)}));function o(){let n;try{n=ig(21)}catch{throw e.entropyUnavailable()}return r.parse(`${t}${n}`)}return{family:e.family,kind:e.kind,version:1,generate:o,schema:a,parse:i,is:e=>i(e).ok}}var vg=si(w(),Qt({family:w(),kind:w(),version:yr(1),generate:ct(),schema:t(Ut),parse:ct(),is:ct()})),yg=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},bg=class extends Error{name=`CairnGenerationError`;code=`entropy_unavailable`;family;kind;version=1;constructor(e){super(`Cairn entropy source is unavailable`),this.family=e.family,this.kind=e.kind}};function xg(e){let t;try{t=dg.safeParse(e)}catch{throw new yg}if(!t.success)throw new yg;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=_g({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new bg({family:n.family,kind:t})})}let i=jr(e=>{let t=vg.safeParse(e);if(!t.success)return!1;let r=Object.entries(t.data);return r.length===Object.keys(n.kinds).length&&r.every(([e,t])=>Object.hasOwn(n.kinds,e)&&t.kind===e&&t.family===n.family)}).safeParse(r);if(!i.success)throw new yg;return i.data}var Sg=_(()=>ln({id:w().min(1).max(256),name:w().min(1).max(128),kind:yr(`agent`).optional()})),Cg=_(()=>w().min(1).max(256)),wg=_(()=>ln({agentId:Cg,sessionId:Cg,commandId:Cg,outcome:Jt([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:w().min(1).max(200).optional(),waitingOnYou:Er(ln({itemId:Cg,kind:w().min(1).max(64),summary:w().min(1).max(200)})).min(1).max(8).optional()})),Tg=ln({author:Sg.optional(),sourceRequestId:Cg.optional(),delegation:ln({ancestors:Er(Cg).max(8),maxDepth:Mn().int().min(1).max(8),steer:yr(!0).optional(),goal:Qr([w().min(1).max(4e3),yr(!1)]).optional(),reply:wg.optional()}).optional()});function Eg(e){let t=Tg.safeParse(e);return t.success?t.data.author:void 0}var Dg=Symbol.for(`effect/MutableList/Empty`),Og=()=>({head:void 0,tail:void 0,length:0}),kg=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},Ag=()=>({array:[],mutable:!0,offset:0,next:void 0}),jg=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=Ag(),e.tail=e.tail.next):e.head=e.tail=Ag(),e.tail.array.push(t),e.length++},Mg=e=>{e.head=e.tail=void 0,e.length=0},Ng=(e,t)=>{if(t=_i(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return Mg(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?Mg(e):kg(e),n;i=i.next}return Mg(e),n},Pg=e=>Ng(e,e.length),Fg=e=>{if(!e.head)return Dg;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:Mg(e):kg(e),t},Ig=`~effect/Queue`,Lg=`~effect/Queue/Enqueue`,Rg=`~effect/Queue/Dequeue`,zg={_A:He,_E:He},Bg={[Ig]:zg,[Lg]:zg,[Rg]:zg,...de,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:r_(this)}}},Vg=e=>Se(t=>{let n=Object.create(Bg);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=Og(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},li(n)}),Hg=e=>Vg({capacity:e}),Ug=e=>Vg({capacity:e,strategy:`dropping`}),Wg=o(2,(e,t)=>ii(()=>Gg(e,t)?a_:e.state._tag===`Open`&&e.strategy===`suspend`?m_(e,t):i_)),Gg=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Fg(e.messages),jg(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(jg(e.messages,t),c_(e),!0):(jg(e.messages,t),l_(e),!0):!1,Kg=o(2,(e,t)=>qg(e,c(t))),qg=o(2,(e,t)=>_t(()=>Jg(e,t))),Jg=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=De(t),r=Fe(n,o_);return e.state.offers.size===0&&e.messages.length===0?(b_(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},l_(e),!0)},Yg=e=>Jg(e,c(ti())),Xg=e=>_t(()=>Zg(e)),Zg=e=>{if(e.state._tag===`Done`)return!1;Mg(e.messages);let t=e.state.offers;b_(e,e.state._tag===`Open`?s_:e.state.exit);for(let e of t)g_(e);return!0},Qg=e=>d_(()=>{if(e.state._tag===`Done`)return Qa(e.state.exit,()=>li([]));let t=y_(e);return v_(e),li(t)}),$g=e=>e_(e,1,1/0),e_=o(3,(e,t,n)=>(t=_i(t),n=_i(n),d_(()=>u_(e,t,n)??Qn(p_(e,()=>f_(e,t)),e_(e,t,n))))),t_=e=>d_(()=>n_(e)??Qn(p_(e,()=>f_(e,1)),t_(e))),n_=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Fg(e.messages);return v_(e),ze(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=__(e.state.offers);return v_(e),ze(t)}},r_=e=>e.state._tag===`Done`?0:e.messages.length,i_=ze(!1),a_=ze(!0),o_=he(ti()),s_=p(),c_=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(be),e.messages.length===0))break}},l_=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,c_(e)},0))},u_=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return ze([]);if(!f_(e,t))return;let r=e.messages.length>0?Ng(e.messages,n):[__(e.state.offers)];return v_(e),ze(r)},d_=jt({op:`QueueTake`,[Ye](e){let t=this[et]();return pi(t)?t[Ye](e):t}}),f_=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,p_=(e,t)=>Jn(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(be);let r={ready:t,resume:n};return e.state.takers.add(r),_t(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),m_=(e,t)=>Jn(n=>Gg(e,t)?n(a_):h_(e,{_tag:`Single`,message:t,resume:n})),h_=(e,t)=>{if(e.state._tag!==`Open`)return g_(t);let n=e.state.offers;return n.add(t),_t(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&b_(e,e.state.exit))})},g_=e=>e._tag===`Single`?e.resume(i_):e.resume(ze(e.remaining.slice(e.offset))),__=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(a_),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(ze([]))),n},v_=e=>{if(e.state._tag===`Done`)return $a(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(b_(e,e.state.exit),$a(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)jg(e.messages,t.message),e.state.offers.delete(t),t.resume(a_);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;jg(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(ze([]))}let r=e.state;if(r._tag===`Done`)return $a(r.exit.cause)}return!1},y_=e=>{if(e.messages.length>0){let t=Pg(e.messages);return v_(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[__(e.state.offers)];return v_(e),t}return[]},b_=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},x_=wr,S_=Kt,C_=Me,w_=Rr,T_=Vt,E_=Mr,D_=hr,O_=e=>new A_(e),k_=(e,t,n)=>Jn(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),_t(()=>{e.waiters.delete(i)})}),A_=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=ii(()=>this.free<e?k_(this,e,t):(this.taken+=e,li(e)));return t}takeIfAvailable(e){return ii(()=>this.free<e?li(!1):(this.taken+=e,li(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Se(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ei))}release(e){return Se(t=>li(this.releaseUnsafe(t,e)))}get releaseAll(){return Se(e=>li(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>te(n=>{let r=ii(()=>{if(this.free<e){let t=k_(this,e,ei);return Tn(n(t),()=>r)}return this.taken+=e,_n(n(t),()=>{this.releaseUnsafe(Rr(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>te(n=>this.free<e?dn:(this.taken+=e,_n(n(l(t)),()=>{this.releaseUnsafe(Rr(),e)},!0)))}},j_=e=>_t(()=>new A_(e)),M_=`~effect/Channel`,N_=e=>br(e,M_),P_={[M_]:{_Env:He,_InErr:He,_InElem:He,_OutErr:He,_OutElem:He},pipe(){return Le(this,arguments)}},F_=e=>{let t=Object.create(P_);return t.transform=(t,n)=>Br(e(t,n),e=>x(Zt(e))),t},I_=(e,t)=>F_((n,r)=>T(z_(e)(n,r),e=>t(e,r))),L_=e=>F_((t,n)=>e),R_=e=>F_(mt(function*(t,n){let r=ka(n),i=e=>Aa(r,ro(e)),a=yield*_e(e(t,n,r),i);return _e(a,i)})),z_=e=>e.transform,B_=4096,V_=(e,t,n)=>Vg({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(In(t=>Da(e,Xg(t))),In(n=>Ta(t(n),e).pipe(Br(e=>qg(n,e)),Ze(e)))),H_=(e,t)=>F_((n,r)=>we(V_(r,e,t),$g)),U_=e=>F_((t,n)=>sr(()=>z_(e())(t,n))),W_=e=>L_(y(()=>{let t=e();return sr(()=>{let e=t.next();return e.done?ta(e.value):x(e.value)})})),G_=(e,t=B_)=>{let n=vi(t);return L_(y(()=>{let t=e(),r=Cn();return sr(()=>{if(r._tag===`Some`)return ta(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return ta(n.value);r=Sr(n.value);break}e.push(n.value)}return x(e)})}))},K_=(e,t=B_)=>G_(()=>e[Symbol.iterator](),t),q_=e=>Z_(x(e)),J_=L_(x(ta())),Y_=e=>L_(x(v(e))),X_=e=>L_(Zt(e)),Z_=e=>L_(y(()=>{let t=!1;return sr(()=>t?ta():(t=!0,e))})),Q_=e=>L_(x($g(e))),$_=(e,t)=>F_(mt(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*Da(r,qt(()=>i.return()))),T(pn({try:()=>i.next(),catch:t}),e=>e.done?ta(e.value):x(e.value))})),ev=(e,t)=>tv($_(e,t),Pt),tv=o(2,(e,t)=>I_(e,e=>y(()=>{let n=0;return we(e,e=>t(e,n++))}))),nv=e=>e===void 0||e!==`unbounded`&&e<=1,rv=o(e=>N_(e[0]),(e,t,n)=>nv(n?.concurrency)?iv(e,t):av(e,t,n)),iv=(e,t)=>F_((n,r)=>{let i=0;return we(z_(e)(n,r),T(e=>t(e,i++)))}),av=(e,t,n)=>R_(mt(function*(r,i,a){let o=0,s=yield*z_(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Hg(0);yield*Da(a,Xg(l));let u=kr(yield*On()),d=T_(a);if(n.unordered){let e=O_(c),n=Xn(e.release(1)),r=kt({onFailure:e=>T(qg(l,e),n),onSuccess:e=>T(Wg(l,e),n)});yield*e.take(1).pipe(T(()=>s),T(e=>{let n=o++;return d(u(r(sr(()=>t(e,n))))),C}),bt({disableYield:!0}),Br(t=>e.withPermits(c-1)(qg(l,t))),Ze(a))}else{let e=yield*Hg(c-2);yield*Da(a,Xg(e)),yield*t_(e).pipe(ni,T(e=>Wg(l,e)),bt({disableYield:!0}),Br(e=>qg(l,e)),Ze(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,Jg(l,e.cause))};yield*s.pipe(T(i=>{if(n)return Zt(n);let a=o++,s=u(sr(()=>t(i,a)));return d(s),s.addObserver(r),Wg(e,S_(s))}),bt({disableYield:!0}),Br(t=>Wg(e,ia(t)).pipe(g(qg(e,t)))),Ze(a))}return t_(l)})),ov=o(e=>N_(e[0]),(e,t,n)=>nv(n?.concurrency)?sv(e,t):cv(e,t,n)),sv=(e,t)=>F_((n,r)=>we(z_(e)(n,r),e=>{let i,a,o=T(e,e=>(a??=ka(r),cn(z_(t(e))(n,a),e=>(i=s(e),i)))),s=Qa(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Aa(a,sa);return a=void 0,T(t,()=>o)});return sr(()=>i??o)})),cv=(e,t,n)=>e.pipe(tv(t),hv(n)),lv=e=>ov(e,He),uv=e=>I_(e,e=>{let t,n=0,r=sr(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return x(e[0]);default:return t=e,x(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),x(i)});return x(r)}),dv=o(2,(e,t)=>I_(e,e=>x(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return At(i)?x(i):T(e,n)})))),fv=o(2,(e,t)=>F_((n,r)=>{let i=ka(r);return we(z_(e)(n,i),e=>{let a=e.pipe(Br(e=>{if($a(e))return Zt(e);let o=i;return i=ka(r),Aa(o,ia(e)).pipe(g(z_(t(e))(n,i)),T(e=>(a=e,e)))}));return sr(()=>a)})})),pv=o(3,(e,t,n)=>fv(e,e=>{let r=t(e);return Ae(r)?X_(r.failure):n(r.success,e)})),mv=o(2,(e,t)=>pv(e,Yi,e=>t(e))),hv=o(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>R_(mt(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:O_(s),l=yield*D_(!0),u=new Set,d=yield*Hg(t);yield*Da(o,Xg(d));let f=yield*z_(e)(i,a);return yield*b(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*ce(f),yield*Dn(c.take(1),g(S_(e),Nt))));let t=e===void 0?yield*f:yield*S_(e),n=ka(o),r=yield*z_(t)(i,n);for(;u.size>=s;){let e=yi(u);u.delete(e),u.size===0&&(yield*l.open),yield*C_(e)}let a=yield*r.pipe(In(()=>fe),T(e=>Wg(d,e)),bt({disableYield:!0}),_e(mt(function*(e){let t=ro(e),r=yield*Ln(Aa(n,t));if(!u.has(a))return;let i=fa([t,r]);la(i)&&(yield*qg(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),ce);l.closeUnsafe(),u.add(a)}}).pipe(Br(e=>{let t=to(e);return Wt(t)?l.whenOpen(qg(d,e)):qg(d,e)}),Ze(o)),t_(d)}))),gv=o(e=>N_(e[0])&&N_(e[1]),(e,t,n)=>R_(mt(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Hg(0);yield*Da(a,Xg(s));let c=0;function l(e,t){if(c++,!$a(t))return qg(s,t);switch(o){case`both`:return c===2?qg(s,t):C;case`left`:case`right`:return e===o?qg(s,t):C;case`either`:return qg(s,t)}}let u=(e,t,n)=>z_(t)(r,n).pipe(T(e=>e.pipe(T(e=>Wg(s,e)),bt)),_e(t=>Cr(ro(t),e=>Aa(n,e)).pipe(kt({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Ze(a));return yield*u(`left`,e,ka(a)),yield*u(`right`,t,ka(a)),t_(s)}))),_v=e=>F_((t,n)=>{let r;return x(sr(()=>r||e.pipe(Ta(n),T(e=>z_(e)(t,n)),T(e=>r=e))))}),vv=o(2,(e,t)=>gv(e,L_(x(T(t,ta))),{haltStrategy:`either`})),yv=o(2,(e,t)=>R_((n,r,i)=>Ea(i,t).pipe(g(z_(e)(n,r))))),bv=o(2,(e,t)=>yv(e,e=>t)),xv=(e,t,n)=>sr(()=>{let r=wa(),i=z_(e)(ta(),r);return Qa(T(i,t),n||x).pipe(Ne(e=>Aa(r,e)))}),Sv=o(2,(e,t)=>xv(e,e=>bt(T(e,t),{disableYield:!0}))),Cv=mt(function*(e){let t=O_(1),n=yield*On(),r=Ee(n,Sa);return(yield*z_(e)(ta(),r)).pipe(st(n),t.withPermits(1))},Br(e=>x(Zt(e)))),wv=(e,t)=>z_(e)(ta(),t),Tv=`~effect/Stream`,Ev={_R:He,_E:He,_A:He},Dv=function(e){this.channel=e};Dv.prototype={[Tv]:Ev,pipe(){return Le(this,arguments)}};var Ov=e=>new Dv(e),kv=`~effect/Sink`,Av={_A:He,_In:He,_L:He,_E:He,_R:He},jv={[kv]:Av,pipe(){return Le(this,arguments)}},Mv=e=>{let t=Object.create(jv);return t.transform=e,t},Nv=((e,t,n)=>Mv(r=>{let i=e(),a;return t(i)?r.pipe(T(e=>{for(let r=0;r<e.length;r++)if(i=n(i,e[r]),!t(i))return r+1<e.length&&(a=e.slice(r+1)),ta();return C}),bt({disableYield:!0}),Qa(()=>x([i,a]))):x([i])}))(Cn,on,(e,t)=>Sr(t)),Pv=()=>Nv,Fv=`~effect/Stream`,Iv=e=>br(e,Fv),Lv=Ov,Rv=e=>Lv(Z_(we(e,Pt))),zv=e=>Vv(x(T(e,()=>ta()))),Bv=e=>Vv(x(we(e,Pt))),Vv=e=>Lv(L_(e)),Hv=(e,t)=>Lv(F_((n,r)=>T(wv(e.channel,r),e=>t(e,r)))),Uv=e=>e.channel,Wv=(e,t)=>Lv(H_(e,t)),Gv=Lv(J_),Kv=e=>Lv(q_(Pt(e))),qv=e=>Lv(U_(()=>e().channel)),Jv=e=>Lv(Y_(e)),Yv=e=>Lv(X_(e)),Xv=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Zv(e):Lv(K_(e,t?.chunkSize)),Zv=e=>At(e)?Lv(q_(e)):Gv,Qv=e=>Lv(Q_(e)),$v=(e,t)=>Lv(ev(e,t)),ey=(e,t)=>Vv(y(()=>{let n=e,r=!1;return sr(function e(){return r?ta():T(t(n),([t,i])=>(on(i)?r=!0:n=i.value,At(t)?x(t):e()))})})),ty=e=>Lv(_v(we(e,Uv))),ny=o(2,(e,t)=>qv(()=>{let n=0;return Lv(tv(e.channel,Et(e=>t(e,n++))))})),ry=o(e=>Iv(e[0]),(e,t,n)=>e.channel.pipe(uv,rv(t,n),tv(Pt),Lv)),iy=e=>e.pipe(ny(n),hy(e=>Kv(ve(e)))),ay=o(e=>Iv(e[0]),(e,t,n)=>e.channel.pipe(uv,ov(e=>t(e).channel,n),Lv)),oy=o(2,(e,t)=>{let n=ue(t.duration);if(!ae(n))return e;if($e(n))return qv(t.orElse);let r=Symbol();return my(qv(()=>{let t=w_().getRef(ja),i=s(n),a,o=E_(!1);return dy(Hv(e,(e,n)=>sr(()=>(a=t.currentTimeMillisUnsafe()+i,o.openUnsafe(),e)).pipe(we(e=>(o.closeUnsafe(),a=void 0,e)),x)),zv(b(function*(){for(;;)if(yield*o.await,a!==void 0&&(yield*jn(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*vr(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Yv(e))}),sy=e=>ay(e,Xv),cy=o(2,(e,t)=>{let n=Lv(lv(W_(()=>uy(e,t))));return ly.set(n,[e,t]),n}),ly=new WeakMap;function*uy(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=ly.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var dy=o(e=>Iv(e[0])&&Iv(e[1]),(e,t,n)=>Lv(gv(Uv(e),Uv(t),n))),fy=o(2,(e,t)=>Lv(dv(Uv(e),t))),py=o(2,mt(function*(e,t){let n,r=yield*Cv(e.channel),i=Br(r,e=>(n=e,Zt(e))),[a,o]=yield*Gr(e=>t.transform(i,e)),s=n?Gv:Vv(x(r));return o&&(s=cy(Zv(o),s)),[a,s]})),my=o(2,(e,t)=>e.channel.pipe(fv(e=>t(e).channel),Lv)),hy=o(2,(e,t)=>Lv(mv(e.channel,e=>t(e).channel))),gy=o(e=>Iv(e[0]),(e,t,n)=>Hv(e,(e,r)=>y(()=>{let r=0,i=!1;return T(sr(()=>i?ta():e),e=>{let a=e.findIndex(e=>t(e,r++));if(a>=0){i=!0;let t=e.slice(0,n?.excludeLast?a:a+1);return At(t)?x(t):ta()}return x(e)})}))),_y=o(2,(e,t)=>Lv(vv(e.channel,t))),vy=o(2,(e,t)=>Lv(bv(e.channel,t))),yy=o(2,(e,t)=>Sv(e.channel,e=>{let n=0;return wt({while:()=>n<e.length,body:()=>t(e[n++]),step:Qe})})),by=o(2,(e,t)=>({[Symbol.asyncIterator](){let n=sn(t),r=kr(t),i=wa(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Ar(g(t?C_(t):C,Aa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(nt(`Suppressed error while closing Stream async iterator`,e))}};return{async next(){if(c)return c;if(o){let e=o.next();if(!e.done)return e;o=void 0}let t=r(a??T(wv(e.channel,i),e=>(a=e,e)));s=t;let d=await n(x_(t));if(s===t&&(s=void 0),ca(d))return o=d.value[Symbol.iterator](),o.next();if($a(d.cause))return l(sa);if(c&&Ki(d.cause))return c;throw await u(d),Ji(d.cause)},return(){return l(sa)},async throw(e){throw await u(oa(e)),e}}}})),xy=e=>by(e,me()),Sy=15e3,Cy=45e3,wy=Mh.check(yh(256)),Ty=H.check(V(0)),Ey=P({agentId:wy,sessionId:wy,name:wy}),Dy=P({by:Ey,reason:L([`escalated`,`sender_archived`,`sender_absent`]),note:k(M.check(yh(1e3)))}),Oy=P({id:wy,kind:Mh.check(yh(64)),summary:Mh.check(yh(200)),since:Ty,expiresAt:A(Ty),inbox:A(j(!1)),waitingOn:A(Ey),escalated:A(Dy)}),ky=Oy.mapFields(e=>({...e,extensionId:wy})),Ay=4096,jy=F(ky).check(yh(64)),My=M.pipe(z(gh(1)),z(yh(256))),Ny=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Py=P({providerId:My,modelId:My,reasoning:A(L(Ny))}),Fy=O(R(Py)),Iy=O(U(R(Py))),Ly=L([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),Ry=L([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),zy=M.pipe(z(gh(1)),z(yh(256))),By=P({_tag:j(`ShiitakeError`),boundary:Ly,cause:Ry,message:M,requestId:k(zy)}),W=class extends Error{boundary;requestId;_tag=`ShiitakeError`;cause;underlying;constructor(e,t,n,r,i){super(n),this.boundary=e,this.requestId=r,this.name=`ShiitakeError`,this.cause=t,this.underlying=i}},Vy=new TextEncoder;function Hy(e){return M.check(gh(1),yh(e),B(t=>Vy.encode(t).byteLength<=e))}var Uy=/\p{Cs}/u,Wy=Hy(256).check(B(e=>!Uy.test(e))),Gy=Hy(262144),Ky=P({type:j(`image`),data:M.check(gh(1),yh(1048576),Rm()),mimeType:M.check(B(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),qy=F(Ky).check(gh(1),yh(8)),Jy=L([`steer`,`followUp`]),Yy=Wy,Xy=D(P({commandId:Wy,timeoutMs:H.check(V(0),$m(3e4))}),{onExcessProperty:`error`});D(P({commandId:Wy,timeoutMs:Ih.check(nh(),eh({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Zy=D(Hy(512)),Qy=P({requestId:Wy}),$y=P({delivery:Jy,requestId:Wy,type:j(`prompt`),text:M.check(yh(262144),B(e=>Vy.encode(e).byteLength<=262144)),images:k(qy)}).check(B(e=>(e.text.length>0||(e.images?.length??0)>0)&&Vy.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),eb=P({type:j(`abort`)}),tb=P({commandId:Wy,onlyIfPending:A(cm),type:j(`cancel`)}),nb=P({type:j(`operator`),requestId:Wy,author:L([`operator`,`party`]),text:Gy}),rb=P({type:j(`branch`),entryId:Wy}),ib=P({type:j(`fork`),entryId:Wy}),ab=M.check(gh(1),yh(4096)),ob=P({type:j(`compact`),requestId:Wy,instructions:k(ab)}),sb=I([$y,ob]),cb=M.check(B(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),lb=I([$y,eb,tb,rb,ib,nb,ob,P({type:j(`title`),title:R(cb)})]),ub=P({command:lb}),db=P({includeSandboxFailures:A(cm),limit:A(H.check(eh({minimum:1,maximum:200}))),before:A(Hy(512))}),fb=P({includeSandboxFailures:A(j(`true`)),limit:A(Ih.check(nh(),eh({minimum:1,maximum:200}))),before:A(Hy(512))}),pb=P({includeSandboxFailures:A(cm),after:A(M)}),mb=P({includeSandboxFailures:A(j(`true`)),mode:A(j(`subscribe`)),after:A(M),limit:A(Ih.check(nh(),eh({minimum:1,maximum:200})))}),hb={onExcessProperty:`error`},gb=D(Yy,hb),_b=D(Qy,hb),vb=D(sb,hb);D(Wy);var yb=D(lb,hb);D(ub,hb);var bb=D(I([db,sm]),hb);D(fb,hb);var xb=D(pb,hb);D(mb,hb);function Sb(e){let t=gb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session id is invalid`);return t.success}function Cb(e){let t=Zy(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function wb(e){let t=_b(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function Tb(e){let t=bb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Read options are invalid`);let n=t.success??{},r={limit:n.limit??200};return n.before!==void 0&&(r={...r,before:n.before}),n.includeSandboxFailures!==void 0&&(r={...r,includeSandboxFailures:n.includeSandboxFailures}),Object.freeze(r)}function Eb(e){let t=xb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Subscribe options are invalid`);let n={};return t.success.after!==void 0&&(n={...n,after:t.success.after}),t.success.includeSandboxFailures!==void 0&&(n={...n,includeSandboxFailures:t.success.includeSandboxFailures}),Object.freeze(n)}function Db(e,t){if(Ae(e))throw new W(`contract`,`invalid`,t);return e.success}var Ob=bn();function kb(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function Ab(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e.charCodeAt(r)-t.charCodeAt(r);if(n!==0)return n}return e.length-t.length}function jb(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[_./:-]/g,` `).toLowerCase().trim()}function Mb(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var Nb=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function Pb(e){return Nb.has(e)}function Fb(e){let t=[],n=n=>{n!==e&&n.length>=3&&!t.includes(n)&&t.push(n)};return e.endsWith(`ing`)&&e.length>4&&n(e.slice(0,-3)),e.endsWith(`ed`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`ation`)&&e.length>6&&n(`${e.slice(0,-3)}e`),e.endsWith(`ies`)&&e.length>4&&(n(e.slice(0,-3)),n(`${e.slice(0,-3)}y`)),e.endsWith(`es`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`s`)&&!e.endsWith(`ss`)&&e.length>3&&n(e.slice(0,-1)),t}function Ib(e){let t=8997,n=33826,r=40164,i=52210;for(let a=0;a<e.length;a+=1){let o=t^e.charCodeAt(a),s=o*435,c=n*435+(s>>>16),l=r*435+(c>>>16)+(o<<8),u=i*435+(l>>>16)+(n<<8);t=s&65535,n=c&65535,r=l&65535,i=u&65535}return i.toString(16).padStart(4,`0`)+r.toString(16).padStart(4,`0`)+n.toString(16).padStart(4,`0`)+t.toString(16).padStart(4,`0`)}function Lb(e){return e.slice(e.indexOf(`.`)+1)}function Rb(e){return e.slice(0,e.indexOf(`.`))}var zb=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,Bb=1e3,Vb=221;function Hb(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Hb(r,t+1));return n}if(!kb(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Hb(r,t+1));return n}var Ub=_(()=>si(w(),bn()).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:`custom`,message:`Sample exceeds the entry bound`}),JSON.stringify(e).length>4e3&&t.addIssue({code:`custom`,message:`Sample exceeds the byte bound`}),Hb(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Wb=_(()=>Qt({query:w().max(200),maxResults:Mn().int().min(1).max(50).default(50)})),Gb=_(()=>Qt({path:w().max(160),detail:Jt([`index`,`full`]).default(`full`),methods:Er(w().max(80)).max(50).optional()})),Kb=Qt({cursor:w().max(400).optional(),limit:Mn().int().min(1).max(50).default(50),namespace:w().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),qb=_(()=>Qt({path:w().max(160),capabilityNotes:w().max(500).optional()})),Jb=Qt({path:w().max(160),description:w().max(1e3).optional(),score:Mn().min(0).max(Vb),matchReason:w().max(500).optional(),sample:Ub.optional(),capabilityNotes:w().max(500).optional(),peers:Er(qb).max(1e3).optional()}),Yb=_(()=>Qt({results:Er(Jb).max(50),total:Mn().int().min(0).max(Bb),truncated:pr(),topScore:Mn().min(0).max(Vb),margin:Mn().min(0).max(Vb),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)})),Xb=Qt({results:Er(Jb).max(50),total:Mn().int().min(0).max(Bb),nextCursor:w().max(400).nullable(),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)}),Zb=_(()=>Qt({path:w().max(160),description:w().max(1e3).optional(),types:w().max(2e4),inputSchema:bn().refine(e=>JSON.stringify(e).length<=2e4&&Hb(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:Jt([`module`,`operation`]),usage:w().max(300).optional()}));_(()=>Qt({code:Jt([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:w().max(1e3)}));var Qb=_(()=>Qt({"~standard":Qt({jsonSchema:Qt({input:t(Function),output:t(Function)})})})),$b=_(()=>jr(e=>Qb.safeParse(e).success,`Expected a Standard JSON Schema`)),ex=_(()=>Qt({path:w().min(3).max(160).regex(zb),description:w().max(1e3).optional(),input:$b,output:$b.optional(),capabilityNotes:w().max(500).optional(),instructions:w().max(1e3).optional()})),tx=_(()=>Qt({revision:w().min(1).max(160),operations:Er(ex).max(Bb)})),nx=class extends Error{code;failure;constructor(e,t,n){let r=t.slice(0,1e3);super(r,n),this.name=`ForageError`,this.code=e,this.failure={code:e,message:r}}},rx=Qr([ir({$ref:w().optional(),$defs:si(w(),xt()).optional(),definitions:si(w(),xt()).optional(),const:xt().optional(),enum:Er(xt()).optional(),oneOf:Er(xt()).optional(),anyOf:Er(xt()).optional(),allOf:Er(xt()).optional(),type:Qr([w(),Er(w())]).optional(),properties:si(w(),xt()).optional(),additionalProperties:xt().optional(),required:Er(w()).optional(),prefixItems:Er(xt()).optional(),items:xt().optional(),examples:Er(xt()).optional(),default:xt().optional()}),pr()]),ix=new WeakMap;function ax(e,t){let n=ix.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`})}catch{throw new nx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}cx(i);let a={raw:i};return n===void 0&&(n={},ix.set(e,n)),n[t]=a,a}function ox(e,t){return ax(e,t).raw}function sx(e,t){let n=ax(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new nx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function cx(e){let t=rx.safeParse(e);if(!t.success)throw new nx(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var lx=256,ux=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function dx(e,t,n){let r=ux.exec(e)?.[1];if(r===void 0||n.expanding.has(r))return`unknown`;let i=n.definitions[r];if(i===void 0)return`unknown`;if(n.budget.expansions+=1,n.budget.expansions>lx)throw new nx(`invalid_input`,`Schema references expand more than ${String(lx)} times; flatten its shared definitions`);return px(cx(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function fx(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=ux.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&fx(cx(r),{definitions:t.definitions,expanding:new Set([...t.expanding,n]),budget:t.budget})}return e.const===void 0?e.enum!==void 0&&e.enum.length>1||e.oneOf!==void 0&&e.oneOf.length>1||e.anyOf!==void 0&&e.anyOf.length>1:!1}function px(e,t,n){if(t>12||e===!0||e===!1)return`unknown`;let r=n??{definitions:{...e.definitions,...e.$defs},expanding:new Set,budget:{expansions:0}};if(e.$ref)return dx(e.$ref,t,r);if(e.const!==void 0)return JSON.stringify(e.const);if(e.enum)return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(e.oneOf)return e.oneOf.map(e=>px(cx(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>px(cx(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=cx(e),i=px(n,t+1,r);return fx(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>Ab(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${px(cx(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
4
|
+
${n.map(([e,n])=>{let a=px(cx(n),t+1,r),o=i.has(e)?``:`?`,s=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e);return`${` `.repeat(t+1)}${s}${o}: ${a};`}).join(`
|
|
5
5
|
`)}
|
|
6
|
-
${` `.repeat(t)}}`}if(e.type===`array`){let n=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>
|
|
6
|
+
${` `.repeat(t)}}`}if(e.type===`array`){let n=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>px(cx(e),t+1,r));return n!==void 0&&n!==!0&&!Array.isArray(n)&&i.push(`...${px(cx(n),t+1,r)}[]`),`[${i.join(`, `)}]`}if(n!==void 0&&Array.isArray(n))return`[${n.map(e=>px(cx(e),t+1,r)).join(`, `)}][]`;let i=n===void 0||cx(n),a=px(i,t+1,r);return`${i!==!0&&i!==!1&&(i.oneOf!==void 0||i.anyOf!==void 0||i.allOf!==void 0)?`(${a})`:a}[]`}switch(e.type){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`unknown`}}function mx(e,t=`input`){return px(cx(ox(e,t)),0)}function hx(e){return e.replace(/[^A-Za-z0-9_$]/g,`_`)}function gx(e,t,n){let r=`(input: ${t}) => Promise<${n}>`;for(let t of e.split(`.`).reverse())r=`{ [${JSON.stringify(t)}]: ${r} }`;return r}function _x(e){return e.length===0?``:`export declare const env: ${e.map(e=>e.indexEnvironment).join(` & `)};`}function vx(e){let t=e.map(e=>e.types).join(`
|
|
7
7
|
|
|
8
|
-
`);return e.length===0?t:`${t}\nexport declare const env: ${e.map(e=>e.environment).join(` & `)};`}var
|
|
9
|
-
`+n),inputBytes:t.length,outputBytes:n.length,sample:
|
|
10
|
-
`))}function Px(e,t){if(e===t)return`exact`;if(e.startsWith(t))return`startsWith`;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`\\b${n}\\b`).test(e))return`phrase`;let r=jb(e);return r.some(e=>e===t)?`token`:r.some(e=>e.startsWith(t))?`prefix`:r.some(e=>e.includes(t))?`substring`:e.includes(t)?`includes`:`none`}function Fx(e,t,n){let r=Ab(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...Pb(e)],s=`none`;for(let e of n){let t=Px(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=Tx[s]*Ex[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function Ix(e,t){let n=Ab(e);return[t,...Pb(t)].some(e=>n.includes(e))}function Lx(e){let t=[];for(let[n,r]of e){if(r.level===`none`)continue;let e=r.matchedTokens.slice(0,4).map(e=>e.slice(0,20));t.push(`${n}:${r.level}(${e.join(` `)})`)}return t.length>0?t.join(`; `):void 0}function Rx(e){let t=Jb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Search output exceeded its bounds`);return t.data}function zx(e){return[Ib(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Bx(e){return Rx({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Vx(e,t,n){let r=Lb(e.path),i=Ib(e.path),a=e.description??``,o=[e.path,r,i,a],s=Fx(e.path,`path`,t),c=Fx(r,`namespace`,t),l=Fx(i,`method`,t),u=Fx(a,`description`,t),d=n.filter(e=>o.some(t=>Ix(t,e))).length;if(d===0)return;let f=d/n.length,p=Math.max(s.score,c.score,l.score,u.score);if(p===0)return;let m=d===n.length?Dx:f*Ox,ee=n[0];ee&&o.some(e=>Ix(e,ee))&&(m+=kx),(s.level===`exact`||l.level===`exact`)&&(m+=Ax);let te={path:e.path,score:d+(p+m)/Mx};a&&(te.description=a);let ne=Lx([[`method`,l],[`description`,u],[`path`,s],[`namespace`,c]]);return ne&&(te.matchReason=ne),e.sample&&(te.sample=e.sample),e.capabilityNotes&&(te.capabilityNotes=e.capabilityNotes),{result:te,cluster:zx(e),pathScore:s.score}}function Hx(e){let t=new Map;for(let n of e){let e=t.get(n.cluster)??[];e.push(n),t.set(n.cluster,e)}let n=[];for(let e of t.values()){let t=[...e].sort((e,t)=>t.pathScore-e.pathScore||t.result.score-e.result.score||kb(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>kb(e.result.path,t.result.path));for(let e of a){let t={path:e.result.path};e.result.capabilityNotes&&(t.capabilityNotes=e.result.capabilityNotes),i.push(t)}let o={...r.result,score:Math.max(...t.map(e=>e.result.score))};i.length>0&&(o.peers=i),n.push(o)}return n.sort((e,t)=>t.score-e.score||kb(e.path,t.path))}function Ux(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return Rx({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function Wx(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=jb(Ab(t)),o=a.filter(e=>!Nb(e));if(o.length===0)return Bx(r);let s=[];for(let t of e){let e=Vx(t,a,o);e&&s.push(e)}return Ux(Hx(s),i,r)}var Gx=ln({catalogStamp:Yb.shape.catalogStamp,namespace:Gb.shape.namespace.unwrap().nullable(),after:qb.shape.path});function Kx(e,t,n){let r=Gb.safeParse(n);if(!r.success)throw new tx(`invalid_input`,r.error.message);let i=r.data,a=i.namespace??null,o=e.filter(e=>a===null||e.path.startsWith(`${a}.`)).sort((e,t)=>kb(Lb(e.path),Lb(t.path))||kb(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=Gx.parse(JSON.parse(i.cursor))}catch(e){throw new tx(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new tx(`invalid_input`,`Listing cursor belongs to a different catalog or namespace`);let n=o.findIndex(t=>t.path===e.after);if(n<0)throw new tx(`invalid_input`,`Listing cursor operation is absent from this view`);s=n+1}let c=o.slice(s,s+i.limit),l=c.at(-1);return Yb.parse({results:c,total:o.length,catalogStamp:t,nextCursor:s+c.length<o.length&&l!==void 0?JSON.stringify({catalogStamp:t,namespace:a,after:l.path}):null})}var qx=1e6;function Jx(t,n=0){if(n>=16)return t.length===0?n:n+1;let r=n;for(let i=t.length-1;i>=0;--i){let a=t[i],o=n+1;if(Array.isArray(a)?o=Jx(a,o):e(a)&&(o=Jx(Object.values(a),o)),r=Math.max(r,o),r>16)return r}return r}function Yx(e){let t=ex.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new tx(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>kb(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new tx(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),ox(e.input,`input`).length>2e4||Jx(Object.values(ax(e.input,`input`)))>16)throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?ox(e.output,`output`).length:0)>2e4||e.output!==void 0&&Jx(Object.values(ax(e.output,`output`)))>16)throw new tx(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=wx(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||Vb(n,0)>16))throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if(i.push(t),a+=t.inputBytes+t.outputBytes+o+e.path.length,a+=e.description?.length??0,a+=e.capabilityNotes?.length??0,a+=e.instructions?.length??0,a>qx)throw new tx(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function Xx(e){let t=Yx(e),n=Object.freeze(t.operations),r=Nx(n),i=n.map(e=>{let t={path:e.path,score:0};return e.description!==void 0&&(t.description=e.description),e.sample!==void 0&&(t.sample=e.sample),e.capabilityNotes!==void 0&&(t.capabilityNotes=e.capabilityNotes),t});return Object.freeze({revision:t.revision,search:e=>{let t=Ub.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new tx(`empty_query`,`Search query must not be empty`);return Wx(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Wb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new tx(`empty_query`,`Description target must not be empty`);return Cx(n,t.data)},list:e=>Kx(i,r,e),stamp:()=>r})}var Zx=_(()=>w().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),Qx=_(()=>si(w(),bn()));_(()=>Qr([Qx,pr()]));var $x=_(()=>Qt({tool:Zx,title:w().max(120),description:w().max(1e3),input:si(w(),bn()),output:si(w(),bn()),call:si(w(),bn())}).catchall(bn()));_(()=>hn(`kind`,[ln({kind:yr(`unindexed`)}),ln({kind:yr(`ready`),tools:Er($x).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var eS=Object.freeze({replay:`safe`,path:`forage.search`,description:`Search operation names and descriptions with short keywords, such as read or shell. If no results match, retry with one relevant keyword. Describe known operation paths directly with forage.describe.`,input:Ub,output:Jb}),tS=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Wb,output:Xb}),nS=Object.freeze({replay:`safe`,path:`forage.list`,description:`List every available operation in stable namespace then path order (UTF-16 code units). Use limit (1–50) and nextCursor to page without duplicates, optionally filtering by exact namespace. total counts all operations in that filter; summaries match search, with score 0 and no peer merging. A cursor belongs to this catalog and filter; describe paths before calling them.`,input:Gb,output:Yb});Object.freeze({createCatalog:Xx,forageSearchDefinition:eS,forageDescribeDefinition:tS,forageListDefinition:nS});var rS=`invalid_definition`,iS=`runtime_closed`,aS=`source_failure`,G=class extends Error{code=rS;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},oS=class extends Error{code=iS;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},sS=class extends Error{sourceId;phase;code=aS;constructor(e,t){super(e===void 0?`Capability source ${t} failed`:`Capability source ${t} failed: ${e}`),this.sourceId=e,this.phase=t,this.name=`MyceliumSourceError`}},cS=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},lS=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},uS=class extends zi(`SourceInvalid`){},dS=class extends zi(`GuestThrew`){},fS=class extends zi(`DeadlineExceeded`){},pS=class extends zi(`SandboxBusy`){code=`sandbox-busy`},mS=class extends zi(`Cancelled`){},hS=class extends zi(`DispatchLost`){},gS=class extends zi(`SandboxCrashed`){},_S=class extends zi(`BadResponse`){},vS=class extends zi(`ResultTooLarge`){},yS=class extends zi(`ResultNotJson`){},bS=class extends zi(`CapabilityFailed`){constructor(e){super(e),this.message=CS(this)}},xS=class extends zi(`Unknown`){};function SS(e,t){switch(e._tag){case`SourceInvalid`:return new uS({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new dS({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new fS({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new pS({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new mS({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new hS({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new gS({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new _S({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new vS({size:e.size,ref:t});case`ResultNotJson`:return new yS({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new bS({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new xS({rawCause:e.rawCause,ref:t})}}function CS(e,t=!0){let n;switch(e._tag){case`SourceInvalid`:n=`SyntaxError in submitted source line ${String(e.line)}, column ${String(e.column)}: ${e.excerpt.slice(0,160)}. Nothing ran. Fix quote/heredoc nesting: quote multi-line shell text with a JavaScript template literal or \\n escapes; escape backticks and \${ inside it. If a nested heredoc is hard to quote, write the script with Files, then execute it.`;break;case`GuestThrew`:{let t=e.name.slice(0,80),r=e.message.slice(0,512),i=e.missingVariable;n=`${t}: ${r}${i===void 0?``:`. Declare ${i} with const or let before assigning it; this sandbox does not create implicit globals. Each execute call has its own variables.`}`;break}case`DeadlineExceeded`:n=`execute hit its ${String(e.limitMs)} ms deadline after ${String(e.elapsedMs)} ms; split the work or persist progress${e.acknowledged===!1?`; sandbox did not acknowledge cancellation`:``}`;break;case`SandboxBusy`:n=`sandbox-busy: all ${String(e.capacity)} sandbox slots remained occupied after waiting ${String(e.waitedMs)} ms. Nothing ran; retry this call after capacity becomes available.`;break;case`Cancelled`:n=e.acknowledged===!1?`Sandbox did not acknowledge cancellation`:`Execution was cancelled`;break;case`DispatchLost`:n=`The sandbox lost contact after ${String(e.elapsedMs)} ms; a running command may still be running; check its effects before retrying`;break;case`SandboxCrashed`:n=`The sandbox process stopped before answering; check effects before retrying`;break;case`BadResponse`:n=`The sandbox returned an unreadable result; retry once, split the call if it recurs`;break;case`ResultTooLarge`:n=`Sandbox result exceeds 256 KiB`;break;case`ResultNotJson`:n=`Sandbox returned non-JSON data`;break;case`CapabilityFailed`:n=e.cause.message.slice(0,1e3);break;case`Unknown`:return`The sandbox failed for an unrecognized reason${t?` (ref ${e.ref??`unavailable`})`:``}`}return!t||e.ref===void 0?n:`${n} (ref ${e.ref})`}var wS=_(()=>Qr([t(uS),t(dS),t(fS),t(pS),t(mS),t(hS),t(gS),t(_S),t(vS),t(yS),t(bS),t(xS)])),TS=_(()=>xt().pipe(Qr([t(Error).transform(e=>({kind:`error`,value:e})),wn().transform(e=>({kind:`null`,value:e})),Ir().transform(e=>({kind:`undefined`,value:e})),w().transform(e=>({kind:`string`,value:e})),pr().transform(e=>({kind:`boolean`,value:e})),Qr([Mn(),Rn(),yr(1/0),yr(-1/0)]).transform(e=>({kind:`number`,value:e})),nn().transform(e=>({kind:`bigint`,value:e})),ht().transform(e=>({kind:`symbol`,value:e})),t(Function).transform(e=>({kind:`function`,value:e})),Er(xt()).transform(e=>({kind:`array`,value:e})),Qr([t(Object),si(w(),xt())]).transform(e=>({kind:`object`,value:e})),xt().transform(()=>({kind:`opaque`}))])));function ES(e){return wS.safeParse(e).success}function DS(e){let t=wS.safeParse(e);return t.success?t.data:new xS({rawCause:e})}function OS(e){let t=TS.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}_(()=>bn().optional());function kS(e){return AS(e,new Set)}function AS(e,t){let n=TS.parse(e);switch(n.kind){case`null`:case`undefined`:return null;case`string`:case`boolean`:return n.value;case`number`:return Number.isFinite(n.value)?n.value:String(n.value);case`bigint`:case`symbol`:return String(n.value);case`function`:return{kind:`function`,name:n.value.name};case`opaque`:return{kind:`opaque`};case`error`:case`array`:case`object`:{let r=n.value;if(t.has(e))return{kind:`circular_reference`};t.add(e);try{if(n.kind===`array`)return n.value.map(e=>AS(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,AS(n,t)]));if(n.kind===`error`){let r=n.value;e.name=r.name,e.message=r.message,r.stack!==void 0&&(e.stack=r.stack),r.cause!==void 0&&(e.cause=AS(r.cause,t)),r instanceof AggregateError&&(e.errors=AS(r.errors,t))}return e}finally{t.delete(e)}}}}var jS=_(()=>Qt({name:yr(`ReferenceError`),message:w().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));_(()=>Qr([jS,Qt({name:w(),message:w()})]).and(Qt({transportMessage:w().max(512).optional()})));var MS=_(()=>ln({v:yr(1),kind:yr(`sandbox_failure`),tag:Jt([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:w().min(1).max(32),message:w().max(160)})),NS=D(U(am)),PS=_(()=>w().transform((e,t)=>{let n=NS(e);return Ae(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),ur):n.success})).pipe(MS);ln({error:PS}),_(()=>xt().pipe(Qr([yr(`Execution timed out`).transform(()=>({kind:`deadline`})),xt().transform(e=>({kind:`bad_response`,rawCause:e}))])));var FS=ln({sandboxCapacity:Vr().positive().optional(),admissionWaitMs:Vr().min(1).max(9e5).optional()});function IS(e,t){let n=FS.safeParse(e??{}),r=Vr().positive().safeParse(t??2);if(!n.success||!r.success)throw new G(`Sandbox admission policy is invalid`);return Object.freeze({capacity:n.data.sandboxCapacity??Math.min(32,Math.max(2,r.data)),waitMs:n.data.admissionWaitMs??18e4})}var LS=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],RS=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],zS=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,BS=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,VS={3:`abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile`,5:`class enum extends super const export import`,6:`enum`,strict:`implements interface let package private protected public static yield`,strictBind:`eval arguments`},HS=`break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this`,US={5:HS,"5module":HS+` export import`,6:HS+` const class extends export import super`},WS=/^in(stanceof)?$/,GS=RegExp(`[`+BS+`]`),KS=RegExp(`[`+BS+zS+`]`);function qS(e,t){for(var n=65536,r=0;r<t.length;r+=2){if(n+=t[r],n>e)return!1;if(n+=t[r+1],n>=e)return!0}return!1}function JS(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&GS.test(String.fromCharCode(e)):t!==!1&&qS(e,RS)}function YS(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&KS.test(String.fromCharCode(e)):t===!1?!1:qS(e,RS)||qS(e,LS)}var K=function(e,t){t===void 0&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function XS(e,t){return new K(e,{beforeExpr:!0,binop:t})}var ZS={beforeExpr:!0},QS={startsExpr:!0},$S={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,$S[e]=new K(e,t)}var J={num:new K(`num`,QS),regexp:new K(`regexp`,QS),string:new K(`string`,QS),name:new K(`name`,QS),privateId:new K(`privateId`,QS),eof:new K(`eof`),bracketL:new K(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new K(`]`),braceL:new K(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new K(`}`),parenL:new K(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new K(`)`),comma:new K(`,`,ZS),semi:new K(`;`,ZS),colon:new K(`:`,ZS),dot:new K(`.`),question:new K(`?`,ZS),questionDot:new K(`?.`),arrow:new K(`=>`,ZS),template:new K(`template`),invalidTemplate:new K(`invalidTemplate`),ellipsis:new K(`...`,ZS),backQuote:new K("`",QS),dollarBraceL:new K("${",{beforeExpr:!0,startsExpr:!0}),eq:new K(`=`,{beforeExpr:!0,isAssign:!0}),assign:new K(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new K(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new K(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:XS(`||`,1),logicalAND:XS(`&&`,2),bitwiseOR:XS(`|`,3),bitwiseXOR:XS(`^`,4),bitwiseAND:XS(`&`,5),equality:XS(`==/!=/===/!==`,6),relational:XS(`</>/<=/>=`,7),bitShift:XS(`<</>>/>>>`,8),plusMin:new K(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:XS(`%`,10),star:XS(`*`,10),slash:XS(`/`,10),starstar:new K(`**`,{beforeExpr:!0}),coalesce:XS(`??`,1),_break:q(`break`),_case:q(`case`,ZS),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,ZS),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,ZS),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,QS),_if:q(`if`),_return:q(`return`,ZS),_switch:q(`switch`),_throw:q(`throw`,ZS),_try:q(`try`),_var:q(`var`),_const:q(`const`),_while:q(`while`,{isLoop:!0}),_with:q(`with`),_new:q(`new`,{beforeExpr:!0,startsExpr:!0}),_this:q(`this`,QS),_super:q(`super`,QS),_class:q(`class`,QS),_extends:q(`extends`,ZS),_export:q(`export`),_import:q(`import`,QS),_null:q(`null`,QS),_true:q(`true`,QS),_false:q(`false`,QS),_in:q(`in`,{beforeExpr:!0,binop:7}),_instanceof:q(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:q(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:q(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:q(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},eC=/\r\n?|\n|\u2028|\u2029/,tC=new RegExp(eC.source,`g`);function nC(e){return e===10||e===13||e===8232||e===8233}function rC(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(nC(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var iC=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,aC=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,oC=Object.prototype,sC=oC.hasOwnProperty,cC=oC.toString,lC=Object.hasOwn||(function(e,t){return sC.call(e,t)}),uC=Array.isArray||(function(e){return cC.call(e)===`[object Array]`}),dC=Object.create(null);function fC(e){return dC[e]||(dC[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function pC(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var mC=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,hC=function(e,t){this.line=e,this.column=t};hC.prototype.offset=function(e){return new hC(this.line,this.column+e)};var gC=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function _C(e,t){for(var n=1,r=0;;){var i=rC(e,r,t);if(i<0)return new hC(n,t-r);++n,r=i}}var vC={ecmaVersion:null,sourceType:`script`,strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,startLocation:null,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},yC=!1;function bC(e){var t={};for(var n in vC)t[n]=e&&lC(e,n)?e[n]:vC[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!yC&&typeof console==`object`&&console.warn&&(yC=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
11
|
-
Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),t.allowReserved??=t.ecmaVersion<5,(!e||e.allowHashBang==null)&&(t.allowHashBang=t.ecmaVersion>=14),
|
|
12
|
-
`,n-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(eC).length)):this.lineStart=0,this.type=J.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType===`module`,this.strict=this.inModule||e.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)===`#!`&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType===`commonjs`?CC:SC),this.regexpState=null,this.privateNameStack=[]},HC={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};VC.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},HC.inFunction.get=function(){return(this.currentVarScope().flags&CC)>0},HC.inGenerator.get=function(){return(this.currentVarScope().flags&TC)>0},HC.inAsync.get=function(){return(this.currentVarScope().flags&wC)>0},HC.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(AC|jC))return!1;if(t&CC)return(t&wC)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},HC.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&SC)},HC.allowSuper.get=function(){return(this.currentThisScope().flags&OC)>0||this.options.allowSuperOutsideMethod},HC.allowDirectSuper.get=function(){return(this.currentThisScope().flags&kC)>0},HC.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},HC.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(AC|jC)||t&CC&&!(t&EC))return!0}return!1},HC.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&MC||!this.inModule&&e&SC)},HC.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&AC)>0},VC.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var n=this,r=0;r<e.length;r++)n=e[r](n);return n},VC.parse=function(e,t){return new this(t,e).parse()},VC.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},VC.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(VC.prototype,HC);var UC=VC.prototype,WC=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;UC.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){aC.lastIndex=e,e+=aC.exec(this.input)[0].length;var t=WC.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){aC.lastIndex=e+t[0].length;var n=aC.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||eC.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,aC.lastIndex=e,e+=aC.exec(this.input)[0].length,this.input[e]===`;`&&e++}},UC.eat=function(e){return this.type===e&&(this.next(),!0)},UC.isContextual=function(e){return this.type===J.name&&this.value===e&&!this.containsEsc},UC.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},UC.catchStackOverflow=function(e){try{return e()}catch(e){if(e instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message)||/\btoo much recursion\b/i.test(e.message)))this.raise(this.start,`Not enough stack space to parse input`);else throw e}},UC.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},UC.canInsertSemicolon=function(){return this.type===J.eof||this.type===J.braceR||eC.test(this.input.slice(this.lastTokEnd,this.start))},UC.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},UC.semicolon=function(){!this.eat(J.semi)&&!this.insertSemicolon()&&this.unexpected()},UC.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},UC.expect=function(e){this.eat(e)||this.unexpected()},UC.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var GC=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};UC.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,`Comma is not permitted after the rest element`);var n=t?e.parenthesizedAssign:e.parenthesizedBind;n>-1&&this.raiseRecoverable(n,t?`Assigning to rvalue`:`Parenthesized pattern`)}},UC.checkExpressionErrors=function(e,t){if(!e)return!1;var n=e.shorthandAssign,r=e.doubleProto;if(!t)return n>=0||r>=0;n>=0&&this.raise(n,`Shorthand property assignments are valid only in destructuring patterns`),r>=0&&this.raiseRecoverable(r,`Redefinition of __proto__ property`)},UC.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,`Yield expression cannot be a default value`),this.awaitPos&&this.raise(this.awaitPos,`Await expression cannot be a default value`)},UC.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var Y=VC.prototype;Y.parseTopLevel=function(e){var t=Object.create(null);for(e.body||=[];this.type!==J.eof;){var n=this.parseStatement(null,!0,t);e.body.push(n)}if(this.inModule)for(var r=0,i=Object.keys(this.undefinedExports);r<i.length;r+=1){var a=i[r];this.raiseRecoverable(this.undefinedExports[a].start,`Export '`+a+`' is not defined`)}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType===`commonjs`?`script`:this.options.sourceType,this.finishNode(e,`Program`)};var KC={kind:`loop`},qC={kind:`switch`};Y.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;aC.lastIndex=this.pos;var t=aC.exec(this.input),n=this.pos+t[0].length,r=this.fullCharCodeAt(n);if(r===91||r===92)return!0;if(e)return!1;if(r===123)return!0;if(JS(r)){var i=n;do n+=r<=65535?1:2;while(YS(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!WS.test(a))return!0}return!1},Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;aC.lastIndex=this.pos;var e=aC.exec(this.input),t=this.pos+e[0].length,n;return!eC.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(YS(n=this.fullCharCodeAt(t+8))||n===92))},Y.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;aC.lastIndex=this.pos;var n=aC.exec(this.input),r=this.pos+n[0].length;if(eC.test(this.input.slice(this.pos,r)))return!1;if(e){var i=r+5,a;if(this.input.slice(r,i)!==`using`||i===this.input.length||YS(a=this.fullCharCodeAt(i))||a===92)return!1;aC.lastIndex=i;var o=aC.exec(this.input);if(r=i+o[0].length,o&&eC.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!JS(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(YS(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(WS.test(l))return!1;if(t&&!e&&l===`of`){aC.lastIndex=r;var u=aC.exec(this.input);if(r+=u[0].length,this.input.charCodeAt(r)!==61||(s=this.input.charCodeAt(r+1))===61||s===62)return!1}return!0},Y.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},Y.isUsing=function(e){return this.isUsingKeyword(!1,e)},Y.parseStatement=function(e,t,n){var r=this.type,i=this.startNode(),a;switch(this.isLet(e)&&(r=J._var,a=`let`),r){case J._break:case J._continue:return this.parseBreakContinueStatement(i,r.keyword);case J._debugger:return this.parseDebuggerStatement(i);case J._do:return this.parseDoStatement(i);case J._for:return this.parseForStatement(i);case J._function:return e&&(this.strict||e!==`if`&&e!==`label`)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case J._class:return e&&this.unexpected(),this.parseClass(i,!0);case J._if:return this.parseIfStatement(i);case J._return:return this.parseReturnStatement(i);case J._switch:return this.parseSwitchStatement(i);case J._throw:return this.parseThrowStatement(i);case J._try:return this.parseTryStatement(i);case J._const:case J._var:return a||=this.value,e&&a!==`var`&&this.unexpected(),this.parseVarStatement(i,a);case J._while:return this.parseWhileStatement(i);case J._with:return this.parseWithStatement(i);case J.braceL:return this.parseBlock(!0,i);case J.semi:return this.parseEmptyStatement(i);case J._export:case J._import:if(this.options.ecmaVersion>10&&r===J._import){aC.lastIndex=this.pos;var o=aC.exec(this.input),s=this.pos+o[0].length,c=this.input.charCodeAt(s);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,`'import' and 'export' may only appear at the top level`),this.inModule||this.raise(this.start,`'import' and 'export' may appear only with 'sourceType: module'`)),r===J._import?this.parseImport(i):this.parseExport(i,n);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.isAwaitUsing(!1)?`await using`:this.isUsing(!1)?`using`:null;if(l)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,`Using declaration is not allowed in single-statement positions`),l===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.next(),this.parseVar(i,!1,l),this.semicolon(),this.finishNode(i,`VariableDeclaration`);var u=this.value,d=this.parseExpression();return r===J.name&&d.type===`Identifier`&&this.eat(J.colon)?this.parseLabeledStatement(i,u,d,e):this.parseExpressionStatement(i,d)}},Y.parseBreakContinueStatement=function(e,t){var n=t===`break`;this.next(),this.eat(J.semi)||this.insertSemicolon()?e.label=null:this.type===J.name?(e.label=this.parseIdent(),this.semicolon()):this.unexpected();for(var r=0;r<this.labels.length;++r){var i=this.labels[r];if((e.label==null||i.name===e.label.name)&&(i.kind!=null&&(n||i.kind===`loop`)||e.label&&n))break}return r===this.labels.length&&this.raise(e.start,`Unsyntactic `+t),this.finishNode(e,n?`BreakStatement`:`ContinueStatement`)},Y.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,`DebuggerStatement`)},Y.parseDoStatement=function(e){return this.next(),this.labels.push(KC),e.body=this.parseStatement(`do`),this.labels.pop(),this.expect(J._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(J.semi):this.semicolon(),this.finishNode(e,`DoWhileStatement`)},Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual(`await`)?this.lastTokStart:-1;if(this.labels.push(KC),this.enterScope(0),this.expect(J.parenL),this.type===J.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var n=this.isLet();if(this.type===J._var||this.type===J._const||n){var r=this.startNode(),i=n?`let`:this.value;return this.next(),this.parseVar(r,!0,i),this.finishNode(r,`VariableDeclaration`),this.parseForAfterInit(e,r,t)}var a=this.isContextual(`let`),o=!1,s=this.isUsing(!0)?`using`:this.isAwaitUsing(!0)?`await using`:null;if(s){var c=this.startNode();return this.next(),s===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.parseVar(c,!0,s),this.finishNode(c,`VariableDeclaration`),this.parseForAfterInit(e,c,t)}var l=this.containsEsc,u=new GC,d=this.start,f=t>-1?this.parseExprSubscripts(u,`await`):this.parseExpression(!0,u);return this.type===J._in||(o=this.options.ecmaVersion>=6&&this.isContextual(`of`))?(t>-1?(this.type===J._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(f.start===d&&!l&&f.type===`Identifier`&&f.name===`async`?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),a&&o&&this.raise(f.start,`The left-hand side of a for-of loop may not start with 'let'.`),this.toAssignable(f,!1,u),this.checkLValPattern(f),this.parseForIn(e,f)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,f))},Y.parseForAfterInit=function(e,t,n){return(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))&&t.declarations.length===1?(this.type===J._in?((t.kind===`using`||t.kind===`await using`)&&!t.declarations[0].init&&this.raise(this.start,`Using declaration is not allowed in for-in loops`),this.options.ecmaVersion>=9&&n>-1&&this.unexpected(n)):this.options.ecmaVersion>=9&&(e.await=n>-1),this.parseForIn(e,t)):(n>-1&&this.unexpected(n),this.parseFor(e,t))},Y.parseFunctionStatement=function(e,t,n){return this.next(),this.parseFunction(e,YC|(n?0:XC),!1,t)},Y.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(`if`),e.alternate=this.eat(J._else)?this.parseStatement(`if`):null,this.finishNode(e,`IfStatement`)},Y.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,`'return' outside of function`),this.next(),this.eat(J.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,`ReturnStatement`)},Y.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(J.braceL),this.labels.push(qC),this.enterScope(MC);for(var t,n=!1;this.type!==J.braceR;)if(this.type===J._case||this.type===J._default){var r=this.type===J._case;t&&this.finishNode(t,`SwitchCase`),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,`Multiple default clauses`),n=!0,t.test=null),this.expect(J.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,`SwitchCase`),this.next(),this.labels.pop(),this.finishNode(e,`SwitchStatement`)},Y.parseThrowStatement=function(e){return this.next(),eC.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,`Illegal newline after throw`),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,`ThrowStatement`)};var JC=[];Y.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?DC:0),this.checkLValPattern(e,t?zC:LC),this.expect(J.parenR),e},Y.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===J._catch){var t=this.startNode();this.next(),this.eat(J.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,`CatchClause`)}return e.finalizer=this.eat(J._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,`Missing catch or finally clause`),this.finishNode(e,`TryStatement`)},Y.parseVarStatement=function(e,t,n){return this.next(),this.parseVar(e,!1,t,n),this.semicolon(),this.finishNode(e,`VariableDeclaration`)},Y.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(KC),e.body=this.parseStatement(`while`),this.labels.pop(),this.finishNode(e,`WhileStatement`)},Y.parseWithStatement=function(e){return this.strict&&this.raise(this.start,`'with' in strict mode`),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(`with`),this.finishNode(e,`WithStatement`)},Y.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,`EmptyStatement`)},Y.parseLabeledStatement=function(e,t,n,r){for(var i=0,a=this.labels;i<a.length;i+=1)a[i].name===t&&this.raise(n.start,`Label '`+t+`' is already declared`);for(var o=this.type.isLoop?`loop`:this.type===J._switch?`switch`:null,s=this.labels.length-1;s>=0;s--){var c=this.labels[s];if(c.statementStart===e.start)c.statementStart=this.start,c.kind=o;else break}return this.labels.push({name:t,kind:o,statementStart:this.start}),e.body=this.parseStatement(r?r.indexOf(`label`)===-1?r+`label`:r:`label`),this.labels.pop(),e.label=n,this.finishNode(e,`LabeledStatement`)},Y.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,`ExpressionStatement`)},Y.parseBlock=function(e,t,n){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(J.braceL),e&&this.enterScope(0);this.type!==J.braceR;){var r=this.parseStatement(null);t.body.push(r)}return n&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,`BlockStatement`)},Y.parseFor=function(e,t){return e.init=t,this.expect(J.semi),e.test=this.type===J.semi?null:this.parseExpression(),this.expect(J.semi),e.update=this.type===J.parenR?null:this.parseExpression(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,`ForStatement`)},Y.parseForIn=function(e,t){var n=this.type===J._in;return this.next(),t.type===`VariableDeclaration`&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!==`var`||t.declarations[0].id.type!==`Identifier`)&&this.raise(t.start,(n?`for-in`:`for-of`)+` loop variable declaration may not have an initializer`),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssign(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,n?`ForInStatement`:`ForOfStatement`)},Y.parseVar=function(e,t,n,r){for(e.declarations=[],e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(J.eq)?i.init=this.parseMaybeAssign(t):!r&&n===`const`&&!(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))?this.unexpected():!r&&(n===`using`||n===`await using`)&&this.options.ecmaVersion>=17&&this.type!==J._in&&!this.isContextual(`of`)?this.raise(this.lastTokEnd,`Missing initializer in `+n+` declaration`):!r&&i.id.type!==`Identifier`&&!(t&&(this.type===J._in||this.isContextual(`of`)))?this.raise(this.lastTokEnd,`Complex binding patterns require an initialization value`):i.init=null,e.declarations.push(this.finishNode(i,`VariableDeclarator`)),!this.eat(J.comma))break}return e},Y.parseVarId=function(e,t){e.id=t===`using`||t===`await using`?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t===`var`?IC:LC,!1)};var YC=1,XC=2,ZC=4;Y.parseFunction=function(e,t,n,r,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===J.star&&t&XC&&this.unexpected(),e.generator=this.eat(J.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&YC&&(e.id=t&ZC&&this.type!==J.name?null:this.parseIdent(),e.id&&!(t&XC)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?IC:LC:RC));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(PC(e.async,e.generator)),t&YC||(e.id=this.type===J.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n,!1,i),this.yieldPos=a,this.awaitPos=o,this.awaitIdentPos=s,this.finishNode(e,t&YC?`FunctionDeclaration`:`FunctionExpression`)},Y.parseFunctionParams=function(e){this.expect(J.parenL),e.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),i=this.startNode(),a=!1;for(i.body=[],this.expect(J.braceL);this.type!==J.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type===`MethodDefinition`&&o.kind===`constructor`?(a&&this.raiseRecoverable(o.start,`Duplicate constructor in the same class`),a=!0):o.key&&o.key.type===`PrivateIdentifier`&&QC(r,o)&&this.raiseRecoverable(o.key.start,`Identifier '#`+o.key.name+`' has already been declared`))}return this.strict=n,this.next(),e.body=this.finishNode(i,`ClassBody`),this.exitClassBody(),this.finishNode(e,t?`ClassDeclaration`:`ClassExpression`)},Y.parseClassElement=function(e){if(this.eat(J.semi))return null;var t=this.options.ecmaVersion,n=this.startNode(),r=``,i=!1,a=!1,o=`method`,s=!1;if(this.eatContextual(`static`)){if(t>=13&&this.eat(J.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===J.star?s=!0:r=`static`}if(n.static=s,!r&&t>=8&&this.eatContextual(`async`)&&((this.isClassElementNameStart()||this.type===J.star)&&!this.canInsertSemicolon()?a=!0:r=`async`),!r&&(t>=9||!a)&&this.eat(J.star)&&(i=!0),!r&&!a&&!i){var c=this.value;(this.eatContextual(`get`)||this.eatContextual(`set`))&&(this.isClassElementNameStart()?o=c:r=c)}if(r?(n.computed=!1,n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),n.key.name=r,this.finishNode(n.key,`Identifier`)):this.parseClassElementName(n),t<13||this.type===J.parenL||o!==`method`||i||a){var l=!n.static&&$C(n,`constructor`),u=l&&e;l&&o!==`method`&&this.raise(n.key.start,`Constructor can't have get/set modifier`),n.kind=l?`constructor`:o,this.parseClassMethod(n,i,a,u)}else this.parseClassField(n);return n},Y.isClassElementNameStart=function(){return this.type===J.name||this.type===J.privateId||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword},Y.parseClassElementName=function(e){this.type===J.privateId?(this.value===`constructor`&&this.raise(this.start,`Classes can't have an element named '#constructor'`),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},Y.parseClassMethod=function(e,t,n,r){var i=e.key;e.kind===`constructor`?(t&&this.raise(i.start,`Constructor can't be a generator`),n&&this.raise(i.start,`Constructor can't be an async method`)):e.static&&$C(e,`prototype`)&&this.raise(i.start,`Classes may not have a static property named prototype`);var a=e.value=this.parseMethod(t,n,r);return e.kind===`get`&&a.params.length!==0&&this.raiseRecoverable(a.start,`getter should have no params`),e.kind===`set`&&a.params.length!==1&&this.raiseRecoverable(a.start,`setter should have exactly one param`),e.kind===`set`&&a.params[0].type===`RestElement`&&this.raiseRecoverable(a.params[0].start,`Setter cannot use rest params`),this.finishNode(e,`MethodDefinition`)},Y.parseClassField=function(e){return $C(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&$C(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(J.eq)?(this.enterScope(jC|OC),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,`PropertyDefinition`)},Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(AC|OC);this.type!==J.braceR;){var n=this.parseStatement(null);e.body.push(n)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,`StaticBlock`)},Y.parseClassId=function(e,t){this.type===J.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,LC,!1)):(t===!0&&this.unexpected(),e.id=null)},Y.parseClassSuper=function(e){e.superClass=this.eat(J._extends)?this.parseExprSubscripts(null,!1):null},Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},Y.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,n=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,i=r===0?null:this.privateNameStack[r-1],a=0;a<n.length;++a){var o=n[a];lC(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function QC(e,t){var n=t.key.name,r=e[n],i=`true`;return t.type===`MethodDefinition`&&(t.kind===`get`||t.kind===`set`)&&(i=(t.static?`s`:`i`)+t.kind),r===`iget`&&i===`iset`||r===`iset`&&i===`iget`||r===`sget`&&i===`sset`||r===`sset`&&i===`sget`?(e[n]=`true`,!1):r?!0:(e[n]=i,!1)}function $C(e,t){var n=e.computed,r=e.key;return!n&&(r.type===`Identifier`&&r.name===t||r.type===`Literal`&&r.value===t)}Y.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual(`as`)?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual(`from`),this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ExportAllDeclaration`)},Y.parseExport=function(e,t){if(this.next(),this.eat(J.star))return this.parseExportAllDeclaration(e,t);if(this.eat(J._default))return this.checkExport(t,`default`,this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,`ExportDefaultDeclaration`);if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type===`VariableDeclaration`?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual(`from`))this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var n=0,r=e.specifiers;n<r.length;n+=1){var i=r[n];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type===`Literal`&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,`ExportNamedDeclaration`)},Y.parseExportDeclaration=function(e){return this.parseStatement(null)},Y.parseExportDefaultDeclaration=function(){var e;if(this.type===J._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,YC|ZC,!1,e)}if(this.type===J._class){var n=this.startNode();return this.parseClass(n,`nullableID`)}var r=this.parseMaybeAssign();return this.semicolon(),r},Y.checkExport=function(e,t,n){e&&(typeof t!=`string`&&(t=t.type===`Identifier`?t.name:t.value),lC(e,t)&&this.raiseRecoverable(n,`Duplicate export '`+t+`'`),e[t]=!0)},Y.checkPatternExport=function(e,t){var n=t.type;if(n===`Identifier`)this.checkExport(e,t,t.start);else if(n===`ObjectPattern`)for(var r=0,i=t.properties;r<i.length;r+=1){var a=i[r];this.checkPatternExport(e,a)}else if(n===`ArrayPattern`)for(var o=0,s=t.elements;o<s.length;o+=1){var c=s[o];c&&this.checkPatternExport(e,c)}else n===`Property`?this.checkPatternExport(e,t.value):n===`AssignmentPattern`?this.checkPatternExport(e,t.left):n===`RestElement`&&this.checkPatternExport(e,t.argument)},Y.checkVariableExport=function(e,t){if(e)for(var n=0,r=t;n<r.length;n+=1){var i=r[n];this.checkPatternExport(e,i.id)}},Y.shouldParseExportStatement=function(){return this.type.keyword===`var`||this.type.keyword===`const`||this.type.keyword===`class`||this.type.keyword===`function`||this.isLet()||this.isAsyncFunction()},Y.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual(`as`)?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,`ExportSpecifier`)},Y.parseExportSpecifiers=function(e){var t=[],n=!0;for(this.expect(J.braceL);!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;t.push(this.parseExportSpecifier(e))}return t},Y.parseImport=function(e){return this.next(),this.type===J.string?(e.specifiers=JC,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual(`from`),e.source=this.type===J.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ImportDeclaration`)},Y.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual(`as`)?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportSpecifier`)},Y.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportDefaultSpecifier`)},Y.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual(`as`),e.local=this.parseIdent(),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportNamespaceSpecifier`)},Y.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===J.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(J.comma)))return e;if(this.type===J.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(J.braceL);!this.eat(J.braceR);){if(t)t=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;e.push(this.parseImportSpecifier())}return e},Y.parseWithClause=function(){var e=[];if(!this.eat(J._with))return e;this.expect(J.braceL);for(var t={},n=!0;!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;var r=this.parseImportAttribute(),i=r.key.type===`Identifier`?r.key.name:r.key.value;lC(t,i)&&this.raiseRecoverable(r.key.start,`Duplicate attribute key '`+i+`'`),t[i]=!0,e.push(r)}return e},Y.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`),this.expect(J.colon),this.type!==J.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,`ImportAttribute`)},Y.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===J.string){var e=this.parseLiteral(this.value);return mC.test(e.value)&&this.raise(e.start,`An export name cannot include a lone surrogate.`),e}return this.parseIdent(!0)},Y.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},Y.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&e.type===`ExpressionStatement`&&e.expression.type===`Literal`&&typeof e.expression.value==`string`&&(this.input[e.start]===`"`||this.input[e.start]===`'`)};var ew=VC.prototype;ew.toAssignable=function(e,t,n){if(this.options.ecmaVersion>=6&&e)switch(e.type){case`Identifier`:this.inAsync&&e.name===`await`&&this.raise(e.start,`Cannot use 'await' as identifier inside an async function`);break;case`ObjectPattern`:case`ArrayPattern`:case`AssignmentPattern`:case`RestElement`:break;case`ObjectExpression`:e.type=`ObjectPattern`,n&&this.checkPatternErrors(n,!0);for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.toAssignable(a,t),a.type===`RestElement`&&(a.argument.type===`ArrayPattern`||a.argument.type===`ObjectPattern`)&&this.raise(a.argument.start,`Unexpected token`)}break;case`Property`:e.kind!==`init`&&this.raise(e.key.start,`Object pattern can't contain getter or setter`),this.toAssignable(e.value,t);break;case`ArrayExpression`:e.type=`ArrayPattern`,n&&this.checkPatternErrors(n,!0),this.toAssignableList(e.elements,t);break;case`SpreadElement`:e.type=`RestElement`,this.toAssignable(e.argument,t),e.argument.type===`AssignmentPattern`&&this.raise(e.argument.start,`Rest elements cannot have a default value`);break;case`AssignmentExpression`:e.operator!==`=`&&this.raise(e.left.end,`Only '=' operator can be used for specifying default value.`),e.type=`AssignmentPattern`,delete e.operator,this.toAssignable(e.left,t);break;case`ParenthesizedExpression`:this.toAssignable(e.expression,t,n);break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:if(!t)break;default:this.raise(e.start,`Assigning to rvalue`)}else n&&this.checkPatternErrors(n,!0);return e},ew.toAssignableList=function(e,t){for(var n=e.length,r=0;r<n;r++){var i=e[r];i&&this.toAssignable(i,t)}if(n){var a=e[n-1];this.options.ecmaVersion===6&&t&&a&&a.type===`RestElement`&&a.argument.type!==`Identifier`&&this.unexpected(a.argument.start)}return e},ew.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},ew.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==J.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,`RestElement`)},ew.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case J.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(J.bracketR,!0,!0),this.finishNode(e,`ArrayPattern`);case J.braceL:return this.parseObj(!0)}return this.parseIdent()},ew.parseBindingList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);)if(a?a=!1:this.expect(J.comma),t&&this.type===J.comma)i.push(null);else if(n&&this.afterTrailingComma(e))break;else if(this.type===J.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.expect(e);break}else i.push(this.parseAssignableListItem(r));return i},ew.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},ew.parseBindingListItem=function(e){return e},ew.parseMaybeDefault=function(e,t,n){if(n||=this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(J.eq))return n;var r=this.startNodeAt(e,t);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,`AssignmentPattern`)},ew.checkLValSimple=function(e,t,n){t===void 0&&(t=FC);var r=t!==FC;switch(e.type){case`Identifier`:this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(r?`Binding `:`Assigning to `)+e.name+` in strict mode`),r&&(t===LC&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(lC(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==BC&&this.declareName(e.name,t,e.start));break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:r&&this.raiseRecoverable(e.start,`Binding member expression`);break;case`ParenthesizedExpression`:return r&&this.raiseRecoverable(e.start,`Binding parenthesized expression`),this.checkLValSimple(e.expression,t,n);default:this.raise(e.start,(r?`Binding`:`Assigning to`)+` rvalue`)}},ew.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=FC),e.type){case`ObjectPattern`:for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,t,n)}break;case`ArrayPattern`:for(var o=0,s=e.elements;o<s.length;o+=1){var c=s[o];c&&this.checkLValInnerPattern(c,t,n)}break;default:this.checkLValSimple(e,t,n)}},ew.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=FC),e.type){case`Property`:this.checkLValInnerPattern(e.value,t,n);break;case`AssignmentPattern`:this.checkLValPattern(e.left,t,n);break;case`RestElement`:this.checkLValPattern(e.argument,t,n);break;default:this.checkLValPattern(e,t,n)}};var tw=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},nw={b_stat:new tw(`{`,!1),b_expr:new tw(`{`,!0),b_tmpl:new tw("${",!1),p_stat:new tw(`(`,!1),p_expr:new tw(`(`,!0),q_tmpl:new tw("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new tw(`function`,!1),f_expr:new tw(`function`,!0),f_expr_gen:new tw(`function`,!0,!1,null,!0),f_gen:new tw(`function`,!1,!1,null,!0)},rw=VC.prototype;rw.initialContext=function(){return[nw.b_stat]},rw.curContext=function(){return this.context[this.context.length-1]},rw.braceIsBlock=function(e){var t=this.curContext();return t===nw.f_expr||t===nw.f_stat?!0:e===J.colon&&(t===nw.b_stat||t===nw.b_expr)?!t.isExpr:e===J._return||e===J.name&&this.exprAllowed?eC.test(this.input.slice(this.lastTokEnd,this.start)):e===J._else||e===J.semi||e===J.eof||e===J.parenR||e===J.arrow?!0:e===J.braceL?t===nw.b_stat:e===J._var||e===J._const||e===J.name?!1:!this.exprAllowed},rw.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token===`function`)return t.generator}return!1},rw.updateContext=function(e){var t,n=this.type;n.keyword&&e===J.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},rw.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},J.parenR.updateContext=J.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===nw.b_stat&&this.curContext().token===`function`&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},J.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?nw.b_stat:nw.b_expr),this.exprAllowed=!0},J.dollarBraceL.updateContext=function(){this.context.push(nw.b_tmpl),this.exprAllowed=!0},J.parenL.updateContext=function(e){var t=e===J._if||e===J._for||e===J._with||e===J._while;this.context.push(t?nw.p_stat:nw.p_expr),this.exprAllowed=!0},J.incDec.updateContext=function(){},J._function.updateContext=J._class.updateContext=function(e){e.beforeExpr&&e!==J._else&&(e!==J.semi||this.curContext()===nw.p_stat)&&!(e===J._return&&eC.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==J.colon&&e!==J.braceL||this.curContext()!==nw.b_stat)?this.context.push(nw.f_expr):this.context.push(nw.f_stat),this.exprAllowed=!1},J.colon.updateContext=function(){this.curContext().token===`function`&&this.context.pop(),this.exprAllowed=!0},J.backQuote.updateContext=function(){this.curContext()===nw.q_tmpl?this.context.pop():this.context.push(nw.q_tmpl),this.exprAllowed=!1},J.star.updateContext=function(e){if(e===J._function){var t=this.context.length-1;this.context[t]===nw.f_expr?this.context[t]=nw.f_expr_gen:this.context[t]=nw.f_gen}this.exprAllowed=!0},J.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==J.dot&&(this.value===`of`&&!this.exprAllowed||this.value===`yield`&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var X=VC.prototype;X.checkPropClash=function(e,t,n){if(!(this.options.ecmaVersion>=9&&e.type===`SpreadElement`)&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var r=e.key,i;switch(r.type){case`Identifier`:i=r.name;break;case`Literal`:i=String(r.value);break;default:return}var a=e.kind;if(this.options.ecmaVersion>=6){i===`__proto__`&&a===`init`&&(t.proto&&(n?n.doubleProto<0&&(n.doubleProto=r.start):this.raiseRecoverable(r.start,`Redefinition of __proto__ property`)),t.proto=!0);return}i=`$`+i;var o=t[i];o?(a===`init`?this.strict&&o.init||o.get||o.set:o.init||o[a])&&this.raiseRecoverable(r.start,`Redefinition of property`):o=t[i]={init:!1,get:!1,set:!1},o[a]=!0}},X.parseExpression=function(e,t){var n=this;return this.catchStackOverflow(function(){var r=n.start,i=n.startLoc,a=n.parseMaybeAssign(e,t);if(n.type===J.comma){var o=n.startNodeAt(r,i);for(o.expressions=[a];n.eat(J.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return n.finishNode(o,`SequenceExpression`)}return a})},X.parseMaybeAssign=function(e,t,n){if(this.isContextual(`yield`)){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var r=!1,i=-1,a=-1,o=-1;t?(i=t.parenthesizedAssign,a=t.trailingComma,o=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new GC,r=!0);var s=this.start,c=this.startLoc;(this.type===J.parenL||this.type===J.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=e===`await`);var l=this.parseMaybeConditional(e,t);if(n&&(l=n.call(this,l,s,c)),this.type.isAssign){var u=this.startNodeAt(s,c);return u.operator=this.value,this.type===J.eq&&(l=this.toAssignable(l,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=l.start&&(t.shorthandAssign=-1),this.type===J.eq?this.checkLValPattern(l):this.checkLValSimple(l),u.left=l,this.next(),u.right=this.parseMaybeAssign(e),o>-1&&(t.doubleProto=o),this.finishNode(u,`AssignmentExpression`)}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),a>-1&&(t.trailingComma=a),l},X.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if((i.type!==`ArrowFunctionExpression`||i.start!==n)&&this.eat(J.question)){var a=this.startNodeAt(n,r);return a.test=i,a.consequent=this.parseMaybeAssign(),this.expect(J.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,`ConditionalExpression`)}return i},X.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===n&&i.type===`ArrowFunctionExpression`?i:this.parseExprOp(i,n,r,-1,e)},X.parseExprOp=function(e,t,n,r,i){var a=this.type.binop;if(a!=null&&(!i||this.type!==J._in)&&a>r){var o=this.type===J.logicalOR||this.type===J.logicalAND,s=this.type===J.coalesce;s&&(a=J.logicalAND.binop);var c=this.value;this.next();var l=this.start,u=this.startLoc,d=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),l,u,a,i),f=this.buildBinary(t,n,e,d,c,o||s);return(o&&this.type===J.coalesce||s&&(this.type===J.logicalOR||this.type===J.logicalAND))&&this.raiseRecoverable(this.start,`Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses`),this.parseExprOp(f,t,n,r,i)}return e},X.buildBinary=function(e,t,n,r,i,a){r.type===`PrivateIdentifier`&&this.raise(r.start,`Private identifier can only be left side of binary expression`);var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,a?`LogicalExpression`:`BinaryExpression`)},X.parseMaybeUnary=function(e,t,n,r){var i=this.start,a=this.startLoc,o;if(this.isContextual(`await`)&&this.canAwait)o=this.parseAwait(r),t=!0;else if(this.type.prefix){var s=this.startNode(),c=this.type===J.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0,c,r),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(s.argument):this.strict&&s.operator===`delete`&&iw(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&aw(s.argument)?this.raiseRecoverable(s.start,`Private fields can not be deleted`):t=!0,o=this.finishNode(s,c?`UpdateExpression`:`UnaryExpression`)}else if(!t&&this.type===J.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==J._in&&this.unexpected();else{if(o=this.parseExprSubscripts(e,r),this.checkExpressionErrors(e))return o;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(i,a);l.operator=this.value,l.prefix=!1,l.argument=o,this.checkLValSimple(o),this.next(),o=this.finishNode(l,`UpdateExpression`)}}if(!n&&(o.type!==`ArrowFunctionExpression`||o.start!==i)&&this.eat(J.starstar)){if(t)this.unexpected(this.lastTokStart);else return this.buildBinary(i,a,o,this.parseMaybeUnary(null,!1,!1,r),`**`,!1)}else return o};function iw(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&&iw(e.expression)}function aw(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&aw(e.expression)||e.type===`ParenthesizedExpression`&&aw(e.expression)}X.parseExprSubscripts=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprAtom(e,t);if(i.type===`ArrowFunctionExpression`&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==`)`)return i;var a=this.parseSubscripts(i,n,r,!1,t);return e&&a.type===`MemberExpression`&&(e.parenthesizedAssign>=a.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=a.start&&(e.parenthesizedBind=-1),e.trailingComma>=a.start&&(e.trailingComma=-1)),a},X.parseSubscripts=function(e,t,n,r,i){for(var a=this.options.ecmaVersion>=8&&e.type===`Identifier`&&e.name===`async`&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.potentialArrowAt===e.start,o=!1;;){var s=this.parseSubscript(e,t,n,r,a,o,i);if(s.optional&&(o=!0),s===e||s.type===`ArrowFunctionExpression`){if(o){var c=this.startNodeAt(t,n);c.expression=s,s=this.finishNode(c,`ChainExpression`)}return s}e=s}},X.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(J.arrow)},X.parseSubscriptAsyncArrow=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!0,r)},X.parseSubscript=function(e,t,n,r,i,a,o){var s=this.options.ecmaVersion>=11,c=s&&this.eat(J.questionDot);r&&c&&this.raise(this.lastTokStart,`Optional chaining cannot appear in the callee of new expressions`);var l=this.eat(J.bracketL);if(l||c&&this.type!==J.parenL&&this.type!==J.backQuote||this.eat(J.dot)){var u=this.startNodeAt(t,n);u.object=e,l?(u.property=this.parseExpression(),this.expect(J.bracketR)):u.property=this.type===J.privateId&&e.type!==`Super`?this.parsePrivateIdent():this.parseIdent(this.options.allowReserved!==`never`),u.computed=!!l,s&&(u.optional=c),e=this.finishNode(u,`MemberExpression`)}else if(!r&&this.eat(J.parenL)){var d=new GC,f=this.yieldPos,p=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var ee=this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1,d);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,`Cannot use 'await' as identifier inside an async function`),this.yieldPos=f,this.awaitPos=p,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,n,ee,o);this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var te=this.startNodeAt(t,n);te.callee=e,te.arguments=ee,s&&(te.optional=c),e=this.finishNode(te,`CallExpression`)}else if(this.type===J.backQuote){(c||a)&&this.raise(this.start,`Optional chaining cannot appear in the tag of tagged template expressions`);var ne=this.startNodeAt(t,n);ne.tag=e,ne.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(ne,`TaggedTemplateExpression`)}return e},X.parseExprAtom=function(e,t,n){this.type===J.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case J._super:return this.allowSuper||this.raise(this.start,`'super' keyword outside a method`),r=this.startNode(),this.next(),this.type===J.parenL&&!this.allowDirectSuper&&this.raise(r.start,`super() call outside constructor of a subclass`),this.type!==J.dot&&this.type!==J.bracketL&&this.type!==J.parenL&&this.unexpected(),this.finishNode(r,`Super`);case J._this:return r=this.startNode(),this.next(),this.finishNode(r,`ThisExpression`);case J.name:var a=this.start,o=this.startLoc,s=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!s&&c.name===`async`&&!this.canInsertSemicolon()&&this.eat(J._function))return this.overrideContext(nw.f_expr),this.parseFunction(this.startNodeAt(a,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(J.arrow))return this.parseArrowExpression(this.startNodeAt(a,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name===`async`&&this.type===J.name&&!s&&(!this.potentialArrowInForAwait||this.value!==`of`||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(J.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,o),[c],!0,t)}return c;case J.regexp:var l=this.value;return r=this.parseLiteral(l.value),r.regex={pattern:l.pattern,flags:l.flags},r;case J.num:case J.string:return this.parseLiteral(this.value);case J._null:case J._true:case J._false:return r=this.startNode(),r.value=this.type===J._null?null:this.type===J._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,`Literal`);case J.parenL:var u=this.start,d=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)&&(e.parenthesizedAssign=u),e.parenthesizedBind<0&&(e.parenthesizedBind=u)),d;case J.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(J.bracketR,!0,!0,e),this.finishNode(r,`ArrayExpression`);case J.braceL:return this.overrideContext(nw.b_expr),this.parseObj(!1,e);case J._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case J._class:return this.parseClass(this.startNode(),!1);case J._new:return this.parseNew();case J.backQuote:return this.parseTemplate();case J._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}},X.parseExprAtomDefault=function(){this.unexpected()},X.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword import`),this.next(),this.type===J.parenL&&!e)return this.parseDynamicImport(t);if(this.type===J.dot){var n=this.startNodeAt(t.start,t.loc&&t.loc.start);return n.name=`import`,t.meta=this.finishNode(n,`Identifier`),this.parseImportMeta(t)}this.unexpected()},X.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(J.parenR)?e.options=null:(this.expect(J.comma),this.afterTrailingComma(J.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(J.parenR)||(this.expect(J.comma),this.afterTrailingComma(J.parenR)||this.unexpected())));else if(!this.eat(J.parenR)){var t=this.start;this.eat(J.comma)&&this.eat(J.parenR)?this.raiseRecoverable(t,`Trailing comma is not allowed in import()`):this.unexpected(t)}return this.finishNode(e,`ImportExpression`)},X.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`meta`&&this.raiseRecoverable(e.property.start,`The only valid meta property for import is 'import.meta'`),t&&this.raiseRecoverable(e.start,`'import.meta' must not contain escaped characters`),this.options.sourceType!==`module`&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,`Cannot use 'import.meta' outside a module`),this.finishNode(e,`MetaProperty`)},X.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value==null?t.raw.slice(0,-1).replace(/_/g,``):t.value.toString()),this.next(),this.finishNode(t,`Literal`)},X.parseParenExpression=function(){this.expect(J.parenL);var e=this.parseExpression();return this.expect(J.parenR),e},X.shouldParseArrow=function(e){return!this.canInsertSemicolon()},X.parseParenAndDistinguishExpression=function(e,t){var n=this.start,r=this.startLoc,i,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc,c=[],l=!0,u=!1,d=new GC,f=this.yieldPos,p=this.awaitPos,m;for(this.yieldPos=0,this.awaitPos=0;this.type!==J.parenR;){if(l?l=!1:this.expect(J.comma),a&&this.afterTrailingComma(J.parenR,!0)){u=!0;break}if(this.type===J.ellipsis){m=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`);break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var ee=this.lastTokEnd,te=this.lastTokEndLoc;if(this.expect(J.parenR),e&&this.shouldParseArrow(c)&&this.eat(J.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=p,this.parseParenArrowList(n,r,c,t);(!c.length||u)&&this.unexpected(this.lastTokStart),m&&this.unexpected(m),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,c.length>1?(i=this.startNodeAt(o,s),i.expressions=c,this.finishNodeAt(i,`SequenceExpression`,ee,te)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var ne=this.startNodeAt(n,r);return ne.expression=i,this.finishNode(ne,`ParenthesizedExpression`)}return i},X.parseParenItem=function(e){return e},X.parseParenArrowList=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!1,r)};var ow=[];X.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword new`);var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===J.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name=`new`,e.meta=this.finishNode(t,`Identifier`),this.next();var n=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`target`&&this.raiseRecoverable(e.property.start,`The only valid meta property for new is 'new.target'`),n&&this.raiseRecoverable(e.start,`'new.target' must not contain escaped characters`),this.allowNewDotTarget||this.raiseRecoverable(e.start,`'new.target' can only be used in functions and class static block`),this.finishNode(e,`MetaProperty`)}var r=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,i,!0,!1),e.callee.type===`Super`&&this.raiseRecoverable(r,`Invalid use of 'super'`),e.arguments=this.eat(J.parenL)?this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1):ow,this.finishNode(e,`NewExpression`)},X.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===J.invalidTemplate?(t||this.raiseRecoverable(this.start,`Bad escape sequence in untagged template literal`),n.value={raw:this.value.replace(/\r\n?/g,`
|
|
8
|
+
`);return e.length===0?t:`${t}\nexport declare const env: ${e.map(e=>e.environment).join(` & `)};`}var yx=new WeakMap;function bx(e){let t=yx.get(e);if(t!==void 0)return t;let n=hx(e.path.replace(/\./g,`$`)),r=mx(e.input,`input`),i=e.output?mx(e.output,`output`):`unknown`,a=Object.freeze({indexEnvironment:gx(e.path,r,i),environment:gx(e.path,`${n}_Input`,`${n}_Output`),types:`export type ${n}_Input = ${r};\nexport type ${n}_Output = ${i};`});return yx.set(e,a),a}function xx(e){let t=cx(ox(e,`input`));if(t===!0||t===!1||!t.properties)return;let n={},r=!1,i=Object.entries(t.properties).sort(([e],[t])=>Ab(e,t));for(let[e,t]of i){let i=cx(t);if(i===!0||i===!1)continue;let a=i.examples;if(a&&a.length>0){let t=Ob.safeParse(a[0]);t.success&&(n[e]=t.data,r=!0)}else if(i.default!==void 0){let t=Ob.safeParse(i.default);t.success&&(n[e]=t.data,r=!0)}}return r?n:void 0}function Sx(e){return e&&e.length>0?e:void 0}function Cx(e){let t=Zb.safeParse(e);if(!t.success)throw new nx(`invalid_input`,`Description output exceeded its bounds`);return t.data}function wx(e,t){let n=e.find(e=>e.path===t.path);if(n){let e=`env.${n.path}`,t=Ob.safeParse(ox(n.input,`input`));if(!t.success)throw new nx(`invalid_input`,`Schema cannot be projected to JSON Schema`);let r={path:n.path,description:Sx(n.description),types:vx([bx(n)]),kind:`operation`,inputSchema:t.data,usage:`await ${e}({ ... })`};if(r.types.length>2e4)throw new nx(`invalid_input`,`Operation description exceeds the bounded output`);return Cx(r)}let r=`${t.path}.`,i=e.filter(e=>e.path.startsWith(r)).sort((e,t)=>Ab(e.path,t.path));if(i.length===0)throw new nx(`unknown_target`,`Unknown target: ${t.path}`);let a=i[0];if(!a)throw new nx(`unknown_target`,`Unknown target: ${t.path}`);let o=t.methods?.length?i.filter(e=>t.methods?.includes(e.path.slice(r.length))):i,s;if(s=t.detail===`index`||t.methods?.length&&o.length===0?_x(i.map(bx)):vx((o.length>0?o:i).map(bx)),s.length>2e4)throw new nx(`invalid_input`,`Description types exceed the bounded output`);return Cx({path:t.path,description:Sx(a.instructions),types:s,kind:`module`})}function Tx(e){let t=sx(e.input,`input`),n=e.output?sx(e.output,`output`):``;return Object.freeze({...e,fingerprint:Ib(t+`
|
|
9
|
+
`+n),inputBytes:t.length,outputBytes:n.length,sample:xx(e.input)})}var Ex={exact:14,startsWith:9,phrase:6,token:4,prefix:2,substring:2,includes:1},Dx={path:12,namespace:8,method:10,description:5},Ox=25,kx=10,Ax=8,jx=20,Mx=Math.max(Ox,kx)+Ax+jx,Nx=1+Math.max(...Object.values(Ex))*Math.max(...Object.values(Dx))+Mx;function Px(e){return Ib([...e].sort((e,t)=>Ab(e.path,t.path)).map(e=>JSON.stringify([e.path,e.description??null,e.capabilityNotes??null,e.instructions??null,e.fingerprint])).join(`
|
|
10
|
+
`))}function Fx(e,t){if(e===t)return`exact`;if(e.startsWith(t))return`startsWith`;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`\\b${n}\\b`).test(e))return`phrase`;let r=Mb(e);return r.some(e=>e===t)?`token`:r.some(e=>e.startsWith(t))?`prefix`:r.some(e=>e.includes(t))?`substring`:e.includes(t)?`includes`:`none`}function Ix(e,t,n){let r=jb(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...Fb(e)],s=`none`;for(let e of n){let t=Fx(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=Ex[s]*Dx[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function Lx(e,t){let n=jb(e);return[t,...Fb(t)].some(e=>n.includes(e))}function Rx(e){let t=[];for(let[n,r]of e){if(r.level===`none`)continue;let e=r.matchedTokens.slice(0,4).map(e=>e.slice(0,20));t.push(`${n}:${r.level}(${e.join(` `)})`)}return t.length>0?t.join(`; `):void 0}function zx(e){let t=Yb.safeParse(e);if(!t.success)throw new nx(`invalid_input`,`Search output exceeded its bounds`);return t.data}function Bx(e){return[Lb(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Vx(e){return zx({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Hx(e,t,n){let r=Rb(e.path),i=Lb(e.path),a=e.description??``,o=[e.path,r,i,a],s=Ix(e.path,`path`,t),c=Ix(r,`namespace`,t),l=Ix(i,`method`,t),u=Ix(a,`description`,t),d=n.filter(e=>o.some(t=>Lx(t,e))).length;if(d===0)return;let f=d/n.length,p=Math.max(s.score,c.score,l.score,u.score);if(p===0)return;let m=d===n.length?Ox:f*kx,ee=n[0];ee&&o.some(e=>Lx(e,ee))&&(m+=Ax),(s.level===`exact`||l.level===`exact`)&&(m+=jx);let te={path:e.path,score:d+(p+m)/Nx};a&&(te.description=a);let ne=Rx([[`method`,l],[`description`,u],[`path`,s],[`namespace`,c]]);return ne&&(te.matchReason=ne),e.sample&&(te.sample=e.sample),e.capabilityNotes&&(te.capabilityNotes=e.capabilityNotes),{result:te,cluster:Bx(e),pathScore:s.score}}function Ux(e){let t=new Map;for(let n of e){let e=t.get(n.cluster)??[];e.push(n),t.set(n.cluster,e)}let n=[];for(let e of t.values()){let t=[...e].sort((e,t)=>t.pathScore-e.pathScore||t.result.score-e.result.score||Ab(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>Ab(e.result.path,t.result.path));for(let e of a){let t={path:e.result.path};e.result.capabilityNotes&&(t.capabilityNotes=e.result.capabilityNotes),i.push(t)}let o={...r.result,score:Math.max(...t.map(e=>e.result.score))};i.length>0&&(o.peers=i),n.push(o)}return n.sort((e,t)=>t.score-e.score||Ab(e.path,t.path))}function Wx(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return zx({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function Gx(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=Mb(jb(t)),o=a.filter(e=>!Pb(e));if(o.length===0)return Vx(r);let s=[];for(let t of e){let e=Hx(t,a,o);e&&s.push(e)}return Wx(Ux(s),i,r)}var Kx=ln({catalogStamp:Xb.shape.catalogStamp,namespace:Kb.shape.namespace.unwrap().nullable(),after:Jb.shape.path});function qx(e,t,n){let r=Kb.safeParse(n);if(!r.success)throw new nx(`invalid_input`,r.error.message);let i=r.data,a=i.namespace??null,o=e.filter(e=>a===null||e.path.startsWith(`${a}.`)).sort((e,t)=>Ab(Rb(e.path),Rb(t.path))||Ab(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=Kx.parse(JSON.parse(i.cursor))}catch(e){throw new nx(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new nx(`invalid_input`,`Listing cursor belongs to a different catalog or namespace`);let n=o.findIndex(t=>t.path===e.after);if(n<0)throw new nx(`invalid_input`,`Listing cursor operation is absent from this view`);s=n+1}let c=o.slice(s,s+i.limit),l=c.at(-1);return Xb.parse({results:c,total:o.length,catalogStamp:t,nextCursor:s+c.length<o.length&&l!==void 0?JSON.stringify({catalogStamp:t,namespace:a,after:l.path}):null})}var Jx=1e6;function Yx(t,n=0){if(n>=16)return t.length===0?n:n+1;let r=n;for(let i=t.length-1;i>=0;--i){let a=t[i],o=n+1;if(Array.isArray(a)?o=Yx(a,o):e(a)&&(o=Yx(Object.values(a),o)),r=Math.max(r,o),r>16)return r}return r}function Xx(e){let t=tx.safeParse(e);if(!t.success)throw new nx(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new nx(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>Ab(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new nx(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),sx(e.input,`input`).length>2e4||Yx(Object.values(ox(e.input,`input`)))>16)throw new nx(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?sx(e.output,`output`).length:0)>2e4||e.output!==void 0&&Yx(Object.values(ox(e.output,`output`)))>16)throw new nx(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=Tx(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||Hb(n,0)>16))throw new nx(`invalid_input`,`Schema projection is too large: ${e.path}`);if(i.push(t),a+=t.inputBytes+t.outputBytes+o+e.path.length,a+=e.description?.length??0,a+=e.capabilityNotes?.length??0,a+=e.instructions?.length??0,a>Jx)throw new nx(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function Zx(e){let t=Xx(e),n=Object.freeze(t.operations),r=Px(n),i=n.map(e=>{let t={path:e.path,score:0};return e.description!==void 0&&(t.description=e.description),e.sample!==void 0&&(t.sample=e.sample),e.capabilityNotes!==void 0&&(t.capabilityNotes=e.capabilityNotes),t});return Object.freeze({revision:t.revision,search:e=>{let t=Wb.safeParse(e);if(!t.success)throw new nx(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new nx(`empty_query`,`Search query must not be empty`);return Gx(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Gb.safeParse(e);if(!t.success)throw new nx(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new nx(`empty_query`,`Description target must not be empty`);return wx(n,t.data)},list:e=>qx(i,r,e),stamp:()=>r})}var Qx=_(()=>w().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),$x=_(()=>si(w(),bn()));_(()=>Qr([$x,pr()]));var eS=_(()=>Qt({tool:Qx,title:w().max(120),description:w().max(1e3),input:si(w(),bn()),output:si(w(),bn()),call:si(w(),bn())}).catchall(bn()));_(()=>hn(`kind`,[ln({kind:yr(`unindexed`)}),ln({kind:yr(`ready`),tools:Er(eS).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var tS=Object.freeze({replay:`safe`,path:`forage.search`,description:`Search operation names and descriptions with short keywords, such as read or shell. If no results match, retry with one relevant keyword. Describe known operation paths directly with forage.describe.`,input:Wb,output:Yb}),nS=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Gb,output:Zb}),rS=Object.freeze({replay:`safe`,path:`forage.list`,description:`List every available operation in stable namespace then path order (UTF-16 code units). Use limit (1–50) and nextCursor to page without duplicates, optionally filtering by exact namespace. total counts all operations in that filter; summaries match search, with score 0 and no peer merging. A cursor belongs to this catalog and filter; describe paths before calling them.`,input:Kb,output:Xb});Object.freeze({createCatalog:Zx,forageSearchDefinition:tS,forageDescribeDefinition:nS,forageListDefinition:rS});var iS=`invalid_definition`,aS=`runtime_closed`,oS=`source_failure`,G=class extends Error{code=iS;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},sS=class extends Error{code=aS;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},cS=class extends Error{sourceId;phase;code=oS;constructor(e,t){super(e===void 0?`Capability source ${t} failed`:`Capability source ${t} failed: ${e}`),this.sourceId=e,this.phase=t,this.name=`MyceliumSourceError`}},lS=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},uS=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},dS=class extends zi(`SourceInvalid`){},fS=class extends zi(`GuestThrew`){},pS=class extends zi(`DeadlineExceeded`){},mS=class extends zi(`SandboxBusy`){code=`sandbox-busy`},hS=class extends zi(`Cancelled`){},gS=class extends zi(`DispatchLost`){},_S=class extends zi(`SandboxCrashed`){},vS=class extends zi(`BadResponse`){},yS=class extends zi(`ResultTooLarge`){},bS=class extends zi(`ResultNotJson`){},xS=class extends zi(`CapabilityFailed`){constructor(e){super(e),this.message=wS(this)}},SS=class extends zi(`Unknown`){};function CS(e,t){switch(e._tag){case`SourceInvalid`:return new dS({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new fS({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new pS({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new mS({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new hS({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new gS({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new _S({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new vS({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new yS({size:e.size,ref:t});case`ResultNotJson`:return new bS({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new xS({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new SS({rawCause:e.rawCause,ref:t})}}function wS(e,t=!0){let n;switch(e._tag){case`SourceInvalid`:n=`SyntaxError in submitted source line ${String(e.line)}, column ${String(e.column)}: ${e.excerpt.slice(0,160)}. Nothing ran. Fix quote/heredoc nesting: quote multi-line shell text with a JavaScript template literal or \\n escapes; escape backticks and \${ inside it. If a nested heredoc is hard to quote, write the script with Files, then execute it.`;break;case`GuestThrew`:{let t=e.name.slice(0,80),r=e.message.slice(0,512),i=e.missingVariable;n=`${t}: ${r}${i===void 0?``:`. Declare ${i} with const or let before assigning it; this sandbox does not create implicit globals. Each execute call has its own variables.`}`;break}case`DeadlineExceeded`:n=`execute hit its ${String(e.limitMs)} ms deadline after ${String(e.elapsedMs)} ms; split the work or persist progress${e.acknowledged===!1?`; sandbox did not acknowledge cancellation`:``}`;break;case`SandboxBusy`:n=`sandbox-busy: all ${String(e.capacity)} sandbox slots remained occupied after waiting ${String(e.waitedMs)} ms. Nothing ran; retry this call after capacity becomes available.`;break;case`Cancelled`:n=e.acknowledged===!1?`Sandbox did not acknowledge cancellation`:`Execution was cancelled`;break;case`DispatchLost`:n=`The sandbox lost contact after ${String(e.elapsedMs)} ms; a running command may still be running; check its effects before retrying`;break;case`SandboxCrashed`:n=`The sandbox process stopped before answering; check effects before retrying`;break;case`BadResponse`:n=`The sandbox returned an unreadable result; retry once, split the call if it recurs`;break;case`ResultTooLarge`:n=`Sandbox result exceeds 256 KiB`;break;case`ResultNotJson`:n=`Sandbox returned non-JSON data`;break;case`CapabilityFailed`:n=e.cause.message.slice(0,1e3);break;case`Unknown`:return`The sandbox failed for an unrecognized reason${t?` (ref ${e.ref??`unavailable`})`:``}`}return!t||e.ref===void 0?n:`${n} (ref ${e.ref})`}var TS=_(()=>Qr([t(dS),t(fS),t(pS),t(mS),t(hS),t(gS),t(_S),t(vS),t(yS),t(bS),t(xS),t(SS)])),ES=_(()=>xt().pipe(Qr([t(Error).transform(e=>({kind:`error`,value:e})),wn().transform(e=>({kind:`null`,value:e})),Ir().transform(e=>({kind:`undefined`,value:e})),w().transform(e=>({kind:`string`,value:e})),pr().transform(e=>({kind:`boolean`,value:e})),Qr([Mn(),Rn(),yr(1/0),yr(-1/0)]).transform(e=>({kind:`number`,value:e})),nn().transform(e=>({kind:`bigint`,value:e})),ht().transform(e=>({kind:`symbol`,value:e})),t(Function).transform(e=>({kind:`function`,value:e})),Er(xt()).transform(e=>({kind:`array`,value:e})),Qr([t(Object),si(w(),xt())]).transform(e=>({kind:`object`,value:e})),xt().transform(()=>({kind:`opaque`}))])));function DS(e){return TS.safeParse(e).success}function OS(e){let t=TS.safeParse(e);return t.success?t.data:new SS({rawCause:e})}function kS(e){let t=ES.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}_(()=>bn().optional());function AS(e){return jS(e,new Set)}function jS(e,t){let n=ES.parse(e);switch(n.kind){case`null`:case`undefined`:return null;case`string`:case`boolean`:return n.value;case`number`:return Number.isFinite(n.value)?n.value:String(n.value);case`bigint`:case`symbol`:return String(n.value);case`function`:return{kind:`function`,name:n.value.name};case`opaque`:return{kind:`opaque`};case`error`:case`array`:case`object`:{let r=n.value;if(t.has(e))return{kind:`circular_reference`};t.add(e);try{if(n.kind===`array`)return n.value.map(e=>jS(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,jS(n,t)]));if(n.kind===`error`){let r=n.value;e.name=r.name,e.message=r.message,r.stack!==void 0&&(e.stack=r.stack),r.cause!==void 0&&(e.cause=jS(r.cause,t)),r instanceof AggregateError&&(e.errors=jS(r.errors,t))}return e}finally{t.delete(e)}}}}var MS=_(()=>Qt({name:yr(`ReferenceError`),message:w().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));_(()=>Qr([MS,Qt({name:w(),message:w()})]).and(Qt({transportMessage:w().max(512).optional()})));var NS=_(()=>ln({v:yr(1),kind:yr(`sandbox_failure`),tag:Jt([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:w().min(1).max(32),message:w().max(160)})),PS=D(U(am)),FS=_(()=>w().transform((e,t)=>{let n=PS(e);return Ae(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),ur):n.success})).pipe(NS);ln({error:FS}),_(()=>xt().pipe(Qr([yr(`Execution timed out`).transform(()=>({kind:`deadline`})),xt().transform(e=>({kind:`bad_response`,rawCause:e}))])));var IS=ln({sandboxCapacity:Vr().positive().optional(),admissionWaitMs:Vr().min(1).max(9e5).optional()});function LS(e,t){let n=IS.safeParse(e??{}),r=Vr().positive().safeParse(t??2);if(!n.success||!r.success)throw new G(`Sandbox admission policy is invalid`);return Object.freeze({capacity:n.data.sandboxCapacity??Math.min(32,Math.max(2,r.data)),waitMs:n.data.admissionWaitMs??18e4})}var RS=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],zS=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],BS=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,VS=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,HS={3:`abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile`,5:`class enum extends super const export import`,6:`enum`,strict:`implements interface let package private protected public static yield`,strictBind:`eval arguments`},US=`break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this`,WS={5:US,"5module":US+` export import`,6:US+` const class extends export import super`},GS=/^in(stanceof)?$/,KS=RegExp(`[`+VS+`]`),qS=RegExp(`[`+VS+BS+`]`);function JS(e,t){for(var n=65536,r=0;r<t.length;r+=2){if(n+=t[r],n>e)return!1;if(n+=t[r+1],n>=e)return!0}return!1}function YS(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&KS.test(String.fromCharCode(e)):t!==!1&&JS(e,zS)}function XS(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&qS.test(String.fromCharCode(e)):t===!1?!1:JS(e,zS)||JS(e,RS)}var K=function(e,t){t===void 0&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function ZS(e,t){return new K(e,{beforeExpr:!0,binop:t})}var QS={beforeExpr:!0},$S={startsExpr:!0},eC={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,eC[e]=new K(e,t)}var J={num:new K(`num`,$S),regexp:new K(`regexp`,$S),string:new K(`string`,$S),name:new K(`name`,$S),privateId:new K(`privateId`,$S),eof:new K(`eof`),bracketL:new K(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new K(`]`),braceL:new K(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new K(`}`),parenL:new K(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new K(`)`),comma:new K(`,`,QS),semi:new K(`;`,QS),colon:new K(`:`,QS),dot:new K(`.`),question:new K(`?`,QS),questionDot:new K(`?.`),arrow:new K(`=>`,QS),template:new K(`template`),invalidTemplate:new K(`invalidTemplate`),ellipsis:new K(`...`,QS),backQuote:new K("`",$S),dollarBraceL:new K("${",{beforeExpr:!0,startsExpr:!0}),eq:new K(`=`,{beforeExpr:!0,isAssign:!0}),assign:new K(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new K(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new K(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:ZS(`||`,1),logicalAND:ZS(`&&`,2),bitwiseOR:ZS(`|`,3),bitwiseXOR:ZS(`^`,4),bitwiseAND:ZS(`&`,5),equality:ZS(`==/!=/===/!==`,6),relational:ZS(`</>/<=/>=`,7),bitShift:ZS(`<</>>/>>>`,8),plusMin:new K(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:ZS(`%`,10),star:ZS(`*`,10),slash:ZS(`/`,10),starstar:new K(`**`,{beforeExpr:!0}),coalesce:ZS(`??`,1),_break:q(`break`),_case:q(`case`,QS),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,QS),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,QS),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,$S),_if:q(`if`),_return:q(`return`,QS),_switch:q(`switch`),_throw:q(`throw`,QS),_try:q(`try`),_var:q(`var`),_const:q(`const`),_while:q(`while`,{isLoop:!0}),_with:q(`with`),_new:q(`new`,{beforeExpr:!0,startsExpr:!0}),_this:q(`this`,$S),_super:q(`super`,$S),_class:q(`class`,$S),_extends:q(`extends`,QS),_export:q(`export`),_import:q(`import`,$S),_null:q(`null`,$S),_true:q(`true`,$S),_false:q(`false`,$S),_in:q(`in`,{beforeExpr:!0,binop:7}),_instanceof:q(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:q(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:q(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:q(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},tC=/\r\n?|\n|\u2028|\u2029/,nC=new RegExp(tC.source,`g`);function rC(e){return e===10||e===13||e===8232||e===8233}function iC(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(rC(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var aC=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,oC=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,sC=Object.prototype,cC=sC.hasOwnProperty,lC=sC.toString,uC=Object.hasOwn||(function(e,t){return cC.call(e,t)}),dC=Array.isArray||(function(e){return lC.call(e)===`[object Array]`}),fC=Object.create(null);function pC(e){return fC[e]||(fC[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function mC(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var hC=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,gC=function(e,t){this.line=e,this.column=t};gC.prototype.offset=function(e){return new gC(this.line,this.column+e)};var _C=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function vC(e,t){for(var n=1,r=0;;){var i=iC(e,r,t);if(i<0)return new gC(n,t-r);++n,r=i}}var yC={ecmaVersion:null,sourceType:`script`,strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,startLocation:null,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},bC=!1;function xC(e){var t={};for(var n in yC)t[n]=e&&uC(e,n)?e[n]:yC[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!bC&&typeof console==`object`&&console.warn&&(bC=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
11
|
+
Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),t.allowReserved??=t.ecmaVersion<5,(!e||e.allowHashBang==null)&&(t.allowHashBang=t.ecmaVersion>=14),dC(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}if(dC(t.onComment)&&(t.onComment=SC(t,t.onComment)),t.sourceType===`commonjs`&&t.allowAwaitOutsideFunction)throw Error(`Cannot use allowAwaitOutsideFunction with sourceType: commonjs`);return t}function SC(e,t){return function(n,r,i,a,o,s){var c={type:n?`Block`:`Line`,value:r,start:i,end:a};e.locations&&(c.loc=new _C(this,o,s)),e.ranges&&(c.range=[i,a]),t.push(c)}}var CC=1,wC=2,TC=4,EC=8,DC=16,OC=32,kC=64,AC=128,jC=256,MC=512,NC=1024,PC=CC|wC|jC;function FC(e,t){return wC|(e?TC:0)|(t?EC:0)}var IC=0,LC=1,RC=2,zC=3,BC=4,VC=5,HC=function(e,t,n){this.options=e=xC(e),this.sourceFile=e.sourceFile,this.keywords=pC(WS[e.ecmaVersion>=6?6:e.sourceType===`module`?`5module`:5]);var r=``;e.allowReserved!==!0&&(r=HS[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType===`module`&&(r+=` await`)),this.reservedWords=pC(r);var i=(r?r+` `:``)+HS.strict;this.reservedWordsStrict=pC(i),this.reservedWordsStrictBind=pC(i+` `+HS.strictBind),this.input=String(t),this.containsEsc=!1,this.pos=n||0,this.curLine=1,e.startLocation?(this.lineStart=this.pos-e.startLocation.column,this.curLine=e.startLocation.line):n?(this.lineStart=this.input.lastIndexOf(`
|
|
12
|
+
`,n-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(tC).length)):this.lineStart=0,this.type=J.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType===`module`,this.strict=this.inModule||e.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)===`#!`&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType===`commonjs`?wC:CC),this.regexpState=null,this.privateNameStack=[]},UC={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};HC.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},UC.inFunction.get=function(){return(this.currentVarScope().flags&wC)>0},UC.inGenerator.get=function(){return(this.currentVarScope().flags&EC)>0},UC.inAsync.get=function(){return(this.currentVarScope().flags&TC)>0},UC.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(jC|MC))return!1;if(t&wC)return(t&TC)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},UC.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&CC)},UC.allowSuper.get=function(){return(this.currentThisScope().flags&kC)>0||this.options.allowSuperOutsideMethod},UC.allowDirectSuper.get=function(){return(this.currentThisScope().flags&AC)>0},UC.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},UC.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(jC|MC)||t&wC&&!(t&DC))return!0}return!1},UC.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&NC||!this.inModule&&e&CC)},UC.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&jC)>0},HC.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var n=this,r=0;r<e.length;r++)n=e[r](n);return n},HC.parse=function(e,t){return new this(t,e).parse()},HC.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},HC.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(HC.prototype,UC);var WC=HC.prototype,GC=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;WC.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){oC.lastIndex=e,e+=oC.exec(this.input)[0].length;var t=GC.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){oC.lastIndex=e+t[0].length;var n=oC.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||tC.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,oC.lastIndex=e,e+=oC.exec(this.input)[0].length,this.input[e]===`;`&&e++}},WC.eat=function(e){return this.type===e&&(this.next(),!0)},WC.isContextual=function(e){return this.type===J.name&&this.value===e&&!this.containsEsc},WC.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},WC.catchStackOverflow=function(e){try{return e()}catch(e){if(e instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message)||/\btoo much recursion\b/i.test(e.message)))this.raise(this.start,`Not enough stack space to parse input`);else throw e}},WC.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},WC.canInsertSemicolon=function(){return this.type===J.eof||this.type===J.braceR||tC.test(this.input.slice(this.lastTokEnd,this.start))},WC.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},WC.semicolon=function(){!this.eat(J.semi)&&!this.insertSemicolon()&&this.unexpected()},WC.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},WC.expect=function(e){this.eat(e)||this.unexpected()},WC.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var KC=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};WC.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,`Comma is not permitted after the rest element`);var n=t?e.parenthesizedAssign:e.parenthesizedBind;n>-1&&this.raiseRecoverable(n,t?`Assigning to rvalue`:`Parenthesized pattern`)}},WC.checkExpressionErrors=function(e,t){if(!e)return!1;var n=e.shorthandAssign,r=e.doubleProto;if(!t)return n>=0||r>=0;n>=0&&this.raise(n,`Shorthand property assignments are valid only in destructuring patterns`),r>=0&&this.raiseRecoverable(r,`Redefinition of __proto__ property`)},WC.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,`Yield expression cannot be a default value`),this.awaitPos&&this.raise(this.awaitPos,`Await expression cannot be a default value`)},WC.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var Y=HC.prototype;Y.parseTopLevel=function(e){var t=Object.create(null);for(e.body||=[];this.type!==J.eof;){var n=this.parseStatement(null,!0,t);e.body.push(n)}if(this.inModule)for(var r=0,i=Object.keys(this.undefinedExports);r<i.length;r+=1){var a=i[r];this.raiseRecoverable(this.undefinedExports[a].start,`Export '`+a+`' is not defined`)}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType===`commonjs`?`script`:this.options.sourceType,this.finishNode(e,`Program`)};var qC={kind:`loop`},JC={kind:`switch`};Y.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;oC.lastIndex=this.pos;var t=oC.exec(this.input),n=this.pos+t[0].length,r=this.fullCharCodeAt(n);if(r===91||r===92)return!0;if(e)return!1;if(r===123)return!0;if(YS(r)){var i=n;do n+=r<=65535?1:2;while(XS(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!GS.test(a))return!0}return!1},Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;oC.lastIndex=this.pos;var e=oC.exec(this.input),t=this.pos+e[0].length,n;return!tC.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(XS(n=this.fullCharCodeAt(t+8))||n===92))},Y.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;oC.lastIndex=this.pos;var n=oC.exec(this.input),r=this.pos+n[0].length;if(tC.test(this.input.slice(this.pos,r)))return!1;if(e){var i=r+5,a;if(this.input.slice(r,i)!==`using`||i===this.input.length||XS(a=this.fullCharCodeAt(i))||a===92)return!1;oC.lastIndex=i;var o=oC.exec(this.input);if(r=i+o[0].length,o&&tC.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!YS(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(XS(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(GS.test(l))return!1;if(t&&!e&&l===`of`){oC.lastIndex=r;var u=oC.exec(this.input);if(r+=u[0].length,this.input.charCodeAt(r)!==61||(s=this.input.charCodeAt(r+1))===61||s===62)return!1}return!0},Y.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},Y.isUsing=function(e){return this.isUsingKeyword(!1,e)},Y.parseStatement=function(e,t,n){var r=this.type,i=this.startNode(),a;switch(this.isLet(e)&&(r=J._var,a=`let`),r){case J._break:case J._continue:return this.parseBreakContinueStatement(i,r.keyword);case J._debugger:return this.parseDebuggerStatement(i);case J._do:return this.parseDoStatement(i);case J._for:return this.parseForStatement(i);case J._function:return e&&(this.strict||e!==`if`&&e!==`label`)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case J._class:return e&&this.unexpected(),this.parseClass(i,!0);case J._if:return this.parseIfStatement(i);case J._return:return this.parseReturnStatement(i);case J._switch:return this.parseSwitchStatement(i);case J._throw:return this.parseThrowStatement(i);case J._try:return this.parseTryStatement(i);case J._const:case J._var:return a||=this.value,e&&a!==`var`&&this.unexpected(),this.parseVarStatement(i,a);case J._while:return this.parseWhileStatement(i);case J._with:return this.parseWithStatement(i);case J.braceL:return this.parseBlock(!0,i);case J.semi:return this.parseEmptyStatement(i);case J._export:case J._import:if(this.options.ecmaVersion>10&&r===J._import){oC.lastIndex=this.pos;var o=oC.exec(this.input),s=this.pos+o[0].length,c=this.input.charCodeAt(s);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,`'import' and 'export' may only appear at the top level`),this.inModule||this.raise(this.start,`'import' and 'export' may appear only with 'sourceType: module'`)),r===J._import?this.parseImport(i):this.parseExport(i,n);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.isAwaitUsing(!1)?`await using`:this.isUsing(!1)?`using`:null;if(l)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,`Using declaration is not allowed in single-statement positions`),l===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.next(),this.parseVar(i,!1,l),this.semicolon(),this.finishNode(i,`VariableDeclaration`);var u=this.value,d=this.parseExpression();return r===J.name&&d.type===`Identifier`&&this.eat(J.colon)?this.parseLabeledStatement(i,u,d,e):this.parseExpressionStatement(i,d)}},Y.parseBreakContinueStatement=function(e,t){var n=t===`break`;this.next(),this.eat(J.semi)||this.insertSemicolon()?e.label=null:this.type===J.name?(e.label=this.parseIdent(),this.semicolon()):this.unexpected();for(var r=0;r<this.labels.length;++r){var i=this.labels[r];if((e.label==null||i.name===e.label.name)&&(i.kind!=null&&(n||i.kind===`loop`)||e.label&&n))break}return r===this.labels.length&&this.raise(e.start,`Unsyntactic `+t),this.finishNode(e,n?`BreakStatement`:`ContinueStatement`)},Y.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,`DebuggerStatement`)},Y.parseDoStatement=function(e){return this.next(),this.labels.push(qC),e.body=this.parseStatement(`do`),this.labels.pop(),this.expect(J._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(J.semi):this.semicolon(),this.finishNode(e,`DoWhileStatement`)},Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual(`await`)?this.lastTokStart:-1;if(this.labels.push(qC),this.enterScope(0),this.expect(J.parenL),this.type===J.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var n=this.isLet();if(this.type===J._var||this.type===J._const||n){var r=this.startNode(),i=n?`let`:this.value;return this.next(),this.parseVar(r,!0,i),this.finishNode(r,`VariableDeclaration`),this.parseForAfterInit(e,r,t)}var a=this.isContextual(`let`),o=!1,s=this.isUsing(!0)?`using`:this.isAwaitUsing(!0)?`await using`:null;if(s){var c=this.startNode();return this.next(),s===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.parseVar(c,!0,s),this.finishNode(c,`VariableDeclaration`),this.parseForAfterInit(e,c,t)}var l=this.containsEsc,u=new KC,d=this.start,f=t>-1?this.parseExprSubscripts(u,`await`):this.parseExpression(!0,u);return this.type===J._in||(o=this.options.ecmaVersion>=6&&this.isContextual(`of`))?(t>-1?(this.type===J._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(f.start===d&&!l&&f.type===`Identifier`&&f.name===`async`?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),a&&o&&this.raise(f.start,`The left-hand side of a for-of loop may not start with 'let'.`),this.toAssignable(f,!1,u),this.checkLValPattern(f),this.parseForIn(e,f)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,f))},Y.parseForAfterInit=function(e,t,n){return(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))&&t.declarations.length===1?(this.type===J._in?((t.kind===`using`||t.kind===`await using`)&&!t.declarations[0].init&&this.raise(this.start,`Using declaration is not allowed in for-in loops`),this.options.ecmaVersion>=9&&n>-1&&this.unexpected(n)):this.options.ecmaVersion>=9&&(e.await=n>-1),this.parseForIn(e,t)):(n>-1&&this.unexpected(n),this.parseFor(e,t))},Y.parseFunctionStatement=function(e,t,n){return this.next(),this.parseFunction(e,XC|(n?0:ZC),!1,t)},Y.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(`if`),e.alternate=this.eat(J._else)?this.parseStatement(`if`):null,this.finishNode(e,`IfStatement`)},Y.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,`'return' outside of function`),this.next(),this.eat(J.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,`ReturnStatement`)},Y.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(J.braceL),this.labels.push(JC),this.enterScope(NC);for(var t,n=!1;this.type!==J.braceR;)if(this.type===J._case||this.type===J._default){var r=this.type===J._case;t&&this.finishNode(t,`SwitchCase`),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,`Multiple default clauses`),n=!0,t.test=null),this.expect(J.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,`SwitchCase`),this.next(),this.labels.pop(),this.finishNode(e,`SwitchStatement`)},Y.parseThrowStatement=function(e){return this.next(),tC.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,`Illegal newline after throw`),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,`ThrowStatement`)};var YC=[];Y.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?OC:0),this.checkLValPattern(e,t?BC:RC),this.expect(J.parenR),e},Y.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===J._catch){var t=this.startNode();this.next(),this.eat(J.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,`CatchClause`)}return e.finalizer=this.eat(J._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,`Missing catch or finally clause`),this.finishNode(e,`TryStatement`)},Y.parseVarStatement=function(e,t,n){return this.next(),this.parseVar(e,!1,t,n),this.semicolon(),this.finishNode(e,`VariableDeclaration`)},Y.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(qC),e.body=this.parseStatement(`while`),this.labels.pop(),this.finishNode(e,`WhileStatement`)},Y.parseWithStatement=function(e){return this.strict&&this.raise(this.start,`'with' in strict mode`),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(`with`),this.finishNode(e,`WithStatement`)},Y.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,`EmptyStatement`)},Y.parseLabeledStatement=function(e,t,n,r){for(var i=0,a=this.labels;i<a.length;i+=1)a[i].name===t&&this.raise(n.start,`Label '`+t+`' is already declared`);for(var o=this.type.isLoop?`loop`:this.type===J._switch?`switch`:null,s=this.labels.length-1;s>=0;s--){var c=this.labels[s];if(c.statementStart===e.start)c.statementStart=this.start,c.kind=o;else break}return this.labels.push({name:t,kind:o,statementStart:this.start}),e.body=this.parseStatement(r?r.indexOf(`label`)===-1?r+`label`:r:`label`),this.labels.pop(),e.label=n,this.finishNode(e,`LabeledStatement`)},Y.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,`ExpressionStatement`)},Y.parseBlock=function(e,t,n){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(J.braceL),e&&this.enterScope(0);this.type!==J.braceR;){var r=this.parseStatement(null);t.body.push(r)}return n&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,`BlockStatement`)},Y.parseFor=function(e,t){return e.init=t,this.expect(J.semi),e.test=this.type===J.semi?null:this.parseExpression(),this.expect(J.semi),e.update=this.type===J.parenR?null:this.parseExpression(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,`ForStatement`)},Y.parseForIn=function(e,t){var n=this.type===J._in;return this.next(),t.type===`VariableDeclaration`&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!==`var`||t.declarations[0].id.type!==`Identifier`)&&this.raise(t.start,(n?`for-in`:`for-of`)+` loop variable declaration may not have an initializer`),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssign(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,n?`ForInStatement`:`ForOfStatement`)},Y.parseVar=function(e,t,n,r){for(e.declarations=[],e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(J.eq)?i.init=this.parseMaybeAssign(t):!r&&n===`const`&&!(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))?this.unexpected():!r&&(n===`using`||n===`await using`)&&this.options.ecmaVersion>=17&&this.type!==J._in&&!this.isContextual(`of`)?this.raise(this.lastTokEnd,`Missing initializer in `+n+` declaration`):!r&&i.id.type!==`Identifier`&&!(t&&(this.type===J._in||this.isContextual(`of`)))?this.raise(this.lastTokEnd,`Complex binding patterns require an initialization value`):i.init=null,e.declarations.push(this.finishNode(i,`VariableDeclarator`)),!this.eat(J.comma))break}return e},Y.parseVarId=function(e,t){e.id=t===`using`||t===`await using`?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t===`var`?LC:RC,!1)};var XC=1,ZC=2,QC=4;Y.parseFunction=function(e,t,n,r,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===J.star&&t&ZC&&this.unexpected(),e.generator=this.eat(J.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&XC&&(e.id=t&QC&&this.type!==J.name?null:this.parseIdent(),e.id&&!(t&ZC)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?LC:RC:zC));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(FC(e.async,e.generator)),t&XC||(e.id=this.type===J.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n,!1,i),this.yieldPos=a,this.awaitPos=o,this.awaitIdentPos=s,this.finishNode(e,t&XC?`FunctionDeclaration`:`FunctionExpression`)},Y.parseFunctionParams=function(e){this.expect(J.parenL),e.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),i=this.startNode(),a=!1;for(i.body=[],this.expect(J.braceL);this.type!==J.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type===`MethodDefinition`&&o.kind===`constructor`?(a&&this.raiseRecoverable(o.start,`Duplicate constructor in the same class`),a=!0):o.key&&o.key.type===`PrivateIdentifier`&&$C(r,o)&&this.raiseRecoverable(o.key.start,`Identifier '#`+o.key.name+`' has already been declared`))}return this.strict=n,this.next(),e.body=this.finishNode(i,`ClassBody`),this.exitClassBody(),this.finishNode(e,t?`ClassDeclaration`:`ClassExpression`)},Y.parseClassElement=function(e){if(this.eat(J.semi))return null;var t=this.options.ecmaVersion,n=this.startNode(),r=``,i=!1,a=!1,o=`method`,s=!1;if(this.eatContextual(`static`)){if(t>=13&&this.eat(J.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===J.star?s=!0:r=`static`}if(n.static=s,!r&&t>=8&&this.eatContextual(`async`)&&((this.isClassElementNameStart()||this.type===J.star)&&!this.canInsertSemicolon()?a=!0:r=`async`),!r&&(t>=9||!a)&&this.eat(J.star)&&(i=!0),!r&&!a&&!i){var c=this.value;(this.eatContextual(`get`)||this.eatContextual(`set`))&&(this.isClassElementNameStart()?o=c:r=c)}if(r?(n.computed=!1,n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),n.key.name=r,this.finishNode(n.key,`Identifier`)):this.parseClassElementName(n),t<13||this.type===J.parenL||o!==`method`||i||a){var l=!n.static&&ew(n,`constructor`),u=l&&e;l&&o!==`method`&&this.raise(n.key.start,`Constructor can't have get/set modifier`),n.kind=l?`constructor`:o,this.parseClassMethod(n,i,a,u)}else this.parseClassField(n);return n},Y.isClassElementNameStart=function(){return this.type===J.name||this.type===J.privateId||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword},Y.parseClassElementName=function(e){this.type===J.privateId?(this.value===`constructor`&&this.raise(this.start,`Classes can't have an element named '#constructor'`),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},Y.parseClassMethod=function(e,t,n,r){var i=e.key;e.kind===`constructor`?(t&&this.raise(i.start,`Constructor can't be a generator`),n&&this.raise(i.start,`Constructor can't be an async method`)):e.static&&ew(e,`prototype`)&&this.raise(i.start,`Classes may not have a static property named prototype`);var a=e.value=this.parseMethod(t,n,r);return e.kind===`get`&&a.params.length!==0&&this.raiseRecoverable(a.start,`getter should have no params`),e.kind===`set`&&a.params.length!==1&&this.raiseRecoverable(a.start,`setter should have exactly one param`),e.kind===`set`&&a.params[0].type===`RestElement`&&this.raiseRecoverable(a.params[0].start,`Setter cannot use rest params`),this.finishNode(e,`MethodDefinition`)},Y.parseClassField=function(e){return ew(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&ew(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(J.eq)?(this.enterScope(MC|kC),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,`PropertyDefinition`)},Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(jC|kC);this.type!==J.braceR;){var n=this.parseStatement(null);e.body.push(n)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,`StaticBlock`)},Y.parseClassId=function(e,t){this.type===J.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,RC,!1)):(t===!0&&this.unexpected(),e.id=null)},Y.parseClassSuper=function(e){e.superClass=this.eat(J._extends)?this.parseExprSubscripts(null,!1):null},Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},Y.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,n=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,i=r===0?null:this.privateNameStack[r-1],a=0;a<n.length;++a){var o=n[a];uC(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function $C(e,t){var n=t.key.name,r=e[n],i=`true`;return t.type===`MethodDefinition`&&(t.kind===`get`||t.kind===`set`)&&(i=(t.static?`s`:`i`)+t.kind),r===`iget`&&i===`iset`||r===`iset`&&i===`iget`||r===`sget`&&i===`sset`||r===`sset`&&i===`sget`?(e[n]=`true`,!1):r?!0:(e[n]=i,!1)}function ew(e,t){var n=e.computed,r=e.key;return!n&&(r.type===`Identifier`&&r.name===t||r.type===`Literal`&&r.value===t)}Y.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual(`as`)?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual(`from`),this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ExportAllDeclaration`)},Y.parseExport=function(e,t){if(this.next(),this.eat(J.star))return this.parseExportAllDeclaration(e,t);if(this.eat(J._default))return this.checkExport(t,`default`,this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,`ExportDefaultDeclaration`);if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type===`VariableDeclaration`?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual(`from`))this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var n=0,r=e.specifiers;n<r.length;n+=1){var i=r[n];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type===`Literal`&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,`ExportNamedDeclaration`)},Y.parseExportDeclaration=function(e){return this.parseStatement(null)},Y.parseExportDefaultDeclaration=function(){var e;if(this.type===J._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,XC|QC,!1,e)}if(this.type===J._class){var n=this.startNode();return this.parseClass(n,`nullableID`)}var r=this.parseMaybeAssign();return this.semicolon(),r},Y.checkExport=function(e,t,n){e&&(typeof t!=`string`&&(t=t.type===`Identifier`?t.name:t.value),uC(e,t)&&this.raiseRecoverable(n,`Duplicate export '`+t+`'`),e[t]=!0)},Y.checkPatternExport=function(e,t){var n=t.type;if(n===`Identifier`)this.checkExport(e,t,t.start);else if(n===`ObjectPattern`)for(var r=0,i=t.properties;r<i.length;r+=1){var a=i[r];this.checkPatternExport(e,a)}else if(n===`ArrayPattern`)for(var o=0,s=t.elements;o<s.length;o+=1){var c=s[o];c&&this.checkPatternExport(e,c)}else n===`Property`?this.checkPatternExport(e,t.value):n===`AssignmentPattern`?this.checkPatternExport(e,t.left):n===`RestElement`&&this.checkPatternExport(e,t.argument)},Y.checkVariableExport=function(e,t){if(e)for(var n=0,r=t;n<r.length;n+=1){var i=r[n];this.checkPatternExport(e,i.id)}},Y.shouldParseExportStatement=function(){return this.type.keyword===`var`||this.type.keyword===`const`||this.type.keyword===`class`||this.type.keyword===`function`||this.isLet()||this.isAsyncFunction()},Y.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual(`as`)?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,`ExportSpecifier`)},Y.parseExportSpecifiers=function(e){var t=[],n=!0;for(this.expect(J.braceL);!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;t.push(this.parseExportSpecifier(e))}return t},Y.parseImport=function(e){return this.next(),this.type===J.string?(e.specifiers=YC,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual(`from`),e.source=this.type===J.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ImportDeclaration`)},Y.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual(`as`)?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,RC),this.finishNode(e,`ImportSpecifier`)},Y.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,RC),this.finishNode(e,`ImportDefaultSpecifier`)},Y.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual(`as`),e.local=this.parseIdent(),this.checkLValSimple(e.local,RC),this.finishNode(e,`ImportNamespaceSpecifier`)},Y.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===J.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(J.comma)))return e;if(this.type===J.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(J.braceL);!this.eat(J.braceR);){if(t)t=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;e.push(this.parseImportSpecifier())}return e},Y.parseWithClause=function(){var e=[];if(!this.eat(J._with))return e;this.expect(J.braceL);for(var t={},n=!0;!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;var r=this.parseImportAttribute(),i=r.key.type===`Identifier`?r.key.name:r.key.value;uC(t,i)&&this.raiseRecoverable(r.key.start,`Duplicate attribute key '`+i+`'`),t[i]=!0,e.push(r)}return e},Y.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`),this.expect(J.colon),this.type!==J.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,`ImportAttribute`)},Y.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===J.string){var e=this.parseLiteral(this.value);return hC.test(e.value)&&this.raise(e.start,`An export name cannot include a lone surrogate.`),e}return this.parseIdent(!0)},Y.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},Y.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&e.type===`ExpressionStatement`&&e.expression.type===`Literal`&&typeof e.expression.value==`string`&&(this.input[e.start]===`"`||this.input[e.start]===`'`)};var tw=HC.prototype;tw.toAssignable=function(e,t,n){if(this.options.ecmaVersion>=6&&e)switch(e.type){case`Identifier`:this.inAsync&&e.name===`await`&&this.raise(e.start,`Cannot use 'await' as identifier inside an async function`);break;case`ObjectPattern`:case`ArrayPattern`:case`AssignmentPattern`:case`RestElement`:break;case`ObjectExpression`:e.type=`ObjectPattern`,n&&this.checkPatternErrors(n,!0);for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.toAssignable(a,t),a.type===`RestElement`&&(a.argument.type===`ArrayPattern`||a.argument.type===`ObjectPattern`)&&this.raise(a.argument.start,`Unexpected token`)}break;case`Property`:e.kind!==`init`&&this.raise(e.key.start,`Object pattern can't contain getter or setter`),this.toAssignable(e.value,t);break;case`ArrayExpression`:e.type=`ArrayPattern`,n&&this.checkPatternErrors(n,!0),this.toAssignableList(e.elements,t);break;case`SpreadElement`:e.type=`RestElement`,this.toAssignable(e.argument,t),e.argument.type===`AssignmentPattern`&&this.raise(e.argument.start,`Rest elements cannot have a default value`);break;case`AssignmentExpression`:e.operator!==`=`&&this.raise(e.left.end,`Only '=' operator can be used for specifying default value.`),e.type=`AssignmentPattern`,delete e.operator,this.toAssignable(e.left,t);break;case`ParenthesizedExpression`:this.toAssignable(e.expression,t,n);break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:if(!t)break;default:this.raise(e.start,`Assigning to rvalue`)}else n&&this.checkPatternErrors(n,!0);return e},tw.toAssignableList=function(e,t){for(var n=e.length,r=0;r<n;r++){var i=e[r];i&&this.toAssignable(i,t)}if(n){var a=e[n-1];this.options.ecmaVersion===6&&t&&a&&a.type===`RestElement`&&a.argument.type!==`Identifier`&&this.unexpected(a.argument.start)}return e},tw.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},tw.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==J.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,`RestElement`)},tw.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case J.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(J.bracketR,!0,!0),this.finishNode(e,`ArrayPattern`);case J.braceL:return this.parseObj(!0)}return this.parseIdent()},tw.parseBindingList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);)if(a?a=!1:this.expect(J.comma),t&&this.type===J.comma)i.push(null);else if(n&&this.afterTrailingComma(e))break;else if(this.type===J.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.expect(e);break}else i.push(this.parseAssignableListItem(r));return i},tw.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},tw.parseBindingListItem=function(e){return e},tw.parseMaybeDefault=function(e,t,n){if(n||=this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(J.eq))return n;var r=this.startNodeAt(e,t);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,`AssignmentPattern`)},tw.checkLValSimple=function(e,t,n){t===void 0&&(t=IC);var r=t!==IC;switch(e.type){case`Identifier`:this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(r?`Binding `:`Assigning to `)+e.name+` in strict mode`),r&&(t===RC&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(uC(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==VC&&this.declareName(e.name,t,e.start));break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:r&&this.raiseRecoverable(e.start,`Binding member expression`);break;case`ParenthesizedExpression`:return r&&this.raiseRecoverable(e.start,`Binding parenthesized expression`),this.checkLValSimple(e.expression,t,n);default:this.raise(e.start,(r?`Binding`:`Assigning to`)+` rvalue`)}},tw.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=IC),e.type){case`ObjectPattern`:for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,t,n)}break;case`ArrayPattern`:for(var o=0,s=e.elements;o<s.length;o+=1){var c=s[o];c&&this.checkLValInnerPattern(c,t,n)}break;default:this.checkLValSimple(e,t,n)}},tw.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=IC),e.type){case`Property`:this.checkLValInnerPattern(e.value,t,n);break;case`AssignmentPattern`:this.checkLValPattern(e.left,t,n);break;case`RestElement`:this.checkLValPattern(e.argument,t,n);break;default:this.checkLValPattern(e,t,n)}};var nw=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},rw={b_stat:new nw(`{`,!1),b_expr:new nw(`{`,!0),b_tmpl:new nw("${",!1),p_stat:new nw(`(`,!1),p_expr:new nw(`(`,!0),q_tmpl:new nw("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new nw(`function`,!1),f_expr:new nw(`function`,!0),f_expr_gen:new nw(`function`,!0,!1,null,!0),f_gen:new nw(`function`,!1,!1,null,!0)},iw=HC.prototype;iw.initialContext=function(){return[rw.b_stat]},iw.curContext=function(){return this.context[this.context.length-1]},iw.braceIsBlock=function(e){var t=this.curContext();return t===rw.f_expr||t===rw.f_stat?!0:e===J.colon&&(t===rw.b_stat||t===rw.b_expr)?!t.isExpr:e===J._return||e===J.name&&this.exprAllowed?tC.test(this.input.slice(this.lastTokEnd,this.start)):e===J._else||e===J.semi||e===J.eof||e===J.parenR||e===J.arrow?!0:e===J.braceL?t===rw.b_stat:e===J._var||e===J._const||e===J.name?!1:!this.exprAllowed},iw.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token===`function`)return t.generator}return!1},iw.updateContext=function(e){var t,n=this.type;n.keyword&&e===J.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},iw.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},J.parenR.updateContext=J.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===rw.b_stat&&this.curContext().token===`function`&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},J.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?rw.b_stat:rw.b_expr),this.exprAllowed=!0},J.dollarBraceL.updateContext=function(){this.context.push(rw.b_tmpl),this.exprAllowed=!0},J.parenL.updateContext=function(e){var t=e===J._if||e===J._for||e===J._with||e===J._while;this.context.push(t?rw.p_stat:rw.p_expr),this.exprAllowed=!0},J.incDec.updateContext=function(){},J._function.updateContext=J._class.updateContext=function(e){e.beforeExpr&&e!==J._else&&(e!==J.semi||this.curContext()===rw.p_stat)&&!(e===J._return&&tC.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==J.colon&&e!==J.braceL||this.curContext()!==rw.b_stat)?this.context.push(rw.f_expr):this.context.push(rw.f_stat),this.exprAllowed=!1},J.colon.updateContext=function(){this.curContext().token===`function`&&this.context.pop(),this.exprAllowed=!0},J.backQuote.updateContext=function(){this.curContext()===rw.q_tmpl?this.context.pop():this.context.push(rw.q_tmpl),this.exprAllowed=!1},J.star.updateContext=function(e){if(e===J._function){var t=this.context.length-1;this.context[t]===rw.f_expr?this.context[t]=rw.f_expr_gen:this.context[t]=rw.f_gen}this.exprAllowed=!0},J.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==J.dot&&(this.value===`of`&&!this.exprAllowed||this.value===`yield`&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var X=HC.prototype;X.checkPropClash=function(e,t,n){if(!(this.options.ecmaVersion>=9&&e.type===`SpreadElement`)&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var r=e.key,i;switch(r.type){case`Identifier`:i=r.name;break;case`Literal`:i=String(r.value);break;default:return}var a=e.kind;if(this.options.ecmaVersion>=6){i===`__proto__`&&a===`init`&&(t.proto&&(n?n.doubleProto<0&&(n.doubleProto=r.start):this.raiseRecoverable(r.start,`Redefinition of __proto__ property`)),t.proto=!0);return}i=`$`+i;var o=t[i];o?(a===`init`?this.strict&&o.init||o.get||o.set:o.init||o[a])&&this.raiseRecoverable(r.start,`Redefinition of property`):o=t[i]={init:!1,get:!1,set:!1},o[a]=!0}},X.parseExpression=function(e,t){var n=this;return this.catchStackOverflow(function(){var r=n.start,i=n.startLoc,a=n.parseMaybeAssign(e,t);if(n.type===J.comma){var o=n.startNodeAt(r,i);for(o.expressions=[a];n.eat(J.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return n.finishNode(o,`SequenceExpression`)}return a})},X.parseMaybeAssign=function(e,t,n){if(this.isContextual(`yield`)){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var r=!1,i=-1,a=-1,o=-1;t?(i=t.parenthesizedAssign,a=t.trailingComma,o=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new KC,r=!0);var s=this.start,c=this.startLoc;(this.type===J.parenL||this.type===J.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=e===`await`);var l=this.parseMaybeConditional(e,t);if(n&&(l=n.call(this,l,s,c)),this.type.isAssign){var u=this.startNodeAt(s,c);return u.operator=this.value,this.type===J.eq&&(l=this.toAssignable(l,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=l.start&&(t.shorthandAssign=-1),this.type===J.eq?this.checkLValPattern(l):this.checkLValSimple(l),u.left=l,this.next(),u.right=this.parseMaybeAssign(e),o>-1&&(t.doubleProto=o),this.finishNode(u,`AssignmentExpression`)}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),a>-1&&(t.trailingComma=a),l},X.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if((i.type!==`ArrowFunctionExpression`||i.start!==n)&&this.eat(J.question)){var a=this.startNodeAt(n,r);return a.test=i,a.consequent=this.parseMaybeAssign(),this.expect(J.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,`ConditionalExpression`)}return i},X.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===n&&i.type===`ArrowFunctionExpression`?i:this.parseExprOp(i,n,r,-1,e)},X.parseExprOp=function(e,t,n,r,i){var a=this.type.binop;if(a!=null&&(!i||this.type!==J._in)&&a>r){var o=this.type===J.logicalOR||this.type===J.logicalAND,s=this.type===J.coalesce;s&&(a=J.logicalAND.binop);var c=this.value;this.next();var l=this.start,u=this.startLoc,d=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),l,u,a,i),f=this.buildBinary(t,n,e,d,c,o||s);return(o&&this.type===J.coalesce||s&&(this.type===J.logicalOR||this.type===J.logicalAND))&&this.raiseRecoverable(this.start,`Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses`),this.parseExprOp(f,t,n,r,i)}return e},X.buildBinary=function(e,t,n,r,i,a){r.type===`PrivateIdentifier`&&this.raise(r.start,`Private identifier can only be left side of binary expression`);var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,a?`LogicalExpression`:`BinaryExpression`)},X.parseMaybeUnary=function(e,t,n,r){var i=this.start,a=this.startLoc,o;if(this.isContextual(`await`)&&this.canAwait)o=this.parseAwait(r),t=!0;else if(this.type.prefix){var s=this.startNode(),c=this.type===J.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0,c,r),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(s.argument):this.strict&&s.operator===`delete`&&aw(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&ow(s.argument)?this.raiseRecoverable(s.start,`Private fields can not be deleted`):t=!0,o=this.finishNode(s,c?`UpdateExpression`:`UnaryExpression`)}else if(!t&&this.type===J.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==J._in&&this.unexpected();else{if(o=this.parseExprSubscripts(e,r),this.checkExpressionErrors(e))return o;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(i,a);l.operator=this.value,l.prefix=!1,l.argument=o,this.checkLValSimple(o),this.next(),o=this.finishNode(l,`UpdateExpression`)}}if(!n&&(o.type!==`ArrowFunctionExpression`||o.start!==i)&&this.eat(J.starstar)){if(t)this.unexpected(this.lastTokStart);else return this.buildBinary(i,a,o,this.parseMaybeUnary(null,!1,!1,r),`**`,!1)}else return o};function aw(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&&aw(e.expression)}function ow(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&ow(e.expression)||e.type===`ParenthesizedExpression`&&ow(e.expression)}X.parseExprSubscripts=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprAtom(e,t);if(i.type===`ArrowFunctionExpression`&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==`)`)return i;var a=this.parseSubscripts(i,n,r,!1,t);return e&&a.type===`MemberExpression`&&(e.parenthesizedAssign>=a.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=a.start&&(e.parenthesizedBind=-1),e.trailingComma>=a.start&&(e.trailingComma=-1)),a},X.parseSubscripts=function(e,t,n,r,i){for(var a=this.options.ecmaVersion>=8&&e.type===`Identifier`&&e.name===`async`&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.potentialArrowAt===e.start,o=!1;;){var s=this.parseSubscript(e,t,n,r,a,o,i);if(s.optional&&(o=!0),s===e||s.type===`ArrowFunctionExpression`){if(o){var c=this.startNodeAt(t,n);c.expression=s,s=this.finishNode(c,`ChainExpression`)}return s}e=s}},X.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(J.arrow)},X.parseSubscriptAsyncArrow=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!0,r)},X.parseSubscript=function(e,t,n,r,i,a,o){var s=this.options.ecmaVersion>=11,c=s&&this.eat(J.questionDot);r&&c&&this.raise(this.lastTokStart,`Optional chaining cannot appear in the callee of new expressions`);var l=this.eat(J.bracketL);if(l||c&&this.type!==J.parenL&&this.type!==J.backQuote||this.eat(J.dot)){var u=this.startNodeAt(t,n);u.object=e,l?(u.property=this.parseExpression(),this.expect(J.bracketR)):u.property=this.type===J.privateId&&e.type!==`Super`?this.parsePrivateIdent():this.parseIdent(this.options.allowReserved!==`never`),u.computed=!!l,s&&(u.optional=c),e=this.finishNode(u,`MemberExpression`)}else if(!r&&this.eat(J.parenL)){var d=new KC,f=this.yieldPos,p=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var ee=this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1,d);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,`Cannot use 'await' as identifier inside an async function`),this.yieldPos=f,this.awaitPos=p,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,n,ee,o);this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var te=this.startNodeAt(t,n);te.callee=e,te.arguments=ee,s&&(te.optional=c),e=this.finishNode(te,`CallExpression`)}else if(this.type===J.backQuote){(c||a)&&this.raise(this.start,`Optional chaining cannot appear in the tag of tagged template expressions`);var ne=this.startNodeAt(t,n);ne.tag=e,ne.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(ne,`TaggedTemplateExpression`)}return e},X.parseExprAtom=function(e,t,n){this.type===J.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case J._super:return this.allowSuper||this.raise(this.start,`'super' keyword outside a method`),r=this.startNode(),this.next(),this.type===J.parenL&&!this.allowDirectSuper&&this.raise(r.start,`super() call outside constructor of a subclass`),this.type!==J.dot&&this.type!==J.bracketL&&this.type!==J.parenL&&this.unexpected(),this.finishNode(r,`Super`);case J._this:return r=this.startNode(),this.next(),this.finishNode(r,`ThisExpression`);case J.name:var a=this.start,o=this.startLoc,s=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!s&&c.name===`async`&&!this.canInsertSemicolon()&&this.eat(J._function))return this.overrideContext(rw.f_expr),this.parseFunction(this.startNodeAt(a,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(J.arrow))return this.parseArrowExpression(this.startNodeAt(a,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name===`async`&&this.type===J.name&&!s&&(!this.potentialArrowInForAwait||this.value!==`of`||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(J.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,o),[c],!0,t)}return c;case J.regexp:var l=this.value;return r=this.parseLiteral(l.value),r.regex={pattern:l.pattern,flags:l.flags},r;case J.num:case J.string:return this.parseLiteral(this.value);case J._null:case J._true:case J._false:return r=this.startNode(),r.value=this.type===J._null?null:this.type===J._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,`Literal`);case J.parenL:var u=this.start,d=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)&&(e.parenthesizedAssign=u),e.parenthesizedBind<0&&(e.parenthesizedBind=u)),d;case J.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(J.bracketR,!0,!0,e),this.finishNode(r,`ArrayExpression`);case J.braceL:return this.overrideContext(rw.b_expr),this.parseObj(!1,e);case J._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case J._class:return this.parseClass(this.startNode(),!1);case J._new:return this.parseNew();case J.backQuote:return this.parseTemplate();case J._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}},X.parseExprAtomDefault=function(){this.unexpected()},X.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword import`),this.next(),this.type===J.parenL&&!e)return this.parseDynamicImport(t);if(this.type===J.dot){var n=this.startNodeAt(t.start,t.loc&&t.loc.start);return n.name=`import`,t.meta=this.finishNode(n,`Identifier`),this.parseImportMeta(t)}this.unexpected()},X.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(J.parenR)?e.options=null:(this.expect(J.comma),this.afterTrailingComma(J.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(J.parenR)||(this.expect(J.comma),this.afterTrailingComma(J.parenR)||this.unexpected())));else if(!this.eat(J.parenR)){var t=this.start;this.eat(J.comma)&&this.eat(J.parenR)?this.raiseRecoverable(t,`Trailing comma is not allowed in import()`):this.unexpected(t)}return this.finishNode(e,`ImportExpression`)},X.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`meta`&&this.raiseRecoverable(e.property.start,`The only valid meta property for import is 'import.meta'`),t&&this.raiseRecoverable(e.start,`'import.meta' must not contain escaped characters`),this.options.sourceType!==`module`&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,`Cannot use 'import.meta' outside a module`),this.finishNode(e,`MetaProperty`)},X.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value==null?t.raw.slice(0,-1).replace(/_/g,``):t.value.toString()),this.next(),this.finishNode(t,`Literal`)},X.parseParenExpression=function(){this.expect(J.parenL);var e=this.parseExpression();return this.expect(J.parenR),e},X.shouldParseArrow=function(e){return!this.canInsertSemicolon()},X.parseParenAndDistinguishExpression=function(e,t){var n=this.start,r=this.startLoc,i,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc,c=[],l=!0,u=!1,d=new KC,f=this.yieldPos,p=this.awaitPos,m;for(this.yieldPos=0,this.awaitPos=0;this.type!==J.parenR;){if(l?l=!1:this.expect(J.comma),a&&this.afterTrailingComma(J.parenR,!0)){u=!0;break}if(this.type===J.ellipsis){m=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`);break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var ee=this.lastTokEnd,te=this.lastTokEndLoc;if(this.expect(J.parenR),e&&this.shouldParseArrow(c)&&this.eat(J.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=p,this.parseParenArrowList(n,r,c,t);(!c.length||u)&&this.unexpected(this.lastTokStart),m&&this.unexpected(m),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,c.length>1?(i=this.startNodeAt(o,s),i.expressions=c,this.finishNodeAt(i,`SequenceExpression`,ee,te)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var ne=this.startNodeAt(n,r);return ne.expression=i,this.finishNode(ne,`ParenthesizedExpression`)}return i},X.parseParenItem=function(e){return e},X.parseParenArrowList=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!1,r)};var sw=[];X.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword new`);var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===J.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name=`new`,e.meta=this.finishNode(t,`Identifier`),this.next();var n=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`target`&&this.raiseRecoverable(e.property.start,`The only valid meta property for new is 'new.target'`),n&&this.raiseRecoverable(e.start,`'new.target' must not contain escaped characters`),this.allowNewDotTarget||this.raiseRecoverable(e.start,`'new.target' can only be used in functions and class static block`),this.finishNode(e,`MetaProperty`)}var r=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,i,!0,!1),e.callee.type===`Super`&&this.raiseRecoverable(r,`Invalid use of 'super'`),e.arguments=this.eat(J.parenL)?this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1):sw,this.finishNode(e,`NewExpression`)},X.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===J.invalidTemplate?(t||this.raiseRecoverable(this.start,`Bad escape sequence in untagged template literal`),n.value={raw:this.value.replace(/\r\n?/g,`
|
|
13
13
|
`),cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
|
|
14
|
-
`),cooked:this.value},this.next(),n.tail=this.type===J.backQuote,this.finishNode(n,`TemplateElement`)},X.parseTemplate=function(e){e===void 0&&(e={});var t=e.isTagged;t===void 0&&(t=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(n.quasis=[r];!r.tail;)this.type===J.eof&&this.raise(this.pos,`Unterminated template literal`),this.expect(J.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(J.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,`TemplateLiteral`)},X.isAsyncProp=function(e){return!e.computed&&e.key.type===`Identifier`&&e.key.name===`async`&&(this.type===J.name||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===J.star)&&!eC.test(this.input.slice(this.lastTokEnd,this.start))},X.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(J.braceR);){if(r)r=!1;else if(this.expect(J.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(J.braceR))break;var a=this.parseProperty(e,t);e||this.checkPropClash(a,i,t),n.properties.push(a)}return this.finishNode(n,e?`ObjectPattern`:`ObjectExpression`)},X.parseProperty=function(e,t){var n=this.startNode(),r,i,a,o;if(this.options.ecmaVersion>=9&&this.eat(J.ellipsis))return e?(n.argument=this.parseIdent(!1),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.finishNode(n,`RestElement`)):(n.argument=this.parseMaybeAssign(!1,t),this.type===J.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(n,`SpreadElement`));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(e||t)&&(a=this.start,o=this.startLoc),e||(r=this.eat(J.star)));var s=this.containsEsc;return this.parsePropertyName(n),!e&&!s&&this.options.ecmaVersion>=8&&!r&&this.isAsyncProp(n)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(J.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,e,r,i,a,o,t,s),this.finishNode(n,`Property`)},X.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var n=e.kind===`get`?0:1;if(e.value.params.length!==n){var r=e.value.start;e.kind===`get`?this.raiseRecoverable(r,`getter should have no params`):this.raiseRecoverable(r,`setter should have exactly one param`)}else e.kind===`set`&&e.value.params[0].type===`RestElement`&&this.raiseRecoverable(e.value.params[0].start,`Setter cannot use rest params`)},X.parsePropertyValue=function(e,t,n,r,i,a,o,s){(n||r)&&this.type===J.colon&&this.unexpected(),this.eat(J.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind=`init`):this.options.ecmaVersion>=6&&this.type===J.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(n,r),e.kind=`init`):!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type===`Identifier`&&(e.key.name===`get`||e.key.name===`set`)&&this.type!==J.comma&&this.type!==J.braceR&&this.type!==J.eq?((n||r)&&this.unexpected(),this.parseGetterSetter(e)):this.options.ecmaVersion>=6&&!e.computed&&e.key.type===`Identifier`?((n||r)&&this.unexpected(),this.checkUnreserved(e.key),e.key.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key)):this.type===J.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind=`init`,e.shorthand=!0):this.unexpected()},X.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(J.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(J.bracketR),e.key;e.computed=!1}return e.key=this.type===J.num||this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`)},X.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},X.parseMethod=function(e,t,n){var r=this.startNode(),i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(PC(t,r.generator)|OC|(n?kC:0)),this.expect(J.parenL),r.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(r,`FunctionExpression`)},X.parseArrowExpression=function(e,t,n,r){var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(PC(n,!1)|EC),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!n),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,`ArrowFunctionExpression`)},X.parseFunctionBody=function(e,t,n,r){var i=t&&this.type!==J.braceL,a=this.strict,o=!1;if(i)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!a||s)&&(o=this.strictDirective(this.end),o&&s&&this.raiseRecoverable(e.start,`Illegal 'use strict' directive in function with non-simple parameter list`));var c=this.labels;this.labels=[],o&&(this.strict=!0),this.checkParams(e,!a&&!o&&!t&&!n&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,BC),e.body=this.parseBlock(!1,void 0,o&&!a),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()},X.isSimpleParamList=function(e){for(var t=0,n=e;t<n.length;t+=1)if(n[t].type!==`Identifier`)return!1;return!0},X.checkParams=function(e,t){for(var n=Object.create(null),r=0,i=e.params;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,IC,t?null:n)}},X.parseExprList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);){if(a)a=!1;else if(this.expect(J.comma),t&&this.afterTrailingComma(e))break;var o=void 0;n&&this.type===J.comma?o=null:this.type===J.ellipsis?(o=this.parseSpread(r),r&&this.type===J.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):o=this.parseMaybeAssign(!1,r),i.push(o)}return i},X.checkUnreserved=function(e){var t=e.start,n=e.end,r=e.name;this.inGenerator&&r===`yield`&&this.raiseRecoverable(t,`Cannot use 'yield' as identifier inside a generator`),this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use 'await' as identifier inside an async function`),!(this.currentThisScope().flags&NC)&&r===`arguments`&&this.raiseRecoverable(t,`Cannot use 'arguments' in class field initializer`),this.inClassStaticBlock&&(r===`arguments`||r===`await`)&&this.raise(t,`Cannot use `+r+` in class static initialization block`),this.keywords.test(r)&&this.raise(t,`Unexpected keyword '`+r+`'`),!(this.options.ecmaVersion<6&&this.input.slice(t,n).indexOf(`\\`)!==-1)&&(this.strict?this.reservedWordsStrict:this.reservedWords).test(r)&&(!this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use keyword 'await' outside an async function`),this.raiseRecoverable(t,`The keyword '`+r+`' is reserved`))},X.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,`Identifier`),e||(this.checkUnreserved(t),t.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=t.start)),t},X.parseIdentNode=function(){var e=this.startNode();return this.type===J.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,(e.name===`class`||e.name===`function`)&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=J.name):this.unexpected(),e},X.parsePrivateIdent=function(){var e=this.startNode();return this.type===J.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,`PrivateIdentifier`),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(e.start,`Private field '#`+e.name+`' must be declared in an enclosing class`):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e},X.parseYield=function(e){this.yieldPos||=this.start;var t=this.startNode();return this.next(),this.type===J.semi||this.canInsertSemicolon()||this.type!==J.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(J.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,`YieldExpression`)},X.parseAwait=function(e){this.awaitPos||=this.start;var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,`AwaitExpression`)};var sw=VC.prototype;sw.raise=function(e,t){var n=_C(this.input,e);t+=` (`+n.line+`:`+n.column+`)`,this.sourceFile&&(t+=` in `+this.sourceFile);var r=SyntaxError(t);throw r.pos=e,r.loc=n,r.raisedAt=this.pos,r},sw.raiseRecoverable=sw.raise,sw.curPosition=function(){if(this.options.locations)return new hC(this.curLine,this.pos-this.lineStart)};var cw=VC.prototype,lw=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};cw.enterScope=function(e){this.scopeStack.push(new lw(e))},cw.exitScope=function(){this.scopeStack.pop()},cw.treatFunctionsAsVarInScope=function(e){return e.flags&CC||!this.inModule&&e.flags&SC},cw.declareName=function(e,t,n){var r=!1;if(t===LC){var i=this.currentScope();r=i.lexical.indexOf(e)>-1||i.functions.indexOf(e)>-1||i.var.indexOf(e)>-1,i.lexical.push(e),this.inModule&&i.flags&SC&&delete this.undefinedExports[e]}else if(t===zC)this.currentScope().lexical.push(e);else if(t===RC){var a=this.currentScope();r=this.treatFunctionsAsVar?a.lexical.indexOf(e)>-1:a.lexical.indexOf(e)>-1||a.var.indexOf(e)>-1,a.functions.push(e)}else for(var o=this.scopeStack.length-1;o>=0;--o){var s=this.scopeStack[o];if(s.lexical.indexOf(e)>-1&&!(s.flags&DC&&s.lexical[0]===e)||!this.treatFunctionsAsVarInScope(s)&&s.functions.indexOf(e)>-1){r=!0;break}if(s.var.push(e),this.inModule&&s.flags&SC&&delete this.undefinedExports[e],s.flags&NC)break}r&&this.raiseRecoverable(n,`Identifier '`+e+`' has already been declared`)},cw.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)},cw.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},cw.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(NC|jC|AC))return t}},cw.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(NC|jC|AC)&&!(t.flags&EC))return t}};var uw=function(e,t,n){this.type=``,this.start=t,this.end=0,e.options.locations&&(this.loc=new gC(e,n)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},dw=VC.prototype;dw.startNode=function(){return new uw(this,this.start,this.startLoc)},dw.startNodeAt=function(e,t){return new uw(this,e,t)};function fw(e,t,n,r){return e.type=t,e.end=n,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=n),e}dw.finishNode=function(e,t){return fw.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},dw.finishNodeAt=function(e,t,n,r){return fw.call(this,e,t,n,r)},dw.copyNode=function(e){var t=new uw(this,e.start,this.startLoc);for(var n in e)t[n]=e[n];return t};var pw=`Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz`,mw=`ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS`,hw=mw+` Extended_Pictographic`,gw=hw,_w=gw+` EBase EComp EMod EPres ExtPict`,vw=_w,yw={9:mw,10:hw,11:gw,12:_w,13:vw,14:vw},bw={9:``,10:``,11:``,12:``,13:``,14:`Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji`},xw=`Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu`,Sw=`Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb`,Cw=Sw+` Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd`,ww=Cw+` Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho`,Tw=ww+` Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi`,Ew=Tw+` Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith`,Dw={9:Sw,10:Cw,11:ww,12:Tw,13:Ew,14:Ew+` `+pw},Ow={};function kw(e){var t=Ow[e]={binary:fC(yw[e]+` `+xw),binaryOfStrings:fC(bw[e]),nonBinary:{General_Category:fC(xw),Script:fC(Dw[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var Aw=0,jw=[9,10,11,12,13,14];Aw<jw.length;Aw+=1){var Mw=jw[Aw];kw(Mw)}var Z=VC.prototype,Nw=function(e,t){this.parent=e,this.base=t||this};Nw.prototype.separatedFrom=function(e){for(var t=this;t;t=t.parent)for(var n=e;n;n=n.parent)if(t.base===n.base&&t!==n)return!0;return!1},Nw.prototype.sibling=function(){return new Nw(this.parent,this.base)};var Pw=function(e){this.parser=e,this.validFlags=`gim`+(e.options.ecmaVersion>=6?`uy`:``)+(e.options.ecmaVersion>=9?`s`:``)+(e.options.ecmaVersion>=13?`d`:``)+(e.options.ecmaVersion>=15?`v`:``),this.unicodeProperties=Ow[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source=``,this.flags=``,this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue=``,this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};Pw.prototype.reset=function(e,t,n){var r=n.indexOf(`v`)!==-1,i=n.indexOf(`u`)!==-1;this.start=e|0,this.source=t+``,this.flags=n,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=i&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=i&&this.parser.options.ecmaVersion>=9)},Pw.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,`Invalid regular expression: /`+this.source+`/: `+e)},Pw.prototype.at=function(e,t){t===void 0&&(t=!1);var n=this.source,r=n.length;if(e>=r)return-1;var i=n.charCodeAt(e);if(!(t||this.switchU)||i<=55295||i>=57344||e+1>=r)return i;var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(i<<10)+a-56613888:i},Pw.prototype.nextIndex=function(e,t){t===void 0&&(t=!1);var n=this.source,r=n.length;if(e>=r)return r;var i=n.charCodeAt(e),a;return!(t||this.switchU)||i<=55295||i>=57344||e+1>=r||(a=n.charCodeAt(e+1))<56320||a>57343?e+1:e+2},Pw.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)},Pw.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Pw.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Pw.prototype.eat=function(e,t){return t===void 0&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Pw.prototype.eatChars=function(e,t){t===void 0&&(t=!1);for(var n=this.pos,r=0,i=e;r<i.length;r+=1){var a=i[r],o=this.at(n,t);if(o===-1||o!==a)return!1;n=this.nextIndex(n,t)}return this.pos=n,!0},Z.validateRegExpFlags=function(e){for(var t=e.validFlags,n=e.flags,r=!1,i=!1,a=0;a<n.length;a++){var o=n.charAt(a);t.indexOf(o)===-1&&this.raise(e.start,`Invalid regular expression flag`),n.indexOf(o,a+1)>-1&&this.raise(e.start,`Duplicate regular expression flag`),o===`u`&&(r=!0),o===`v`&&(i=!0)}this.options.ecmaVersion>=15&&r&&i&&this.raise(e.start,`Invalid regular expression flag`)};function Fw(e){for(var t in e)return!0;return!1}Z.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&Fw(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Z.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue=``,e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise(`Unmatched ')'`),(e.eat(93)||e.eat(125))&&e.raise(`Lone quantifier brackets`)),e.maxBackReference>e.numCapturingParens&&e.raise(`Invalid escape`);for(var t=0,n=e.backReferenceNames;t<n.length;t+=1){var r=n[t];e.groupNames[r]||e.raise(`Invalid named capture referenced`)}},Z.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new Nw(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise(`Nothing to repeat`),e.eat(123)&&e.raise(`Lone quantifier brackets`)},Z.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},Z.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise(`Invalid quantifier`),!0):(e.switchU?this.regexp_eatAtom(e):this.regexp_eatExtendedAtom(e))?(this.regexp_eatQuantifier(e),!0):!1},Z.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var n=!1;if(this.options.ecmaVersion>=9&&(n=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise(`Unterminated group`),e.lastAssertionIsQuantifiable=!n,!0}return e.pos=t,!1},Z.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1},Z.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Z.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var r=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return i!==-1&&i<r&&!t&&e.raise(`numbers out of order in {} quantifier`),!0;e.switchU&&!t&&e.raise(`Incomplete quantifier`),e.pos=n}return!1},Z.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)},Z.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},Z.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var n=this.regexp_eatModifiers(e),r=e.eat(45);if(n||r){for(var i=0;i<n.length;i++){var a=n.charAt(i);n.indexOf(a,i+1)>-1&&e.raise(`Duplicate regular expression modifiers`)}if(r){var o=this.regexp_eatModifiers(e);!n&&!o&&e.current()===58&&e.raise(`Invalid regular expression modifiers`);for(var s=0;s<o.length;s++){var c=o.charAt(s);(o.indexOf(c,s+1)>-1||n.indexOf(c)>-1)&&e.raise(`Duplicate regular expression modifiers`)}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise(`Unterminated group`)}}e.pos=t}return!1},Z.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):e.current()===63&&e.raise(`Invalid group`),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise(`Unterminated group`)}return!1},Z.regexp_eatModifiers=function(e){for(var t=``,n=0;(n=e.current())!==-1&&Iw(n);)t+=pC(n),e.advance();return t};function Iw(e){return e===105||e===109||e===115}Z.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Z.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise(`Nothing to repeat`),!1},Z.regexp_eatSyntaxCharacter=function(e){var t=e.current();return Lw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Lw(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Z.regexp_eatPatternCharacters=function(e){for(var t=e.pos,n=0;(n=e.current())!==-1&&!Lw(n);)e.advance();return e.pos!==t},Z.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124&&(e.advance(),!0)},Z.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise(`Invalid group`);var t=this.options.ecmaVersion>=16,n=e.groupNames[e.lastStringValue];if(n){if(t)for(var r=0,i=n;r<i.length;r+=1)i[r].separatedFrom(e.branchID)||e.raise(`Duplicate capture group name`);else e.raise(`Duplicate capture group name`)}t?(n||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}},Z.regexp_eatGroupName=function(e){if(e.lastStringValue=``,e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise(`Invalid capture group name`)}return!1},Z.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue=``,this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=pC(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=pC(e.lastIntValue);return!0}return!1},Z.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),Rw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function Rw(e){return JS(e,!0)||e===36||e===95}Z.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),zw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function zw(e){return YS(e,!0)||e===36||e===95||e===8204||e===8205}Z.regexp_eatAtomEscape=function(e){return this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)?!0:(e.switchU&&(e.current()===99&&e.raise(`Invalid unicode escape`),e.raise(`Invalid escape`)),!1)},Z.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU)return n>e.maxBackReference&&(e.maxBackReference=n),!0;if(n<=e.numCapturingParens)return!0;e.pos=t}return!1},Z.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise(`Invalid named reference`)}return!1},Z.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Z.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Z.regexp_eatZero=function(e){return e.current()===48&&!Zw(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Z.regexp_eatControlEscape=function(e){var t=e.current();return t===116?(e.lastIntValue=9,e.advance(),!0):t===110?(e.lastIntValue=10,e.advance(),!0):t===118?(e.lastIntValue=11,e.advance(),!0):t===102?(e.lastIntValue=12,e.advance(),!0):t===114&&(e.lastIntValue=13,e.advance(),!0)},Z.regexp_eatControlLetter=function(e){var t=e.current();return Bw(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function Bw(e){return e>=65&&e<=90||e>=97&&e<=122}Z.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){t===void 0&&(t=!1);var n=e.pos,r=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(r&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(i-55296)*1024+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(r&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&Vw(e.lastIntValue))return!0;r&&e.raise(`Invalid unicode escape`),e.pos=n}return!1};function Vw(e){return e>=0&&e<=1114111}Z.regexp_eatIdentityEscape=function(e){if(e.switchU)return this.regexp_eatSyntaxCharacter(e)?!0:e.eat(47)?(e.lastIntValue=47,!0):!1;var t=e.current();return t!==99&&(!e.switchN||t!==107)&&(e.lastIntValue=t,e.advance(),!0)},Z.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1};var Hw=0,Uw=1,Ww=2;Z.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(Gw(t))return e.lastIntValue=-1,e.advance(),Uw;var n=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((n=t===80)||t===112)){e.lastIntValue=-1,e.advance();var r;if(e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return n&&r===Ww&&e.raise(`Invalid property name`),r;e.raise(`Invalid property name`)}return Hw};function Gw(e){return e===100||e===68||e===115||e===83||e===119||e===87}Z.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,n,r),Uw}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return Hw},Z.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){lC(e.unicodeProperties.nonBinary,t)||e.raise(`Invalid property name`),e.unicodeProperties.nonBinary[t].test(n)||e.raise(`Invalid property value`)},Z.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return Uw;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return Ww;e.raise(`Invalid property name`)},Z.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue=``;Kw(t=e.current());)e.lastStringValue+=pC(t),e.advance();return e.lastStringValue!==``};function Kw(e){return Bw(e)||e===95}Z.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue=``;qw(t=e.current());)e.lastStringValue+=pC(t),e.advance();return e.lastStringValue!==``};function qw(e){return Kw(e)||Zw(e)}Z.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Z.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),n=this.regexp_classContents(e);return e.eat(93)||e.raise(`Unterminated character class`),t&&n===Ww&&e.raise(`Negated character class may contain strings`),!0}return!1},Z.regexp_classContents=function(e){return e.current()===93?Uw:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),Uw)},Z.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;e.switchU&&(t===-1||n===-1)&&e.raise(`Invalid character class`),t!==-1&&n!==-1&&t>n&&e.raise(`Range out of order in character class`)}}},Z.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var n=e.current();(n===99||eT(n))&&e.raise(`Invalid class escape`),e.raise(`Invalid escape`)}e.pos=t}var r=e.current();return r!==93&&(e.lastIntValue=r,e.advance(),!0)},Z.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Z.regexp_classSetExpression=function(e){var t=Uw,n;if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e)){n===Ww&&(t=Ww);for(var r=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(n=this.regexp_eatClassSetOperand(e))){n!==Ww&&(t=Uw);continue}e.raise(`Invalid character in character class`)}if(r!==e.pos)return t;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise(`Invalid character in character class`);if(r!==e.pos)return t}else e.raise(`Invalid character in character class`)}for(;;)if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e),!n)return t;n===Ww&&(t=Ww)}},Z.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return n!==-1&&r!==-1&&n>r&&e.raise(`Range out of order in character class`),!0}e.pos=t}return!1},Z.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?Uw:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Z.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var n=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return n&&r===Ww&&e.raise(`Negated character class may contain strings`),r;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null},Z.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var n=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return n}else e.raise(`Invalid escape`);e.pos=t}return null},Z.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===Ww&&(t=Ww);return t},Z.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?Uw:Ww},Z.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e)?!0:e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1);var n=e.current();return n<0||n===e.lookahead()&&Jw(n)||Yw(n)?!1:(e.advance(),e.lastIntValue=n,!0)};function Jw(e){return e===33||e>=35&&e<=38||e>=42&&e<=44||e===46||e>=58&&e<=64||e===94||e===96||e===126}function Yw(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}Z.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return Xw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Xw(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}Z.regexp_eatClassControlLetter=function(e){var t=e.current();return Zw(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1},Z.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise(`Invalid escape`),e.pos=t}return!1},Z.regexp_eatDecimalDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;Zw(n=e.current());)e.lastIntValue=10*e.lastIntValue+(n-48),e.advance();return e.pos!==t};function Zw(e){return e>=48&&e<=57}Z.regexp_eatHexDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;Qw(n=e.current());)e.lastIntValue=16*e.lastIntValue+$w(n),e.advance();return e.pos!==t};function Qw(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function $w(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}Z.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;e.lastIntValue=t<=3&&this.regexp_eatOctalDigit(e)?t*64+n*8+e.lastIntValue:t*8+n}else e.lastIntValue=t;return!0}return!1},Z.regexp_eatOctalDigit=function(e){var t=e.current();return eT(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function eT(e){return e>=48&&e<=55}Z.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var r=0;r<t;++r){var i=e.current();if(!Qw(i))return e.pos=n,!1;e.lastIntValue=16*e.lastIntValue+$w(i),e.advance()}return!0};var tT=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new gC(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},Q=VC.prototype;Q.next=function(e){!e&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword `+this.type.keyword),this.options.onToken&&this.options.onToken(new tT(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},Q.getToken=function(){return this.next(),new tT(this)},typeof Symbol<`u`&&(Q[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===J.eof,value:t}}}}),Q.nextToken=function(){var e=this.curContext();if((!e||!e.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(J.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())},Q.readToken=function(e){return JS(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)},Q.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var n=this.input.charCodeAt(e+1);return n<=56319||n>=57344?t:(t<<10)+n-56613888},Q.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},Q.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,n=this.input.indexOf(`*/`,this.pos+=2);if(n===-1&&this.raise(this.pos-2,`Unterminated comment`),this.pos=n+2,this.options.locations)for(var r=void 0,i=t;(r=rC(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,n),t,this.pos,e,this.curPosition())},Q.skipLineComment=function(e){for(var t=this.pos,n=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!nC(r);)r=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,n,this.curPosition())},Q.skipSpace=function(){loop:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break loop}break;default:if(e>8&&e<14||e>=5760&&iC.test(String.fromCharCode(e)))++this.pos;else break loop}}},Q.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},Q.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&e===46&&t===46?(this.pos+=3,this.finishToken(J.ellipsis)):(++this.pos,this.finishToken(J.dot))},Q.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(J.assign,2):this.finishOp(J.slash,1)},Q.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=e===42?J.star:J.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++n,r=J.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(J.assign,n+1):this.finishOp(r,n)},Q.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(e===124?J.logicalOR:J.logicalAND,2):t===61?this.finishOp(J.assign,2):this.finishOp(e===124?J.bitwiseOR:J.bitwiseAND,1)},Q.readToken_caret=function(){return this.input.charCodeAt(this.pos+1)===61?this.finishOp(J.assign,2):this.finishOp(J.bitwiseXOR,1)},Q.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||eC.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(J.incDec,2):t===61?this.finishOp(J.assign,2):this.finishOp(J.plusMin,1)},Q.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+n)===61?this.finishOp(J.assign,n+1):this.finishOp(J.bitShift,n)):t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(t===61&&(n=2),this.finishOp(J.relational,n))},Q.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(J.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(J.arrow)):this.finishOp(e===61?J.eq:J.prefix,1)},Q.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57)return this.finishOp(J.questionDot,2)}if(t===63)return e>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(J.coalesce,2)}return this.finishOp(J.question,1)},Q.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),JS(t,!0)||t===92))return this.finishToken(J.privateId,this.readWord1());this.raise(this.pos,`Unexpected character '`+pC(t)+`'`)},Q.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(J.parenL);case 41:return++this.pos,this.finishToken(J.parenR);case 59:return++this.pos,this.finishToken(J.semi);case 44:return++this.pos,this.finishToken(J.comma);case 91:return++this.pos,this.finishToken(J.bracketL);case 93:return++this.pos,this.finishToken(J.bracketR);case 123:return++this.pos,this.finishToken(J.braceL);case 125:return++this.pos,this.finishToken(J.braceR);case 58:return++this.pos,this.finishToken(J.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(J.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(t===111||t===79)return this.readRadixNumber(8);if(t===98||t===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(J.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,`Unexpected character '`+pC(e)+`'`)},Q.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)},Q.readRegexp=function(){for(var e,t,n=this.pos;;){this.pos>=this.input.length&&this.raise(n,`Unterminated regular expression`);var r=this.input.charAt(this.pos);if(eC.test(r)&&this.raise(n,`Unterminated regular expression`),e)e=!1;else{if(r===`[`)t=!0;else if(r===`]`&&t)t=!1;else if(r===`/`&&!t)break;e=r===`\\`}++this.pos}var i=this.input.slice(n,this.pos);++this.pos;var a=this.pos,o=this.readWord1();this.containsEsc&&this.unexpected(a);var s=this.regexpState||=new Pw(this);s.reset(n,i,o),this.validateRegExpFlags(s),this.validateRegExpPattern(s);var c=null;try{c=new RegExp(i,o)}catch{}return this.finishToken(J.regexp,{pattern:i,flags:o,value:c})},Q.readInt=function(e,t,n){for(var r=this.options.ecmaVersion>=12&&t===void 0,i=n&&this.input.charCodeAt(this.pos)===48,a=this.pos,o=0,s=0,c=0,l=t??1/0;c<l;++c,++this.pos){var u=this.input.charCodeAt(this.pos),d=void 0;if(r&&u===95){i&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed in legacy octal numeric literals`),s===95&&this.raiseRecoverable(this.pos,`Numeric separator must be exactly one underscore`),c===0&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed at the first of digits`),s=u;continue}if(d=u>=97?u-97+10:u>=65?u-65+10:u>=48&&u<=57?u-48:1/0,d>=e)break;s=u,o=o*e+d}return r&&s===95&&this.raiseRecoverable(this.pos-1,`Numeric separator is not allowed at the last of digits`),this.pos===a||t!=null&&this.pos-a!==t?null:o};function nT(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,``))}function rT(e){return typeof BigInt==`function`?BigInt(e.replace(/_/g,``)):null}Q.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);return n??this.raise(this.start+2,`Expected number in radix `+e),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(n=rT(this.input.slice(t,this.pos)),++this.pos):JS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,n)},Q.readNumber=function(e){var t=this.pos;!e&&this.readInt(10,void 0,!0)===null&&this.raise(t,`Invalid number`);var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;n&&this.strict&&this.raise(t,`Invalid number`);var r=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&r===110){var i=rT(this.input.slice(t,this.pos));return++this.pos,JS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,i)}n&&/[89]/.test(this.input.slice(t,this.pos))&&(n=!1),r===46&&!n&&(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),(r===69||r===101)&&!n&&(r=this.input.charCodeAt(++this.pos),(r===43||r===45)&&++this.pos,this.readInt(10)===null&&this.raise(t,`Invalid number`)),JS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`);var a=nT(this.input.slice(t,this.pos),n);return this.finishToken(J.num,a)},Q.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){this.options.ecmaVersion<6&&this.unexpected();var n=++this.pos;t=this.readHexChar(this.input.indexOf(`}`,this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(n,`Code point out of bounds`)}else t=this.readHexChar(4);return t},Q.readString=function(e){for(var t=``,n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated string constant`);var r=this.input.charCodeAt(this.pos);if(r===e)break;r===92?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(!1),n=this.pos):r===8232||r===8233?(this.options.ecmaVersion<10&&this.raise(this.start,`Unterminated string constant`),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(nC(r)&&this.raise(this.start,`Unterminated string constant`),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(J.string,t)};var iT={};Q.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===iT)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},Q.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw iT;this.raise(e,t)},Q.readTmplToken=function(){for(var e=``,t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated template`);var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===J.template||this.type===J.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(J.dollarBraceL)):(++this.pos,this.finishToken(J.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(J.template,e));if(n===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(nC(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=`
|
|
14
|
+
`),cooked:this.value},this.next(),n.tail=this.type===J.backQuote,this.finishNode(n,`TemplateElement`)},X.parseTemplate=function(e){e===void 0&&(e={});var t=e.isTagged;t===void 0&&(t=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(n.quasis=[r];!r.tail;)this.type===J.eof&&this.raise(this.pos,`Unterminated template literal`),this.expect(J.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(J.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,`TemplateLiteral`)},X.isAsyncProp=function(e){return!e.computed&&e.key.type===`Identifier`&&e.key.name===`async`&&(this.type===J.name||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===J.star)&&!tC.test(this.input.slice(this.lastTokEnd,this.start))},X.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(J.braceR);){if(r)r=!1;else if(this.expect(J.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(J.braceR))break;var a=this.parseProperty(e,t);e||this.checkPropClash(a,i,t),n.properties.push(a)}return this.finishNode(n,e?`ObjectPattern`:`ObjectExpression`)},X.parseProperty=function(e,t){var n=this.startNode(),r,i,a,o;if(this.options.ecmaVersion>=9&&this.eat(J.ellipsis))return e?(n.argument=this.parseIdent(!1),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.finishNode(n,`RestElement`)):(n.argument=this.parseMaybeAssign(!1,t),this.type===J.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(n,`SpreadElement`));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(e||t)&&(a=this.start,o=this.startLoc),e||(r=this.eat(J.star)));var s=this.containsEsc;return this.parsePropertyName(n),!e&&!s&&this.options.ecmaVersion>=8&&!r&&this.isAsyncProp(n)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(J.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,e,r,i,a,o,t,s),this.finishNode(n,`Property`)},X.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var n=e.kind===`get`?0:1;if(e.value.params.length!==n){var r=e.value.start;e.kind===`get`?this.raiseRecoverable(r,`getter should have no params`):this.raiseRecoverable(r,`setter should have exactly one param`)}else e.kind===`set`&&e.value.params[0].type===`RestElement`&&this.raiseRecoverable(e.value.params[0].start,`Setter cannot use rest params`)},X.parsePropertyValue=function(e,t,n,r,i,a,o,s){(n||r)&&this.type===J.colon&&this.unexpected(),this.eat(J.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind=`init`):this.options.ecmaVersion>=6&&this.type===J.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(n,r),e.kind=`init`):!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type===`Identifier`&&(e.key.name===`get`||e.key.name===`set`)&&this.type!==J.comma&&this.type!==J.braceR&&this.type!==J.eq?((n||r)&&this.unexpected(),this.parseGetterSetter(e)):this.options.ecmaVersion>=6&&!e.computed&&e.key.type===`Identifier`?((n||r)&&this.unexpected(),this.checkUnreserved(e.key),e.key.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key)):this.type===J.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind=`init`,e.shorthand=!0):this.unexpected()},X.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(J.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(J.bracketR),e.key;e.computed=!1}return e.key=this.type===J.num||this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`)},X.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},X.parseMethod=function(e,t,n){var r=this.startNode(),i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(FC(t,r.generator)|kC|(n?AC:0)),this.expect(J.parenL),r.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(r,`FunctionExpression`)},X.parseArrowExpression=function(e,t,n,r){var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(FC(n,!1)|DC),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!n),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,`ArrowFunctionExpression`)},X.parseFunctionBody=function(e,t,n,r){var i=t&&this.type!==J.braceL,a=this.strict,o=!1;if(i)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!a||s)&&(o=this.strictDirective(this.end),o&&s&&this.raiseRecoverable(e.start,`Illegal 'use strict' directive in function with non-simple parameter list`));var c=this.labels;this.labels=[],o&&(this.strict=!0),this.checkParams(e,!a&&!o&&!t&&!n&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,VC),e.body=this.parseBlock(!1,void 0,o&&!a),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()},X.isSimpleParamList=function(e){for(var t=0,n=e;t<n.length;t+=1)if(n[t].type!==`Identifier`)return!1;return!0},X.checkParams=function(e,t){for(var n=Object.create(null),r=0,i=e.params;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,LC,t?null:n)}},X.parseExprList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);){if(a)a=!1;else if(this.expect(J.comma),t&&this.afterTrailingComma(e))break;var o=void 0;n&&this.type===J.comma?o=null:this.type===J.ellipsis?(o=this.parseSpread(r),r&&this.type===J.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):o=this.parseMaybeAssign(!1,r),i.push(o)}return i},X.checkUnreserved=function(e){var t=e.start,n=e.end,r=e.name;this.inGenerator&&r===`yield`&&this.raiseRecoverable(t,`Cannot use 'yield' as identifier inside a generator`),this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use 'await' as identifier inside an async function`),!(this.currentThisScope().flags&PC)&&r===`arguments`&&this.raiseRecoverable(t,`Cannot use 'arguments' in class field initializer`),this.inClassStaticBlock&&(r===`arguments`||r===`await`)&&this.raise(t,`Cannot use `+r+` in class static initialization block`),this.keywords.test(r)&&this.raise(t,`Unexpected keyword '`+r+`'`),!(this.options.ecmaVersion<6&&this.input.slice(t,n).indexOf(`\\`)!==-1)&&(this.strict?this.reservedWordsStrict:this.reservedWords).test(r)&&(!this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use keyword 'await' outside an async function`),this.raiseRecoverable(t,`The keyword '`+r+`' is reserved`))},X.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,`Identifier`),e||(this.checkUnreserved(t),t.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=t.start)),t},X.parseIdentNode=function(){var e=this.startNode();return this.type===J.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,(e.name===`class`||e.name===`function`)&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=J.name):this.unexpected(),e},X.parsePrivateIdent=function(){var e=this.startNode();return this.type===J.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,`PrivateIdentifier`),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(e.start,`Private field '#`+e.name+`' must be declared in an enclosing class`):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e},X.parseYield=function(e){this.yieldPos||=this.start;var t=this.startNode();return this.next(),this.type===J.semi||this.canInsertSemicolon()||this.type!==J.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(J.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,`YieldExpression`)},X.parseAwait=function(e){this.awaitPos||=this.start;var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,`AwaitExpression`)};var cw=HC.prototype;cw.raise=function(e,t){var n=vC(this.input,e);t+=` (`+n.line+`:`+n.column+`)`,this.sourceFile&&(t+=` in `+this.sourceFile);var r=SyntaxError(t);throw r.pos=e,r.loc=n,r.raisedAt=this.pos,r},cw.raiseRecoverable=cw.raise,cw.curPosition=function(){if(this.options.locations)return new gC(this.curLine,this.pos-this.lineStart)};var lw=HC.prototype,uw=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};lw.enterScope=function(e){this.scopeStack.push(new uw(e))},lw.exitScope=function(){this.scopeStack.pop()},lw.treatFunctionsAsVarInScope=function(e){return e.flags&wC||!this.inModule&&e.flags&CC},lw.declareName=function(e,t,n){var r=!1;if(t===RC){var i=this.currentScope();r=i.lexical.indexOf(e)>-1||i.functions.indexOf(e)>-1||i.var.indexOf(e)>-1,i.lexical.push(e),this.inModule&&i.flags&CC&&delete this.undefinedExports[e]}else if(t===BC)this.currentScope().lexical.push(e);else if(t===zC){var a=this.currentScope();r=this.treatFunctionsAsVar?a.lexical.indexOf(e)>-1:a.lexical.indexOf(e)>-1||a.var.indexOf(e)>-1,a.functions.push(e)}else for(var o=this.scopeStack.length-1;o>=0;--o){var s=this.scopeStack[o];if(s.lexical.indexOf(e)>-1&&!(s.flags&OC&&s.lexical[0]===e)||!this.treatFunctionsAsVarInScope(s)&&s.functions.indexOf(e)>-1){r=!0;break}if(s.var.push(e),this.inModule&&s.flags&CC&&delete this.undefinedExports[e],s.flags&PC)break}r&&this.raiseRecoverable(n,`Identifier '`+e+`' has already been declared`)},lw.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)},lw.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},lw.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(PC|MC|jC))return t}},lw.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(PC|MC|jC)&&!(t.flags&DC))return t}};var dw=function(e,t,n){this.type=``,this.start=t,this.end=0,e.options.locations&&(this.loc=new _C(e,n)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},fw=HC.prototype;fw.startNode=function(){return new dw(this,this.start,this.startLoc)},fw.startNodeAt=function(e,t){return new dw(this,e,t)};function pw(e,t,n,r){return e.type=t,e.end=n,this.options.locations&&(e.loc.end=r),this.options.ranges&&(e.range[1]=n),e}fw.finishNode=function(e,t){return pw.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},fw.finishNodeAt=function(e,t,n,r){return pw.call(this,e,t,n,r)},fw.copyNode=function(e){var t=new dw(this,e.start,this.startLoc);for(var n in e)t[n]=e[n];return t};var mw=`Berf Beria_Erfe Gara Garay Gukh Gurung_Khema Hrkt Katakana_Or_Hiragana Kawi Kirat_Rai Krai Nag_Mundari Nagm Ol_Onal Onao Sidetic Sidt Sunu Sunuwar Tai_Yo Tayo Todhri Todr Tolong_Siki Tols Tulu_Tigalari Tutg Unknown Zzzz`,hw=`ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS`,gw=hw+` Extended_Pictographic`,_w=gw,vw=_w+` EBase EComp EMod EPres ExtPict`,yw=vw,bw={9:hw,10:gw,11:_w,12:vw,13:yw,14:yw},xw={9:``,10:``,11:``,12:``,13:``,14:`Basic_Emoji Emoji_Keycap_Sequence RGI_Emoji_Modifier_Sequence RGI_Emoji_Flag_Sequence RGI_Emoji_Tag_Sequence RGI_Emoji_ZWJ_Sequence RGI_Emoji`},Sw=`Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu`,Cw=`Adlam Adlm Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb`,ww=Cw+` Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd`,Tw=ww+` Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho`,Ew=Tw+` Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi`,Dw=Ew+` Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith`,Ow={9:Cw,10:ww,11:Tw,12:Ew,13:Dw,14:Dw+` `+mw},kw={};function Aw(e){var t=kw[e]={binary:pC(bw[e]+` `+Sw),binaryOfStrings:pC(xw[e]),nonBinary:{General_Category:pC(Sw),Script:pC(Ow[e])}};t.nonBinary.Script_Extensions=t.nonBinary.Script,t.nonBinary.gc=t.nonBinary.General_Category,t.nonBinary.sc=t.nonBinary.Script,t.nonBinary.scx=t.nonBinary.Script_Extensions}for(var jw=0,Mw=[9,10,11,12,13,14];jw<Mw.length;jw+=1){var Nw=Mw[jw];Aw(Nw)}var Z=HC.prototype,Pw=function(e,t){this.parent=e,this.base=t||this};Pw.prototype.separatedFrom=function(e){for(var t=this;t;t=t.parent)for(var n=e;n;n=n.parent)if(t.base===n.base&&t!==n)return!0;return!1},Pw.prototype.sibling=function(){return new Pw(this.parent,this.base)};var Fw=function(e){this.parser=e,this.validFlags=`gim`+(e.options.ecmaVersion>=6?`uy`:``)+(e.options.ecmaVersion>=9?`s`:``)+(e.options.ecmaVersion>=13?`d`:``)+(e.options.ecmaVersion>=15?`v`:``),this.unicodeProperties=kw[e.options.ecmaVersion>=14?14:e.options.ecmaVersion],this.source=``,this.flags=``,this.start=0,this.switchU=!1,this.switchV=!1,this.switchN=!1,this.pos=0,this.lastIntValue=0,this.lastStringValue=``,this.lastAssertionIsQuantifiable=!1,this.numCapturingParens=0,this.maxBackReference=0,this.groupNames=Object.create(null),this.backReferenceNames=[],this.branchID=null};Fw.prototype.reset=function(e,t,n){var r=n.indexOf(`v`)!==-1,i=n.indexOf(`u`)!==-1;this.start=e|0,this.source=t+``,this.flags=n,r&&this.parser.options.ecmaVersion>=15?(this.switchU=!0,this.switchV=!0,this.switchN=!0):(this.switchU=i&&this.parser.options.ecmaVersion>=6,this.switchV=!1,this.switchN=i&&this.parser.options.ecmaVersion>=9)},Fw.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,`Invalid regular expression: /`+this.source+`/: `+e)},Fw.prototype.at=function(e,t){t===void 0&&(t=!1);var n=this.source,r=n.length;if(e>=r)return-1;var i=n.charCodeAt(e);if(!(t||this.switchU)||i<=55295||i>=57344||e+1>=r)return i;var a=n.charCodeAt(e+1);return a>=56320&&a<=57343?(i<<10)+a-56613888:i},Fw.prototype.nextIndex=function(e,t){t===void 0&&(t=!1);var n=this.source,r=n.length;if(e>=r)return r;var i=n.charCodeAt(e),a;return!(t||this.switchU)||i<=55295||i>=57344||e+1>=r||(a=n.charCodeAt(e+1))<56320||a>57343?e+1:e+2},Fw.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)},Fw.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Fw.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Fw.prototype.eat=function(e,t){return t===void 0&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Fw.prototype.eatChars=function(e,t){t===void 0&&(t=!1);for(var n=this.pos,r=0,i=e;r<i.length;r+=1){var a=i[r],o=this.at(n,t);if(o===-1||o!==a)return!1;n=this.nextIndex(n,t)}return this.pos=n,!0},Z.validateRegExpFlags=function(e){for(var t=e.validFlags,n=e.flags,r=!1,i=!1,a=0;a<n.length;a++){var o=n.charAt(a);t.indexOf(o)===-1&&this.raise(e.start,`Invalid regular expression flag`),n.indexOf(o,a+1)>-1&&this.raise(e.start,`Duplicate regular expression flag`),o===`u`&&(r=!0),o===`v`&&(i=!0)}this.options.ecmaVersion>=15&&r&&i&&this.raise(e.start,`Invalid regular expression flag`)};function Iw(e){for(var t in e)return!0;return!1}Z.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&Iw(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Z.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue=``,e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise(`Unmatched ')'`),(e.eat(93)||e.eat(125))&&e.raise(`Lone quantifier brackets`)),e.maxBackReference>e.numCapturingParens&&e.raise(`Invalid escape`);for(var t=0,n=e.backReferenceNames;t<n.length;t+=1){var r=n[t];e.groupNames[r]||e.raise(`Invalid named capture referenced`)}},Z.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new Pw(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise(`Nothing to repeat`),e.eat(123)&&e.raise(`Lone quantifier brackets`)},Z.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},Z.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise(`Invalid quantifier`),!0):(e.switchU?this.regexp_eatAtom(e):this.regexp_eatExtendedAtom(e))?(this.regexp_eatQuantifier(e),!0):!1},Z.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var n=!1;if(this.options.ecmaVersion>=9&&(n=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise(`Unterminated group`),e.lastAssertionIsQuantifiable=!n,!0}return e.pos=t,!1},Z.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1},Z.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Z.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var r=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return i!==-1&&i<r&&!t&&e.raise(`numbers out of order in {} quantifier`),!0;e.switchU&&!t&&e.raise(`Incomplete quantifier`),e.pos=n}return!1},Z.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)},Z.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},Z.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var n=this.regexp_eatModifiers(e),r=e.eat(45);if(n||r){for(var i=0;i<n.length;i++){var a=n.charAt(i);n.indexOf(a,i+1)>-1&&e.raise(`Duplicate regular expression modifiers`)}if(r){var o=this.regexp_eatModifiers(e);!n&&!o&&e.current()===58&&e.raise(`Invalid regular expression modifiers`);for(var s=0;s<o.length;s++){var c=o.charAt(s);(o.indexOf(c,s+1)>-1||n.indexOf(c)>-1)&&e.raise(`Duplicate regular expression modifiers`)}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise(`Unterminated group`)}}e.pos=t}return!1},Z.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):e.current()===63&&e.raise(`Invalid group`),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise(`Unterminated group`)}return!1},Z.regexp_eatModifiers=function(e){for(var t=``,n=0;(n=e.current())!==-1&&Lw(n);)t+=mC(n),e.advance();return t};function Lw(e){return e===105||e===109||e===115}Z.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Z.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise(`Nothing to repeat`),!1},Z.regexp_eatSyntaxCharacter=function(e){var t=e.current();return Rw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Rw(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Z.regexp_eatPatternCharacters=function(e){for(var t=e.pos,n=0;(n=e.current())!==-1&&!Rw(n);)e.advance();return e.pos!==t},Z.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124&&(e.advance(),!0)},Z.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise(`Invalid group`);var t=this.options.ecmaVersion>=16,n=e.groupNames[e.lastStringValue];if(n){if(t)for(var r=0,i=n;r<i.length;r+=1)i[r].separatedFrom(e.branchID)||e.raise(`Duplicate capture group name`);else e.raise(`Duplicate capture group name`)}t?(n||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}},Z.regexp_eatGroupName=function(e){if(e.lastStringValue=``,e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise(`Invalid capture group name`)}return!1},Z.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue=``,this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=mC(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=mC(e.lastIntValue);return!0}return!1},Z.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),zw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function zw(e){return YS(e,!0)||e===36||e===95}Z.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),Bw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function Bw(e){return XS(e,!0)||e===36||e===95||e===8204||e===8205}Z.regexp_eatAtomEscape=function(e){return this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)?!0:(e.switchU&&(e.current()===99&&e.raise(`Invalid unicode escape`),e.raise(`Invalid escape`)),!1)},Z.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU)return n>e.maxBackReference&&(e.maxBackReference=n),!0;if(n<=e.numCapturingParens)return!0;e.pos=t}return!1},Z.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise(`Invalid named reference`)}return!1},Z.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Z.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Z.regexp_eatZero=function(e){return e.current()===48&&!Qw(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Z.regexp_eatControlEscape=function(e){var t=e.current();return t===116?(e.lastIntValue=9,e.advance(),!0):t===110?(e.lastIntValue=10,e.advance(),!0):t===118?(e.lastIntValue=11,e.advance(),!0):t===102?(e.lastIntValue=12,e.advance(),!0):t===114&&(e.lastIntValue=13,e.advance(),!0)},Z.regexp_eatControlLetter=function(e){var t=e.current();return Vw(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function Vw(e){return e>=65&&e<=90||e>=97&&e<=122}Z.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){t===void 0&&(t=!1);var n=e.pos,r=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(r&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(i-55296)*1024+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(r&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&Hw(e.lastIntValue))return!0;r&&e.raise(`Invalid unicode escape`),e.pos=n}return!1};function Hw(e){return e>=0&&e<=1114111}Z.regexp_eatIdentityEscape=function(e){if(e.switchU)return this.regexp_eatSyntaxCharacter(e)?!0:e.eat(47)?(e.lastIntValue=47,!0):!1;var t=e.current();return t!==99&&(!e.switchN||t!==107)&&(e.lastIntValue=t,e.advance(),!0)},Z.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1};var Uw=0,Ww=1,Gw=2;Z.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(Kw(t))return e.lastIntValue=-1,e.advance(),Ww;var n=!1;if(e.switchU&&this.options.ecmaVersion>=9&&((n=t===80)||t===112)){e.lastIntValue=-1,e.advance();var r;if(e.eat(123)&&(r=this.regexp_eatUnicodePropertyValueExpression(e))&&e.eat(125))return n&&r===Gw&&e.raise(`Invalid property name`),r;e.raise(`Invalid property name`)}return Uw};function Kw(e){return e===100||e===68||e===115||e===83||e===119||e===87}Z.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,n,r),Ww}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return Uw},Z.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){uC(e.unicodeProperties.nonBinary,t)||e.raise(`Invalid property name`),e.unicodeProperties.nonBinary[t].test(n)||e.raise(`Invalid property value`)},Z.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return Ww;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return Gw;e.raise(`Invalid property name`)},Z.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue=``;qw(t=e.current());)e.lastStringValue+=mC(t),e.advance();return e.lastStringValue!==``};function qw(e){return Vw(e)||e===95}Z.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue=``;Jw(t=e.current());)e.lastStringValue+=mC(t),e.advance();return e.lastStringValue!==``};function Jw(e){return qw(e)||Qw(e)}Z.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Z.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),n=this.regexp_classContents(e);return e.eat(93)||e.raise(`Unterminated character class`),t&&n===Gw&&e.raise(`Negated character class may contain strings`),!0}return!1},Z.regexp_classContents=function(e){return e.current()===93?Ww:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),Ww)},Z.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;e.switchU&&(t===-1||n===-1)&&e.raise(`Invalid character class`),t!==-1&&n!==-1&&t>n&&e.raise(`Range out of order in character class`)}}},Z.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var n=e.current();(n===99||tT(n))&&e.raise(`Invalid class escape`),e.raise(`Invalid escape`)}e.pos=t}var r=e.current();return r!==93&&(e.lastIntValue=r,e.advance(),!0)},Z.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Z.regexp_classSetExpression=function(e){var t=Ww,n;if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e)){n===Gw&&(t=Gw);for(var r=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(n=this.regexp_eatClassSetOperand(e))){n!==Gw&&(t=Ww);continue}e.raise(`Invalid character in character class`)}if(r!==e.pos)return t;for(;e.eatChars([45,45]);)this.regexp_eatClassSetOperand(e)||e.raise(`Invalid character in character class`);if(r!==e.pos)return t}else e.raise(`Invalid character in character class`)}for(;;)if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e),!n)return t;n===Gw&&(t=Gw)}},Z.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return n!==-1&&r!==-1&&n>r&&e.raise(`Range out of order in character class`),!0}e.pos=t}return!1},Z.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?Ww:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Z.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var n=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return n&&r===Gw&&e.raise(`Negated character class may contain strings`),r;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null},Z.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var n=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return n}else e.raise(`Invalid escape`);e.pos=t}return null},Z.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===Gw&&(t=Gw);return t},Z.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?Ww:Gw},Z.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e)?!0:e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1);var n=e.current();return n<0||n===e.lookahead()&&Yw(n)||Xw(n)?!1:(e.advance(),e.lastIntValue=n,!0)};function Yw(e){return e===33||e>=35&&e<=38||e>=42&&e<=44||e===46||e>=58&&e<=64||e===94||e===96||e===126}function Xw(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}Z.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return Zw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Zw(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}Z.regexp_eatClassControlLetter=function(e){var t=e.current();return Qw(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1},Z.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise(`Invalid escape`),e.pos=t}return!1},Z.regexp_eatDecimalDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;Qw(n=e.current());)e.lastIntValue=10*e.lastIntValue+(n-48),e.advance();return e.pos!==t};function Qw(e){return e>=48&&e<=57}Z.regexp_eatHexDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;$w(n=e.current());)e.lastIntValue=16*e.lastIntValue+eT(n),e.advance();return e.pos!==t};function $w(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function eT(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}Z.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;e.lastIntValue=t<=3&&this.regexp_eatOctalDigit(e)?t*64+n*8+e.lastIntValue:t*8+n}else e.lastIntValue=t;return!0}return!1},Z.regexp_eatOctalDigit=function(e){var t=e.current();return tT(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function tT(e){return e>=48&&e<=55}Z.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var r=0;r<t;++r){var i=e.current();if(!$w(i))return e.pos=n,!1;e.lastIntValue=16*e.lastIntValue+eT(i),e.advance()}return!0};var nT=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new _C(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},Q=HC.prototype;Q.next=function(e){!e&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword `+this.type.keyword),this.options.onToken&&this.options.onToken(new nT(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},Q.getToken=function(){return this.next(),new nT(this)},typeof Symbol<`u`&&(Q[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===J.eof,value:t}}}}),Q.nextToken=function(){var e=this.curContext();if((!e||!e.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(J.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())},Q.readToken=function(e){return YS(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)},Q.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var n=this.input.charCodeAt(e+1);return n<=56319||n>=57344?t:(t<<10)+n-56613888},Q.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},Q.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,n=this.input.indexOf(`*/`,this.pos+=2);if(n===-1&&this.raise(this.pos-2,`Unterminated comment`),this.pos=n+2,this.options.locations)for(var r=void 0,i=t;(r=iC(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,n),t,this.pos,e,this.curPosition())},Q.skipLineComment=function(e){for(var t=this.pos,n=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!rC(r);)r=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,n,this.curPosition())},Q.skipSpace=function(){loop:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break loop}break;default:if(e>8&&e<14||e>=5760&&aC.test(String.fromCharCode(e)))++this.pos;else break loop}}},Q.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},Q.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&e===46&&t===46?(this.pos+=3,this.finishToken(J.ellipsis)):(++this.pos,this.finishToken(J.dot))},Q.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(J.assign,2):this.finishOp(J.slash,1)},Q.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=e===42?J.star:J.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++n,r=J.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(J.assign,n+1):this.finishOp(r,n)},Q.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(e===124?J.logicalOR:J.logicalAND,2):t===61?this.finishOp(J.assign,2):this.finishOp(e===124?J.bitwiseOR:J.bitwiseAND,1)},Q.readToken_caret=function(){return this.input.charCodeAt(this.pos+1)===61?this.finishOp(J.assign,2):this.finishOp(J.bitwiseXOR,1)},Q.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||tC.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(J.incDec,2):t===61?this.finishOp(J.assign,2):this.finishOp(J.plusMin,1)},Q.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+n)===61?this.finishOp(J.assign,n+1):this.finishOp(J.bitShift,n)):t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(t===61&&(n=2),this.finishOp(J.relational,n))},Q.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(J.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(J.arrow)):this.finishOp(e===61?J.eq:J.prefix,1)},Q.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57)return this.finishOp(J.questionDot,2)}if(t===63)return e>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(J.coalesce,2)}return this.finishOp(J.question,1)},Q.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),YS(t,!0)||t===92))return this.finishToken(J.privateId,this.readWord1());this.raise(this.pos,`Unexpected character '`+mC(t)+`'`)},Q.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(J.parenL);case 41:return++this.pos,this.finishToken(J.parenR);case 59:return++this.pos,this.finishToken(J.semi);case 44:return++this.pos,this.finishToken(J.comma);case 91:return++this.pos,this.finishToken(J.bracketL);case 93:return++this.pos,this.finishToken(J.bracketR);case 123:return++this.pos,this.finishToken(J.braceL);case 125:return++this.pos,this.finishToken(J.braceR);case 58:return++this.pos,this.finishToken(J.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(J.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(t===111||t===79)return this.readRadixNumber(8);if(t===98||t===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(J.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,`Unexpected character '`+mC(e)+`'`)},Q.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)},Q.readRegexp=function(){for(var e,t,n=this.pos;;){this.pos>=this.input.length&&this.raise(n,`Unterminated regular expression`);var r=this.input.charAt(this.pos);if(tC.test(r)&&this.raise(n,`Unterminated regular expression`),e)e=!1;else{if(r===`[`)t=!0;else if(r===`]`&&t)t=!1;else if(r===`/`&&!t)break;e=r===`\\`}++this.pos}var i=this.input.slice(n,this.pos);++this.pos;var a=this.pos,o=this.readWord1();this.containsEsc&&this.unexpected(a);var s=this.regexpState||=new Fw(this);s.reset(n,i,o),this.validateRegExpFlags(s),this.validateRegExpPattern(s);var c=null;try{c=new RegExp(i,o)}catch{}return this.finishToken(J.regexp,{pattern:i,flags:o,value:c})},Q.readInt=function(e,t,n){for(var r=this.options.ecmaVersion>=12&&t===void 0,i=n&&this.input.charCodeAt(this.pos)===48,a=this.pos,o=0,s=0,c=0,l=t??1/0;c<l;++c,++this.pos){var u=this.input.charCodeAt(this.pos),d=void 0;if(r&&u===95){i&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed in legacy octal numeric literals`),s===95&&this.raiseRecoverable(this.pos,`Numeric separator must be exactly one underscore`),c===0&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed at the first of digits`),s=u;continue}if(d=u>=97?u-97+10:u>=65?u-65+10:u>=48&&u<=57?u-48:1/0,d>=e)break;s=u,o=o*e+d}return r&&s===95&&this.raiseRecoverable(this.pos-1,`Numeric separator is not allowed at the last of digits`),this.pos===a||t!=null&&this.pos-a!==t?null:o};function rT(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,``))}function iT(e){return typeof BigInt==`function`?BigInt(e.replace(/_/g,``)):null}Q.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);return n??this.raise(this.start+2,`Expected number in radix `+e),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(n=iT(this.input.slice(t,this.pos)),++this.pos):YS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,n)},Q.readNumber=function(e){var t=this.pos;!e&&this.readInt(10,void 0,!0)===null&&this.raise(t,`Invalid number`);var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;n&&this.strict&&this.raise(t,`Invalid number`);var r=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&r===110){var i=iT(this.input.slice(t,this.pos));return++this.pos,YS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,i)}n&&/[89]/.test(this.input.slice(t,this.pos))&&(n=!1),r===46&&!n&&(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),(r===69||r===101)&&!n&&(r=this.input.charCodeAt(++this.pos),(r===43||r===45)&&++this.pos,this.readInt(10)===null&&this.raise(t,`Invalid number`)),YS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`);var a=rT(this.input.slice(t,this.pos),n);return this.finishToken(J.num,a)},Q.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){this.options.ecmaVersion<6&&this.unexpected();var n=++this.pos;t=this.readHexChar(this.input.indexOf(`}`,this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(n,`Code point out of bounds`)}else t=this.readHexChar(4);return t},Q.readString=function(e){for(var t=``,n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated string constant`);var r=this.input.charCodeAt(this.pos);if(r===e)break;r===92?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(!1),n=this.pos):r===8232||r===8233?(this.options.ecmaVersion<10&&this.raise(this.start,`Unterminated string constant`),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(rC(r)&&this.raise(this.start,`Unterminated string constant`),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(J.string,t)};var aT={};Q.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===aT)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},Q.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw aT;this.raise(e,t)},Q.readTmplToken=function(){for(var e=``,t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated template`);var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===J.template||this.type===J.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(J.dollarBraceL)):(++this.pos,this.finishToken(J.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(J.template,e));if(n===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(rC(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=`
|
|
15
15
|
`;break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},Q.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case`\\`:++this.pos;break;case`$`:if(this.input[this.pos+1]!==`{`)break;case"`":return this.finishToken(J.invalidTemplate,this.input.slice(this.start,this.pos));case`\r`:this.input[this.pos+1]===`
|
|
16
16
|
`&&++this.pos;case`
|
|
17
17
|
`:case`\u2028`:case`\u2029`:++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,`Unterminated template`)},Q.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
|
|
18
|
-
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return pC(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),(r!==`0`||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return nC(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},Q.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},Q.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(YS(i,r))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?JS:YS)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=pC(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},Q.readWord=function(){var e=this.readWord1(),t=J.name;return this.keywords.test(e)&&(t=$S[e]),this.finishToken(t,e)},VC.acorn={Parser:VC,version:`8.18.0`,defaultOptions:vC,Position:hC,SourceLocation:gC,getLineInfo:_C,Node:uw,TokenType:K,tokTypes:J,keywordTypes:$S,TokContext:tw,tokContexts:nw,isIdentifierChar:YS,isIdentifierStart:JS,Token:tT,isNewLine:nC,lineBreak:eC,lineBreakG:tC,nonASCIIwhitespace:iC};function aT(e,t){return VC.parse(e,t)}_(()=>hn(`ok`,[ln({ok:yr(!0),value:xt()}),ln({ok:yr(!1),error:ln({kind:yr(`guest_threw`),name:w().max(80),message:w().max(512),transportMessage:w().max(512).optional()})})]));var oT=_(()=>w().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),sT=oT.refine(e=>{if(e===`env`)return!1;try{return aT(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);_(()=>si(sT,Er(oT).min(1))),_(()=>si(sT,Er(w().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var cT=L([`read`,`write`]),lT=cm,uT=P({access:A(cT),confirm:A(lT)}),dT=L([`none`,`read`,`write`]),fT=D(uT),pT=D(dT);function mT(e){let t=fT({access:e.access,confirm:e.confirm});if(Ae(t))throw new G(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function hT(e,t){let n=`${t.module}.${t.operation}`;switch(e){case`not-granted`:return`${n} is not granted to this Agent.`;case`read-only`:return`${n} changes something, and this Agent has read-only access to ${t.module}.`;case`confirmation-unavailable`:return`${n} needs a person's approval, and no one can be asked here.`;case`declined`:return`${n} was not approved.`}}function gT(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:hT(e,t)})}function _T(e,t,n){let r=e.sessionGrants?.(t),i=r!==void 0&&Object.hasOwn(r,n)?r:e.grants;if(i===void 0||!Object.hasOwn(i,n))return e.required?.includes(n)===!0?`none`:e.defaultGrant??`write`;let a=pT(i[n]);return Wt(a)?a.success:`none`}async function vT(e,t,n,r,i){let a=await yT(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function yT(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=bT(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?gT(`confirmation-unavailable`,n):await e.confirm({module:n.module,operation:n.operation,access:n.access,sessionId:t.sessionId,input:r},i)?(await e.beforeCall?.(i),i.throwIfAborted(),bT(e,t,n)):gT(`declined`,n)}function bT(e,t,n){let r=_T(e,t,n.module);if(r===`none`)return gT(`not-granted`,n);if(r===`read`&&n.access!==`read`)return gT(`read-only`,n)}function xT(e,t,n){let r={module:e.module,operation:e.descriptor.name,...mT(e)};return{...e,prepare:i=>pn({try:e=>vT(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(T(t=>t===void 0?e.prepare(i):x({execute:()=>Gv({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var ST=Cs();async function CT(e){let t=await Kn(e);if(ca(t))return{value:t.value};let n=Yi(t.cause);if(Ae(n))throw Ji(t.cause);return{issues:ST(n.success.issue).issues}}function wT(e){let t=Xh(e),n=Bp(t)[`~standard`].jsonSchema,r=Hp(t),i=qp(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>CT(r(e)),encode:e=>CT(i(e))})}function TT(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function ET(e){return em(e)?wT(e):TT(e)}var DT=Symbol(`mycelium.operation`),OT=Symbol(`mycelium.module`),kT=new WeakMap,AT=new WeakMap;function jT(e){let t=Object.freeze({[DT]:!0}),n=ET(e.input),r=e.output===void 0?void 0:ET(e.output),i={replay:e.replay??`unsafe`,...mT(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new cS(a.issues);let o=await e.execute(a.value,i);if(r===void 0)return o;let s=await r.encode(o);if(s.issues!==void 0)throw new _S({reason:`Capability output failed its declared schema`,rawCause:new lS(s.issues)});return s.value}};e.description!==void 0&&(i.description=e.description),r!==void 0&&(i.output=r.description);let a=Object.freeze(i);return kT.set(t,a),t}function MT(e){let t=Er(oT).safeParse(e.namespace??[]);if(!t.success)throw new G(`Invalid module namespace`);let n=Object.freeze({[OT]:!0}),r={id:e.id,grantKey:e.id,name:e.name??e.id,namespace:Object.freeze(t.data),operations:Object.freeze({...e.operations})};e.description!==void 0&&(r.description=e.description);let i=Object.freeze(r);return AT.set(n,i),n}function NT(e){return AT.has(e)}function PT(e){return kT.get(e)}function FT(e){return AT.get(e)}function IT(e,t,n){let r=FT(e);if(r===void 0)throw new G(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(NT(a)){let n=FT(a);if(n===void 0)throw new G(`Unknown child module registration`);i[e]=IT(a,t,[r,...n.namespace].join(`.`));continue}let o=PT(a);if(o===void 0)throw new G(`Unknown operation registration: ${e}`);let s=Object.freeze({[DT]:!0});kT.set(s,Object.freeze({...o,invoke:async(e,n)=>{let i=await t({operation:r,context:n});return i.kind===`refuse`?i.value:await o.invoke(e,n)}})),i[e]=s}return LT(MT(r.description===void 0?{id:r.id,name:r.name,namespace:r.namespace,operations:i}:{id:r.id,name:r.name,namespace:r.namespace,description:r.description,operations:i}),r.grantKey)}function LT(e,t){let n=FT(e);if(n===void 0)throw new G(`Unknown module registration`);let r=Object.freeze({[OT]:!0});return AT.set(r,Object.freeze({...n,grantKey:t})),r}function RT(e,t){if(t.length===0||t.length>160)throw new G(`Grant key must be non-empty and bounded`);return LT(e,t)}function zT(e,t){return IT(e,t,``)}function BT(e,t){return e<t?-1:+(e>t)}function VT(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var HT=160;function UT(e){if(e.length===0||e.length>HT)throw new G(`Module id must be non-empty and bounded`)}function WT(e){if(!e.split(`.`).every(e=>oT.safeParse(e).success))throw new G(`Operation key must be a path segment or a dotted relative path`)}function GT(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function KT(e){let t=GT(e);return sT.safeParse(t).success?t:`module_${t}`}function qT(e,t){let n=new Set([`forage`,`env`]),r=new Map;for(let i of e){let e=t===`logical`?i.namespace:[],a=t===`logical`?GT(i.name):KT(i.name),o=t=>[...e,t].join(`.`),s=a,c=2;for(;n.has(o(s));)s=`${a}_${String(c)}`,c+=1;n.add(o(s)),r.set(i.id,s)}return r}var JT=14695981039346656037n,YT=1099511628211n,XT=18446744073709551615n;function ZT(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*YT&XT,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*YT&XT,n=(n^BigInt(r>>>8&255))*YT&XT}return n}function QT(e,t,n){let r=ZT(JT,e),i=[...t.entries()].sort(([e],[t])=>BT(e,t));for(let[e,t]of i)r=ZT(r,e),r=ZT(r,t);let a=[...n].sort((e,t)=>BT(e.id,t.id));for(let e of a)r=ZT(r,e.id),r=ZT(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function $T(){return[tS,eS,nS]}function eE(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(WT(t),NT(o)){let s=FT(o);if(s===void 0)throw new G(`Unknown child module registration`);return eE(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=PT(o);if(s===void 0)throw new G(`Unknown operation registration: ${[...r,t].join(`.`)}`);return[Object.freeze({grantKey:e,path:[...r,t].join(`.`),namespace:n,name:[...a,t].join(`.`),moduleDescription:i,operation:s})]})}function tE(e,t=[]){let n=e.map(e=>{let t=FT(e);if(t===void 0)throw new G(`Unknown module registration`);return UT(t.id),t}).sort((e,t)=>BT(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new G(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=qT(n,`transport`),a=qT(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new G(`Missing logical alias: ${e.id}`);return[t,Object.freeze([...e.namespace,n])]}))),s=n.flatMap(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new G(`Missing namespace path: ${e.id}`);return eE(e.grantKey,e,t,n,e.description)}).sort((e,t)=>BT(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new G(`Duplicate operation path`);for(let e of $T()){if(c.has(e.path))throw new G(`Reserved intrinsic path: ${e.path}`);c.add(e.path)}for(let e of c){let t=e.split(`.`);for(let n=1;n<t.length;n+=1)if(c.has(t.slice(0,n).join(`.`)))throw new G(`Operation conflicts with namespace: ${e}`)}let l;try{l=Xx({revision:`prepared-content-stamp`,operations:[...s.map(({path:e,moduleDescription:t,operation:n})=>{let r={path:e,input:n.input};return n.description!==void 0&&(r.description=n.description),n.output!==void 0&&(r.output=n.output),t!==void 0&&(r.instructions=t),r}),...$T()]})}catch(e){throw new G(VT(e))}let u=QT(l.stamp(),i,t),d=Object.freeze({revision:u,search:l.search,describe:l.describe,list:l.list,stamp:l.stamp}),f=Object.freeze(Object.fromEntries([...i.entries()].map(([e,t])=>[t,e])));return Object.freeze({revision:u,catalog:d,operations:Object.freeze(s),moduleAliases:f,namespacePaths:o})}function nE(){return null}var rE=bn(),iE=_(()=>Qr([wn(),w(),pr(),Mn()])),aE=_(()=>si(w(),xt())),oE=_(()=>FS.extend({timeoutMs:Mn().int().min(1).max(9e5).optional(),abortGraceMs:Mn().int().min(1).max(3e4).optional()}).optional()),sE=64,cE=262144,lE=new TextEncoder,uE=e=>{e(x(void 0))};function dE(e){let t=oE.safeParse(e);if(!t.success)throw new G(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...IS({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function fE(e){return b(function*(){let t=yield*A_(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=$n(t=>e===0?(t(x(void 0)),y(()=>void 0)):(n.add(t),y(()=>n.delete(t))));return Object.freeze({start:r=>ne(i=>y(()=>{e+=1}).pipe(g(re(i(t.withPermits(1)(r)).pipe(rr(y(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(uE)}}))))))),awaitIdle:r})}})})}function pE(e,t=0){if(t>sE)throw Error(`JSON value exceeds the nesting bound`);let n=iE.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>pE(e,t+1));let r=aE.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,pE(n,t+1)]))}function mE(e){return rE.parse(pE(e))}function hE(e){let t=JSON.stringify(mE(e)),n=lE.encode(t).byteLength;if(n>cE)throw new vS({size:n});return Object.freeze({text:t})}function gE(e,t){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.freeze(Object.fromEntries(Object.entries(n).map(([n,r])=>[n,async i=>{t();try{return mE(await r(i))}catch(t){throw ES(t)?t:t instanceof tx?new bS({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof cS?new bS({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Rt({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function _E(e){return $n(t=>{let n=t.bind(void 0,C);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),y(e.removeEventListener.bind(e,`abort`,n))})}function vE(e,t){if(e===void 0)return()=>void 0;let n=t.bind(void 0);return e.aborted?(n(),()=>void 0):(e.addEventListener(`abort`,n,{once:!0}),e.removeEventListener.bind(e,`abort`,n))}function yE(e,t,n){return e===`deadline_exceeded`?new fS({limitMs:t,elapsedMs:n??0}):new mS({by:`caller`})}function bE(e){return Ma.pipe(we(t=>t-e))}function xE(e){return Ma.pipe(T(t=>sr(()=>{let n=e.executionId,r=new AbortController,i=t,a={kind:`waiting`},o,s=e=>{o===void 0&&a.kind!==`refused`&&(o=e,r.abort())},c=t=>{let n=new pS({capacity:e.policy.capacity,waitedMs:Math.max(0,t-i)});return a={kind:`refused`,failure:n},n},l=()=>{if(r.signal.aborted)throw yE(o,e.policy.timeoutMs)},u=vE(e.callerSignal,()=>{s(`cancelled`)}),d=t+e.policy.timeoutMs,f={executionId:n,deadlineAt:d,signal:r.signal,images:e.images};e.toolCallId!==void 0&&Object.assign(f,{toolCallId:e.toolCallId}),e.output!==void 0&&Object.assign(f,{output:e.output});let p=Object.freeze(f),m=sr(()=>Ma.pipe(T(u=>a.kind===`refused`?v(a.failure):(u>=d&&s(`deadline_exceeded`),r.signal.aborted?bE(t).pipe(T(t=>v(yE(o,e.policy.timeoutMs,t)))):u>=i+e.policy.waitMs?v(c(u)):(a={kind:`admitted`},e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:gE(e.createBindings(p),l),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(Br(e=>Ki(e)?Zt(e):v(DS(Ji(e)))))))))),ee=t=>S_(t).pipe(di({duration:e.policy.abortGraceMs,orElse:()=>v(o===`deadline_exceeded`?new fS({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new mS({by:`caller`,acknowledged:!1}))})),te,ne=!1,re=r=>(ne=!0,bE(t).pipe(T(t=>{let i=DS(r),a=i instanceof fS?new fS({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=SS(a,n),s=si(w(),bn()).parse(kS(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??nE(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=sr(()=>e.sandbox.onFailure?.(c)??C);return nt(`sandbox_failure`,c).pipe(fr({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),g(o._tag===`Unknown`?po(mo(fo(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(g(nt(`sandbox_health_alert`).pipe(fr({ref:n,adapter:c.adapter})))):C),g(l.pipe(Br(e=>nt(`sandbox_failure_record_failed`,e)))),Ar(o))})));return b(function*(){if(r.signal.aborted){let n=yield*bE(t);return yield*v(yE(o,e.policy.timeoutMs,n))}i=yield*Ma,te=yield*e.backingWork.start(m);let n=yield*Ma,l=jn(Math.max(0,i+e.policy.waitMs-n)).pipe(g(Ma),T(e=>a.kind===`admitted`?Nt:a.kind===`refused`?x({kind:`busy`,failure:a.failure}):r.signal.aborted?x({kind:`cancelled`}):e>=d?(s(`deadline_exceeded`),x({kind:`deadline`})):x({kind:`busy`,failure:c(e)}))),u=yield*Dn(b_(te).pipe(we(e=>Object.freeze({kind:`settled`,exit:e}))),Dn(jn(Math.max(0,d-n)).pipe(g(y(()=>(s(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),Dn(_E(r.signal).pipe(Ar(Object.freeze({kind:`cancelled`}))),l))),f=a.kind===`refused`?a.failure:u.kind===`busy`?u.failure:void 0;if(f!==void 0)return yield*ee(te).pipe(g(v(f)));if(u.kind===`settled`&&o===void 0)return yield*xe(u.exit,{onFailure:Zt,onSuccess:e=>oi({try:()=>hE(e),catch:t=>ES(t)?t:new yS({kind:OS(e),rawCause:t})})});u.kind===`deadline`&&s(`deadline_exceeded`);let p=yield*bE(t);return yield*ee(te).pipe(g(v(yE(o,e.policy.timeoutMs,p))))}).pipe(ke(()=>(s(`cancelled`),(te===void 0?C:S_(te).pipe(Xr(e.policy.abortGraceMs),mn)).pipe(g(sr(()=>ne?C:re(new mS({by:`operator`})).pipe(mn))))))).pipe(yn(e=>re(e).pipe(T(v))),rr(y(u)))})))}var SE=ym(()=>I([sm,om,cm,N,M,zh,Am(AbortSignal),F(SE),CE])),CE=fm(M,SE);function wE(e){return O(CE)(e)}var TE=new Map([[`openai`,`OpenAI`],[`openai-codex`,`OpenAI`],[`anthropic`,`Anthropic`],[`cloudflare-workers-ai`,`Cloudflare Workers AI`]]),EE=fm(M,Zh),DE=O(P({samplingParams:k(EE),samplingParamsByThinkingLevel:k(P({off:k(EE),minimal:k(EE),low:k(EE),medium:k(EE),high:k(EE),xhigh:k(EE),max:k(EE)}))}));function OE(e){return{...e,...DE(e)}}function kE(e){if(e===void 0)return;let{onPayload:t,onProviderStreamEvent:n,onResponse:r,...i}=e,a={...i};return t!==void 0&&(a.onPayload=(e,n)=>t(wE(e),OE(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(wE(e),OE(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,OE(t))),a}function AE(e){let t=new Map,n=[],r=e=>{for(let r of t.values())n.push({role:`toolResult`,toolCallId:r.id,toolName:r.name,content:[{type:`text`,text:`Tool execution interrupted.`}],isError:!0,timestamp:e});t.clear()};for(let i of e.messages){if(i.role===`toolResult`){t.delete(i.toolCallId)&&n.push(i);continue}if(i.role!==`system`&&r(i.timestamp),i.role===`assistant`){if(i.stopReason===`error`||i.stopReason===`aborted`)continue;for(let e of i.content)e.type===`toolCall`&&t.set(e.id,e)}n.push(i)}return r(e.messages.at(-1)?.timestamp??0),hi({...e,messages:n})}var jE=async(e,t,n)=>{let{streamSimple:r}=await gi(async()=>{let{streamSimple:e}=await import(`./compat-Bg_8DMIR.js`);return{streamSimple:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));return r(e,AE(t),kE(n))},ME=P({error:P({code:A(M),type:A(M)})});Wp(P({type:j(`response.failed`),response:ME})),Wp(U(ME)),Wp(P({type:j(`error`),status:A(N.check(th(),$m({minimum:100,maximum:599}))),code:A(M),error:A(ME.fields.error)})),O(Am(Uint8Array)),Wp(Fh.check($m({minimum:0,maximum:60}))),Wp(Fh.check(th(),$m({minimum:0,maximum:864e10}))),Wp(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Wp(j(`rejected`)),Wp(j(`0`)),Wp(Kh),Wp(P({type:j(`error`),error:P({type:j(`overloaded_error`)})}));var NE=[/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,/context window exceeded/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,/^(?:[\w -]+ API error \(413\):|413(?:\s|:|$))/i],PE=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,FE=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function IE(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!FE.some(t=>t.test(e.errorMessage))&&(NE.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&PE.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function LE(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function RE(e){return new RegExp(e.join(`|`),`i`)}var zE=RE([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`,`subscription_sharing_workplace_individual_usage_limit_exceeded`,`"code"\\s*:\\s*"?1308(?![0-9])`]),BE=RE([`overloaded`,`server_busy`,`servers are currently busy`,`currently experiencing high demand`,`model is at capacity`,`rate.?limit`,`too many requests`,`(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])`,`service.?(?:is.?)?(?:temporarily.?)?unavailable`,`server.?error`,`internal.?error`,`provider.?returned.?(?:an.?)?error`,`exceeded request buffer limit while retrying upstream`,`unable to forward upstream`,`upstream.?request.?failed`,`upstream_stream_read_error`,`stream was interrupted`,`http/?2 stream failed`,`network.?error`,`connection.?error`,`connection.?refused`,`connection.?lost`,`other side closed`,`fetch failed`,`request to \\S+ failed, reason:`,`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`,`stream disconnected before completion`,`cut short after the reply had begun`,`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`]),VE=6e4;function HE(e,t){let n=e.baseDelayMs*2**Math.max(0,t-1);return Math.min(Number.isSafeInteger(n)?n:2**53-1,e.maxAgentDelayMs??6e4)}var UE=class extends Error{constructor(){super(`Aborted`)}};function WE(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new UE);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new UE)},{once:!0})})}async function GE(e,t,n,r){let i=t?.enabled?t.maxRetries:0,a=0,o;for(;;){let s=await e();if(s.stopReason===`aborted`)return o&&await r?.onRetryFinished?.(!1,o.attempt),s;if(s.stopReason!==`error`)return o&&await r?.onRetryFinished?.(!0,o.attempt),s;if(a>=i||!KE(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=HE(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await WE(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof UE){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function KE(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!zE.test(t)&&BE.test(t)}var qE=P({provider:M,cause:I([I([P({code:j(`usage-limit-reached`),cause:k(j(`quota`)),resetAt:k(N),limit:k(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`]))}),P({code:j(`rate-limit`),retryAfterMs:k(N)}),P({code:j(`overloaded`)}),P({code:j(`provider_unavailable`),status:k(N)}),P({code:j(`provider_rejected`),status:N})]),P({code:L([`setup_required`,`tools_unsupported`,`request_failed`])})])}),JE={assign:0,create:0,clone:0,discard:0,update:0};function YE(e){return ZE(e,null)}function XE(e){return ZE(typeof e,`object`)&&!YE(e)}function ZE(e,t){return e===t}function QE(e){return ZE(e,`__proto__`)||ZE(e,`constructor`)||ZE(e,`prototype`)}function $E(e,t){return QE(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function eD(e){return Object.getOwnPropertyNames(e)}var tD={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function nD(){return tD}function rD(e){return nD().immutableTypes?Object.freeze(e):e}function iD(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function aD(e,t){return{...e,...t}}function oD(e,t,n={}){JE.create+=1;let r=aD(t,n);return rD(nD().enumerableKind?aD(r,e):iD(r,e))}function sD(e){return XE(e)}function cD(e){return sD(e)&&$E(e,`~optional`)}function lD(e){return eD(e).filter(t=>!cD(e[t]))}function uD(e,t={}){let n=lD(e);return oD({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var dD;(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`})(dD||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var fD=new Float64Array(1);new DataView(fD.buffer),new Uint8Array(fD.buffer),new TextEncoder;var pD=`-?(?:0|[1-9][0-9]*)`,mD=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function hD(e){return oD({"~kind":`String`},{type:`string`},e)}var gD=`^${pD}$`;`${mD}`;function _D(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var vD=[..._D(97,122),..._D(65,90)],yD=[`0`,..._D(49,57)];[...yD],[...vD,...yD],[...yD],new RegExp(gD);var bD={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},xD={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},SD=1e3,CD=Symbol(`Mule model limit`),wD=Symbol(`Mule model attempt limit`);function TD(e,t){return IE(e,t)}var ED=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),DD=(e,t)=>({kind:e,value:`mule_${e}_${rg()}`,parent:t}),OD=()=>C;function kD(e,t){let n={role:`toolResult`,toolCallId:e.id,toolName:e.name,content:t.content,isError:t.isError,timestamp:Date.now()};return t.usage!==void 0&&(n.usage=t.usage),n}var AD=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function jD(e,t){return e.find(e=>e.descriptor.name===t.name)}function MD(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function ND(e,t,n,r,i){let a=DD(`tool_call`,r);return b(function*(){if(yield*i({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:a,call:t}),e===void 0){let e=AD(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*MD(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*zr(e.prepare(t));if(Ae(o)){let e=AD(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*MD(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function PD(e,t,n,r){return b(function*(){let i,a;yield*vy(ry(e.tool.execute()),o=>Ae(o)?(a=o.failure,C):i===void 0?o.success.type===`result`?(i=o.success.result,C):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):C);let o=a===void 0?i??AD(`Tool "${e.call.name}" returned no result`):AD(a.message),s={call:e.call,identity:e.identity,result:o};return yield*MD(s,t,n,r),s})}function FD(e,t,n,r){let i=kD(e.call,e.result),a=DD(`tool_result`,e.identity);return b(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:a,value:i}),yield*r({type:`message_end`,run:t,turn:n,message:a,value:i,data:e.result.data}),i})}function ID(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>jD(a,e)?.executionMode===`sequential`);return b(function*(){let t=e=>e.kind===`finalized`?x(e.value):PD(e,n,r,i),s=o?yield*Zr(e,e=>T(ND(jD(a,e),e,n,r,i),t)):yield*b(function*(){let o=yield*Zr(e,e=>ND(jD(a,e),e,n,r,i));return yield*Hn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*Zr(s,e=>FD(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var LD=e=>AD(`Tool call "${e.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.`);function RD(e,t,n,r){return b(function*(){let i=yield*Zr(e,e=>b(function*(){let i=DD(`tool_call`,n),a={call:e,identity:i,result:LD(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*MD(a,t,n,r),a}));return yield*Zr(i,e=>FD(e,t,n,r))})}function zD(e,t){return pn({try:n=>{let r=()=>{t.abort(n.reason)};return n.aborted?r():n.addEventListener(`abort`,r,{once:!0}),Promise.resolve(e.next()).finally(()=>{n.removeEventListener(`abort`,r)})},catch:e=>ED(`model`,`Pi model stream failed`,e)})}function BD(e,t,n){return e.pipe(di({duration:t,orElse:()=>v(n())}))}function VD(e,t,n,r,i,a){let o=DD(`message`,r),s,c={started:!1,terminal:void 0};return nr(b(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??xD.firstEventMs,xD.firstEventMs),d=Math.min(l?.attemptMs??xD.attemptMs,xD.attemptMs),f=Math.min(l?.outputBytes??xD.outputBytes,xD.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*v(ED(`model`,`Model stream limits must be positive safe integers`));let p=Date.now(),m=p,ee=0,te=0,ne=new TextEncoder,re=!1,ie=e=>ED(`model`,`Model ${e} after ${String(Date.now()-p)} ms (max provider gap ${String(Math.max(ee,Date.now()-m))} ms, streamed ${String(te)} bytes)${e===`attempt timed out`?`. Write big content with file tools instead of one giant response.`:``}`,e===`attempt timed out`?wD:CD),ae=t=>{let n=Date.now()-p,r=d-n,i=Math.min(re?xD.idleMs:u,e.modelStreamIdleTimeoutMs??xD.idleMs)-(Date.now()-m),a=r<=i?`attempt timed out`:re?`stream timed out (silence)`:`first event timed out`;return BD(t,Math.max(0,Math.min(r,i)),()=>ie(a))},oe=new AbortController,se={};yield*Tr(()=>pn({try:()=>{if(oe.abort(`Mule model scope closed`),se.response===void 0)return Promise.resolve(!0);let e=se.response.then(async e=>{await Promise.all([se.iterator?.return?.(),e.result()])},()=>void 0);return new Promise(t=>{let n=setTimeout(()=>{t(!1)},SD);e.then(()=>{clearTimeout(n),t(!0)},()=>{clearTimeout(n),t(!1)})})},catch:e=>ED(`model`,`Pi model stream failed`,e)}).pipe(Lt(()=>!1),T(t=>t?C:e.onUndrained??C)));let ce=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,le={...e.streamOptions,maxRetries:0,signal:oe.signal};ce!==void 0&&(le.apiKey=ce);let ue=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*i({type:`model_prompt`,run:n,turn:r,attempt:a,systemPrompt:ue}));let de={systemPrompt:ue,messages:t},fe=(e.tools??[]).map(e=>e.descriptor);fe.length>0&&(de.tools=fe);let pe=yield*ae(pn({try:()=>{let t=e.stream??jE;return se.response=Promise.resolve(t(e.model,AE(de),le)),se.response},catch:e=>ED(`model`,`Pi model stream could not start`,e)})),me=pe[Symbol.asyncIterator]();se.iterator=me;let he=e=>{let a=Date.now();if(ee=Math.max(ee,a-m),m=a,re=!0,(e.type===`text_delta`||e.type===`thinking_delta`||e.type===`toolcall_delta`)&&(te+=ne.encode(e.delta).byteLength,te>f))return v(ie(`output limit exceeded`));switch(`partial`in e&&(s=e.partial),e.type){case`start`:return t.push(e.partial),c.started=!0,i({type:`message_start`,run:n,turn:r,message:o,value:e.partial});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`:return c.started&&(t[t.length-1]=e.partial),i({type:`message_update`,run:n,turn:r,message:o,value:e.partial,event:e});case`done`:return c.terminal=e.message,C;case`error`:return c.terminal=e.error,C}},ge=()=>ae(zD(me,oe)),_e=yield*ge();for(;!_e.done;)yield*he(_e.value),_e=yield*ge();let ve=c.terminal??(yield*ae(pn({try:()=>pe.result(),catch:e=>ED(`model`,`Pi model stream did not settle`,e)})));return c.started?t[t.length-1]=ve:(t.push(ve),yield*i({type:`message_start`,run:n,turn:r,message:o,value:ve})),{message:ve,identity:o}}).pipe(yn(l=>{if(l.cause!==CD&&l.cause!==wD)return v(l);let u={role:`assistant`,content:s?.content??[],api:e.model.api,provider:e.model.provider,model:e.model.id,usage:s?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,timestamp:Date.now(),errorMessage:e.retry?.enabled&&a>e.retry.maxRetries?`The model failed ${String(a)} times on this conversation: ${l.message}`:l.message};return b(function*(){return c.started?t[t.length-1]=u:(t.push(u),yield*i({type:`message_start`,run:n,turn:r,message:o,value:u})),{identity:o,message:u,limitReached:!0,attemptTimedOut:l.cause===wD}})})))}function HD(e,t,n,r,i,a){return b(function*(){let o=e.retry===void 0?void 0:{...e.retry};if(o?.enabled&&[o.maxRetries,o.baseDelayMs,o.maxAgentDelayMs??6e4].some(e=>!Number.isSafeInteger(e)||e<0))return yield*v(ED(`model`,`Retry policy requires non-negative safe-integer counts and delays`));let s,c=Math.min(o?.maxRetries??0,a?.maxAttempts??1/0),l=a===void 0?0:a.attempt+ +(a.phase===`dispatched`),u=a?.attempt??0,d=0,f=!1,p=a?.message?.errorMessage,m=t=>e.onRetry===void 0?C:e.onRetry(t),ee=(e,t)=>b(function*(){f=!0,yield*m(t===void 0?{type:`retry_finished`,run:n,turn:r,attempt:u,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:u,success:e,finalError:t})}),te=e=>b(function*(){yield*jn(Math.max(0,e-Date.now())),yield*m({type:`retry_attempt_started`,run:n,turn:r,attempt:u})}),ne=(e,t)=>b(function*(){if(o===void 0)return yield*v(ED(`model`,`Retry policy is unavailable`));u++,p=e;let i=Math.max(HE(o,u),t!==void 0&&Number.isSafeInteger(t)&&t>=0&&t<=6e4?t:0),a=Math.min(1e3,i/4,Math.max(0,6e4-i)),s=i+Math.floor(Math.random()*a),l=Date.now()+s;return{type:`retry_scheduled`,run:n,turn:r,attempt:u,maxAttempts:c,delayMs:s,dueAt:l,errorMessage:p}});return yield*b(function*(){if(a!==void 0){if(!Number.isSafeInteger(a.attempt)||a.attempt<0||a.maxAttempts!==void 0&&(!Number.isSafeInteger(a.maxAttempts)||a.maxAttempts<0)||a.phase===`waiting`&&(!Number.isSafeInteger(a.dueAt)||a.dueAt<0))return yield*v(ED(`model`,`Invalid model retry continuation`));if(!o?.enabled||u>c||a.phase===`dispatched`&&u>=c)return yield*ee(!1,`Model retry budget exhausted after restart`),a.message===void 0?yield*v(ED(`model`,`Model retry budget exhausted after restart`)):{message:a.message};if(a.phase===`waiting`)yield*te(a.dueAt);else{let e={...yield*ne(`Model request interrupted by a restart`),delayMs:0,dueAt:Date.now()};yield*m(e),yield*te(e.dueAt)}}for(;;){if(s!==void 0){let e=t.indexOf(s.message);e!==-1&&t.splice(e,1)}let a=yield*VD(e,t,n,r,i,++l);s=a;let p=a.message,ee=a.attemptTimedOut===!0&&d>0;a.attemptTimedOut&&d++;let re;if(p.stopReason===`error`&&o?.enabled&&u<c&&!ee&&(yield*oi({try:()=>a.limitReached===!0||e.retryable(p),catch:e=>ED(`model`,`Typed model retry decision failed`,e)}))){let t=yield*oi({try:()=>e.retryAfterMs?.(p),catch:e=>ED(`model`,`Model retry delay observation failed`,e)});re=yield*ne(p.errorMessage??`Unknown error`,t)}if(re===void 0&&(p.stopReason===`error`||u>0)){let e={type:`retry_finished`,run:n,turn:r,attempt:u,success:p.stopReason!==`error`&&p.stopReason!==`aborted`};re=p.stopReason===`error`&&p.errorMessage!==void 0?{...e,finalError:p.errorMessage}:e}if(yield*i({type:`message_end`,run:n,turn:r,message:a.identity,value:p,retry:re}),re?.type===`retry_finished`&&(f=!0),re!==void 0&&u>0&&(yield*m(re)),re?.type!==`retry_scheduled`)return s;yield*te(re.dueAt)}}).pipe(ke(()=>u===0||f?C:ee(!1,p)))})}var UD=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function WD(e,t,n,r,i,a){return Zr(e,e=>b(function*(){let o=DD(`message`,i);t.push(e),n.push(e),yield*a({type:`message_start`,run:r,turn:i,message:o,value:e}),yield*a({type:`message_end`,run:r,turn:i,message:o,value:e})})).pipe(mn)}function GD(e,t,n,r,i,a,o,s){return b(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*WD(a,t,n,r,i,o);let c=yield*HD(e,t,r,i,o,s),l=UD(c.message)!==`completed`,u=c.message.content.filter(e=>e.type===`toolCall`),d=u.length===0||l?{messages:[],terminate:!1}:c.message.stopReason===`length`?{messages:yield*RD(u,r,i,o),terminate:!1}:yield*ID(u,e,r,i,o);t.push(...d.messages),n.push(c.message,...d.messages),yield*o({type:`turn_end`,run:r,turn:i,message:c.message,toolResults:d.messages});let f={message:c.message,toolResults:d.messages,terminate:d.terminate};return c.limitReached&&c.message.errorMessage!==void 0?{...f,modelLimitReason:c.message.errorMessage}:f})}function KD(e,t,n,r,i,a){let o=DD(`turn`,i);return b(function*(){if(UD(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*Zr(t.tools,n=>b(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=jD(e.tools??[],n.call),s;if(t.message.stopReason!==`length`&&(n.state===`pending`||n.state===`started`&&n.replay===`safe`&&r?.replay===`safe`)){let e=yield*ND(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*PD(e,i,o,a)}else s={call:n.call,identity:DD(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?LD(n.call):AD(`Interrupted by a restart; it may or may not have completed; check before retrying.`)},yield*a({type:`tool_execution_start`,replay:`unsafe`,run:i,turn:o,toolCall:s.identity,call:s.call}),yield*MD(s,i,o,a);return{message:yield*FD(s,i,o,a),terminate:s.result.terminate===!0,recorded:!1}})),c=s.filter(({recorded:e})=>!e).map(({message:e})=>e);return n.push(...c),r.push(...c),{message:t.message,toolResults:s.map(({message:e})=>e),terminate:s.length>0&&s.every(({terminate:e})=>e)}})}function qD(e,t,n,r){return b(function*(){if(e.shouldStopAfterTurn!==void 0&&(yield*e.shouldStopAfterTurn({message:t.message,toolResults:t.toolResults,context:n,newMessages:r})))return{continue:!1,pending:[]};let i=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()];if(t.message.content.some(e=>e.type===`toolCall`)&&!t.terminate||i.length>0)return{continue:!0,pending:i};let a=e.getFollowUpMessages===void 0?[]:[...yield*e.getFollowUpMessages()];return{continue:a.length>0,pending:a}})}function JD(e,t,n,r,i,a,o){return b(function*(){yield*a({type:`run_end`,run:e,terminal:t,outcome:i});let s={status:i,run:e,terminal:t,message:n,messages:r};return o===void 0?s:{...s,modelLimitReason:o}})}function YD(e,t=OD){return b(function*(){let n=yield*A_(1),r={started:!1,ended:!1},i=e=>sr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(In(()=>y(()=>{e.type===`run_start`&&(r.started=!0)}))),a=DD(`run`),o=DD(`terminal`,a);return yield*ZD(e,i,a,o).pipe(Ne(e=>{let t=XD(e);return!r.started||r.ended||t===void 0?C:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Ve)}))})}function XD(e){if(ca(e))return;if(Ki(e.cause))return`cancelled`;let t=Xi(e.cause);if(!(Nr(t)&&t.value.phase===`listener`))return`failed`}function ZD(e,t,n,r){return b(function*(){let i=[...e.messages],a=[],o=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()],s,c;yield*t({type:`run_start`,run:n});let l=e.resume?.kind===`retry`?e.resume:void 0;if(e.resume?.kind===`assistant`){let s=yield*KD(e,e.resume,i,a,n,t),c=UD(s.message),l=c===`completed`?yield*qD(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*JD(n,r,s.message,a,c,t);o.push(...l.pending)}do{let u=yield*GD(e,i,a,n,DD(`turn`,n),o,t,l);l=void 0,s=u.message;let d=UD(u.message);if(d!==`completed`)return yield*JD(n,r,u.message,a,d,t,u.modelLimitReason);if(e.prepareNextTurn!==void 0&&!u.terminate&&u.message.content.some(e=>e.type===`toolCall`)){let t=yield*e.prepareNextTurn({message:u.message,toolResults:u.toolResults,context:i,newMessages:a});t!==void 0&&i.splice(0,i.length,...t)}let f=yield*qD(e,u,i,a);o=[...f.pending],c=f.continue}while(c);return yield*JD(n,r,s,a,`completed`,t)})}var QD={run:YD},$D=class{#e=new Map;#t;constructor(e=8){this.#t=e}push(e,t){let n=this.#e.get(e)??[];if(n.length>=this.#t)throw new bS({namespace:`execute`,operation:`images`,cause:{kind:`Unavailable`,message:`Image collector cap reached for this execution (max ${String(this.#t)} images). Process images one at a time or write them to files.`}});let r=`img_${String(n.length)}`;return n.push(Object.freeze({...t})),this.#e.set(e,n),r}drain(e){let t=this.#e.get(e);return t===void 0?[]:(this.#e.delete(e),t)}dispose(e){this.#e.delete(e)}},eO=8192,tO=eO*4,nO=new TextEncoder,rO=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),iO=class e{wake;#e={stdout:{decoder:rO(),pending:new Uint8Array},stderr:{decoder:rO(),pending:new Uint8Array}};#t=rO();#n=Array.from({length:eO},()=>void 0);#r=0;#i=0;#a=0;#o=0;#s=0;#c=0;#l=!1;#u=!1;constructor(e){this.wake=e}static make(){return Bg({capacity:1,strategy:`dropping`}).pipe(we(t=>new e(t)))}write(e,t){if(this.#u||t.length===0)return;let n=this.#e[e];this.#c+=t.length;for(let e=0;e<t.length;e+=tO){let r=t.subarray(e,e+tO),i=n.decoder.decode(r,{stream:!0}),a=new Uint8Array(n.pending.length+r.length);a.set(n.pending),a.set(r,n.pending.length);let o=this.#f(a);n.pending=a.slice(a.length-o),this.#h(i,a.length-o,a)}this.#l=!0,Wg(this.wake,void 0)}#d(e,t){let n=this.#t.decode(e.subarray(0,t),{stream:!0});return this.#t.decode(),n}#f(e){for(let t=1;t<=Math.min(3,e.length);t++){let n=e.subarray(e.length-t);if(this.#d(n,n.length).length===0)return t}return 0}#p(){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);this.#n[this.#r]=void 0,this.#r=(this.#r+1)%eO,this.#i--,this.#a-=e.textBytes,this.#o-=e.newlines,this.#s+=e.rawBytes}#m(e,t,n){let r=e.raw;if(r===null){this.#p();return}let i=e=>{let i=this.#d(r,e);return nO.encode(i).length>=t&&i.split(`
|
|
19
|
-
`).length-1>=n},a=Math.min(r.length,Math.max(4,t));for(;a<r.length&&!i(a);)a=Math.min(r.length,a*2);let o=0;for(;o<a;){let e=Math.floor((o+a)/2);i(e)?a=e:o=e+1}let s=this.#d(r,o);if(s.length===e.text.length){this.#p();return}let c=o-this.#f(r.subarray(0,o)),l=
|
|
20
|
-
`).length-1;e.raw=r.slice(c),e.text=this.#d(e.raw,e.raw.length),e.rawBytes-=c,e.textBytes-=l,e.newlines-=u,this.#a-=l,this.#o-=u,this.#s+=c}#h(e,t,n){if(e.length===0)return;let r={text:e,raw:n,rawBytes:t,textBytes:
|
|
21
|
-
`).length-1};for(this.#i===eO&&this.#p(),this.#n[(this.#r+this.#i)%eO]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>eO||this.#o>=200;){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);let t=Math.max(0,this.#a-eO),n=Math.max(0,this.#o-199);e.textBytes<=t||e.newlines<n?this.#p():this.#m(e,t,n)}}snapshot(){let e=``;for(let t=0;t<this.#i;t++){let n=this.#n[(this.#r+t)%eO];if(n===void 0)throw Error(`Missing output ring entry`);e+=n.text}return{tail:e,droppedBytes:this.#s,totalBytes:this.#c}}#g(){if(!this.#l)return;this.#l=!1;let{tail:e,...t}=this.snapshot();return{type:`update`,result:{isError:!1,content:[{type:`text`,text:e}],data:t}}}finish(){if(!this.#u){this.#u=!0;for(let e of[this.#e.stdout,this.#e.stderr]){let t=e.decoder.decode();this.#h(t,e.pending.length,null),e.pending=new Uint8Array,t.length>0&&(this.#l=!0)}return this.#g()}}get updates(){return Zv(this.wake).pipe(ny(()=>jn(`100 millis`).pipe(we(()=>this.#u?void 0:this.#g()))),dy(e=>e!==void 0))}dispose(){this.#u=!0,this.#n.fill(void 0),this.#r=this.#i=this.#a=this.#o=0,this.#c=this.#s=0,this.#l=!1;for(let e of[this.#e.stdout,this.#e.stderr])e.decoder.decode(),e.pending=new Uint8Array}},aO=P({code:M}),oO='Inside execute, call forage.search, forage.list or forage.describe to discover operations and inspect their inputs. forage is available only there, not as a separate tool. Run async JavaScript in the sandbox. Each call is a fresh sandbox, not a REPL: nothing survives between calls, so redefine helpers or persist state to a file. Never shadow injected module names with local bindings. Find operations with await forage.search({ query }) using one short keyword such as read or shell, or page them all with forage.list({limit:50}), optionally by namespace, until nextCursor is null. Inspect input with await forage.describe({ path }) before calling; describe known paths directly. Call an operation as await env.<path>({ ... }) with the exact dotted path, for example await env.computers.local.exec({ command: "pwd" }); a bare computers.local.exec is not defined. Put multiline shell commands in a template literal. Code is JavaScript first, so double each backslash the shell needs (`\\\\(` passes `\\(`; `\\(` becomes `(`). For file edits, prefer Files operations when available. Explicitly return the final value. Before treating a shell or process result as success, check status, exitCode and stderr.';function sO(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await vT(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function cO(e,t,n,r){let i=0,a=new Map;for(let o of e){let e=o.namespace,s=o.name,c=a.get(e)??new Map;c.set(s,e=>sO(o,Object.freeze({...t,operationOrdinal:i++}),n,r)(e)),a.set(e,c)}return Object.freeze(Object.fromEntries([...a].map(([e,t])=>[e,Object.freeze(Object.fromEntries(t))])))}function lO(e,t){let n=e.safeParse(t);if(!n.success)throw new cS(n.error.issues);return n.data}function uO(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(lO(Gb,t))),describe:t=>Promise.resolve().then(()=>e.describe(lO(Wb,t))),search:t=>Promise.resolve().then(()=>e.search(lO(Ub,t)))})}function dO(e,t,n,r,i){return Object.freeze({...cO(e,n,r,i),forage:uO(t)})}function fO(e,t,n,r,i,a,o,s){let c=n.execution??dE(void 0),l=new $D,u=(u,d,f,p,m)=>xE({executionId:u,toolCallId:p,output:m,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>dO(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>sr(()=>{let n=rg();return u(n,e,t).pipe(rr(y(()=>{l.dispose(n)})))}),f=(e,t,n)=>sr(()=>{let r=rg(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(Tt({onSuccess:e=>x(pO({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof vS&&t.length>0?x(pO({text:CS(e),isError:!0},t)):v(mO(e))}}),rr(y(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:oO,parameters:uD({code:hD()},{additionalProperties:!1})},prepare:e=>Hp(aO)(e.arguments).pipe(we(({code:t})=>({execute:()=>ey(b(function*(){let n=yield*iO.make();yield*Tr(()=>y(()=>{n.dispose()}));let r=yield*Yn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return uy(n.updates,Lv(b_(r)).pipe(iy(e=>{let t=n.finish();return sy(Yv(t===void 0?[]:[t]),Lv(e))})),{haltStrategy:`right`}).pipe(hy(e=>e.type===`result`))}))})),ut(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function pO(e,t){let n=t.map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})),r=[{type:`text`,text:e.text},...n];return t.length===0?{type:`result`,result:{content:r,isError:e.isError}}:{type:`result`,result:{content:r,data:{images:t.map(e=>({bytes:e.bytes,mimeType:e.mimeType,path:e.path}))},isError:e.isError}}}function mO(e){let t={_tag:`MuleError`,phase:`tool`,message:ES(e)?CS(e):e.message};return e instanceof pS?{...t,cause:e}:t}function hO(e,t){return e<t?-1:+(e>t)}var gO=128,_O=_(()=>w().min(1).max(160)),vO=_(()=>Qt({version:w().min(1).max(160),modules:Er(xt())})),yO=1e3;function bO(e){if(e.length>gO)throw new G(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>hO(e.id,t.id)),n=new Set;for(let e of t){if(!_O.safeParse(e.id).success)throw new G(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new G(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function xO(e){if(e>yO)throw new G(`Candidate module count exceeds bound`)}function SO(e,t){let n=vO.safeParse(e);if(!n.success)throw new G(`Capability source snapshot must have a non-empty bounded version`);xO(t+n.data.modules.length)}function CO(e,t,n,r,i){return ne(a=>b(function*(){let o=t=>pn({try:()=>t.release(),catch:()=>new sS(e.id,`release`)}).pipe(yn(e=>y(()=>{n.push(e)}))),s=yield*oi({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(i===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:i}).then(e=>ra(e),()=>aa(new sS(e.id,`acquire`)))}},catch:()=>new sS(e.id,`acquire`)});yield*Da(t,qt(()=>s.outcome).pipe(T(e=>ca(e)?o(e.value):C)));let c=yield*a(qt(()=>s.outcome)).pipe(ke(()=>y(()=>{s.controller.abort()})));return la(c)?yield*Zt(c.cause):c.value}))}function wO(e){return b(function*(){let t=yield*oi({try:()=>bO(e.sources),catch:e=>e instanceof G?e:new G(`Capability sources are invalid`)});yield*oi({try:()=>{xO(e.modules.length)},catch:e=>e instanceof G?e:new G(`Static capability modules are invalid`)});let n=yield*Ca(),r=[],i=!1,a=[...e.modules],o=[];return yield*b(function*(){for(let s of t){let t=yield*CO(s,n,r,()=>{i=!0},e.session);yield*oi({try:()=>{SO(t.snapshot,a.length)},catch:e=>e instanceof G?e:new G(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*oi({try:()=>tE(a,o),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=fO(s.operations,s.catalog,e.sandbox,c,s.moduleAliases,s.namespacePaths,e.session?.sessionId??null,e.access),u=!1;return Object.freeze({compiled:s,executeDoor:l,isStale:()=>i,close:()=>b(function*(){u||(u=!0,yield*c.awaitIdle,yield*Aa(n,sa));let e=r[0];e!==void 0&&(yield*v(e))})})}).pipe(Ne(e=>ca(e)?C:Aa(n,e)))})}var TO=2;function EO(e){return b(function*(){for(let t=0;t<TO;t+=1){let t=yield*wO(e);if(!t.isStale())return t;yield*t.close()}return yield*v(new sS(void 0,`stale`))})}function DO(e,t,n){return ne(r=>r(e.take(1)).pipe(T(()=>y(t).pipe(rr(e.release(1)))),T(n)))}function OO(e,t){return yt(e.candidate.close().pipe(Tt({onFailure:t=>ya(e.settled,t).pipe(g(v(t))),onSuccess:()=>ba(e.settled,void 0).pipe(g(y(()=>{t.delete(e)})))})))}function kO(e,t){return e.runCleanup?OO(e.installed,t):_a(e.installed.settled)}function AO(e,t){return Hn(e.map(e=>kO(e,t).pipe(Ln)),{concurrency:`unbounded`}).pipe(T(e=>{let t=e.find(la);return t===void 0?C:Zt(t.cause)}))}function jO(e){return b(function*(){let t=yield*A_(1),n=yield*oi({try:()=>dE(e.execution),catch:e=>e instanceof G?e:new G(`Execution policy is invalid`)}),r=yield*fE(n.capacity),i=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:n}),a=e.modules.length===0&&e.sources.length>0?void 0:yield*oi({try:()=>tE(e.modules),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)}),o=yield*oi({try:()=>Object.freeze(e.tools.map(t=>xT(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof G?e:new G(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*EO({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*ga(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>DO(t,()=>(l=!0,[...c].map(e=>{e.retired=!0;let t=e.leases===0&&!e.closing;return t&&(e.closing=!0),{installed:e,runCleanup:t}})),e=>AO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({acquire:()=>t.withPermits(1)(b(function*(){if(l)return yield*v(new oS);if(s===void 0||s.candidate.isStale()){let t=yield*EO({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*ga(),leases:0,retired:!1,closing:!1};s=a,c.add(a),n!==void 0&&(n.retired=!0,n.leases===0&&!n.closing&&(n.closing=!0,yield*OO(n,c)))}let n=s;n.leases+=1;let a,u=()=>DO(t,()=>{if(a!==void 0)return a?{installed:n,runCleanup:!1}:void 0;if(--n.leases,a=n.retired&&n.leases===0&&!n.closing,a)return n.closing=!0,{installed:n,runCleanup:!0}},e=>e===void 0?C:kO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({revision:n.candidate.compiled.revision,catalog:n.candidate.compiled.catalog,executeDoor:n.candidate.executeDoor,effectExecuteTool:n.candidate.executeDoor.effectTool,tools:o,release:u})})),close:u})})}function MO(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>yt(pn({try:()=>e.execute(t,n),catch:DS}))})}function NO(e){return jO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:e.sandbox,onSandboxFailure:e.onSandboxFailure,tools:e.tools??[],access:e.access??{}}).pipe(we(e=>Object.freeze({acquire:()=>e.acquire().pipe(we(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function PO(e,t){let n=await Kn(e,t);if(ca(n))return n.value;let r=Xi(n.cause);if(Nr(r))throw r.value;if(Ki(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Ji(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function FO(e){let t=await PO(Ca()),n=e.onSandboxFailure;try{let r=await PO(jO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:MO(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>qt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(Ta(t))),i=async e=>{let t=await PO(Ca());try{let n=await PO(r.acquire().pipe(Ta(t)),e?.signal===void 0?void 0:{signal:e.signal}),i;return Object.freeze({revision:n.revision,catalog:n.catalog,executeTool:n.effectExecuteTool,tools:n.tools,release:()=>(i??=PO(n.release().pipe(rr(Aa(t,sa)))),i)})}catch(e){throw await PO(Aa(t,sa)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=PO(r.close().pipe(rr(Aa(t,sa)))),a)})}catch(e){throw await PO(Aa(t,sa)),e}}var IO=ym(()=>I([om,cm,Hm,M,gm(F(IO)),tm(fm(M,IO))])),LO=M.check(hh(1),vh(256)),RO=M.check(hh(1),vh(128)),zO=P({kind:j(`sandbox_failure`),ref:LO,executionId:LO,adapter:RO,buildSha:R(RO),tag:L([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:fm(M,IO),healthAlert:cm});function BO(e){return jT(e)}function VO(e){return MT(e)}var HO=Object.freeze({module:VO,operation:BO,make:FO,gate:zT,grantAs:RT}),UO=Zh,WO=4096,GO=new TextEncoder,KO=UO.check(B(e=>GO.encode(JSON.stringify(e)).byteLength<=WO)),qO=D(KO);function JO(e,t){if(em(e))return Wt(D(e)(t));let n=e[`~standard`].validate(t);if(br(n,`then`))throw new W(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function YO(e,t){let n=qO(t);if(Ae(n))throw new W(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!JO(e.schema,n.success))throw new W(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function XO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ZO(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function QO(e){return ZO({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function $O(e,t,n){dr(nt(`shiitake_operation_failed`,Lo(t)).pipe(fr({operation:e,errorKind:t instanceof Error?`error`:`non-error`,...n})))}var ek=64,tk=256,nk=new WeakMap,rk=new TextEncoder;function ik(e){let t=nk.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:rk.encode(n).byteLength});return nk.set(e,r),r}function ak(e){if(e.kind===`update`&&e.sandboxFailures!==void 0){let t={...e};return delete t.sandboxFailures,t}if(e.kind===`reset`&&e.baseline.sandboxFailures!==void 0){let t={...e.baseline};return delete t.sandboxFailures,{...e,baseline:t}}return e}function ok(e){let t=new Set,n=!1,r,i=e=>{_r(Zg(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:_r(Hg(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=sr(()=>o.closed?x(`closed`):r===void 0?o.lagged?x(`reset`):n?x(`closed`):e_(o.frames).pipe(Qa(()=>x(`closed`)),T(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=ik(e).bytes),x(e)):v(r))):v(r));return Object.freeze({take:s,checkpoint:(e=-1)=>{i(o),o.lagged=!1,o.observed=e},close:()=>{o.closed||(o.closed=!0,i(o),t.delete(o),Jg(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=ak(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=ik(t);n.bytes+o>1048576||!Wg(n.frames,t)?(i(n),n.lagged=!0,Wg(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Jg(e.frames)}}}}var sk=new WeakMap;function ck(e,t){for(let n of sk.get(e)??[])if(n.observes(t))return!0;return!1}function lk(e,t){return e===`closed`||t===`closed`?`closed`:e===`reset`||t===`reset`?`reset`:e===`durable`||t===`durable`?`durable`:e===`activity`||t===`activity`?`activity`:`progress`}function uk(e,t){if(e.pendingCount>=tk){e.pendingCount=0,e.pendingReason=void 0,e.reset=!0;return}e.pendingCount+=1,e.pendingReason=e.pendingReason===`durable`||t===`durable`?`durable`:e.pendingReason===`activity`||t===`activity`?`activity`:`progress`}function dk(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){uk(e,t);return}e.wake=void 0;try{n(t)}catch(t){$O(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function fk(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&dk(n,`activity`)}function pk(e,t,n=`durable`){let r=sk.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){$O(`owner-observation-publish`,e);continue}}function mk(e){let t=sk.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){$O(`owner-execution-change-publish`,e)}}function hk(e){let t=new Map,n=new Set,r=sk.get(e)??new Set,i=!1,a=e=>{if(e.closed)return`closed`;if(e.reset)return e.reset=!1,`reset`;if(e.pendingCount===0)return;e.pendingCount=0;let t=e.pendingReason;return e.pendingReason=void 0,t??`progress`},o=e=>{if(e.closed)return;e.closed=!0,e.pendingCount=0,e.pendingReason=void 0,e.reset=!1;let r=e.wake;e.wake=void 0,n.delete(e);let i=t.get(e.sessionId);if(i?.delete(e),i?.size===0&&t.delete(e.sessionId),r!==void 0)try{r(`closed`)}catch(e){$O(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){fk(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&fk(n,e.sessionId);let r=e.sessionId===null?n:t.get(e.sessionId);if(r!==void 0)for(let t of r)t.settlementOnly&&e.reason!==`settlement`||dk(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),sk.set(e,r),Object.freeze({register:(e,r)=>sr(()=>{if(i)return v(new W(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=ek)return v(new W(`runtime`,`rejected`,`Observation capacity is exhausted`));let s={revision:0,sessionId:e,settlementOnly:r===`settlement`,closed:!1,pendingCount:0,pendingReason:void 0,queued:!0,reset:!1,wake:void 0},c=t.get(e)??new Set;c.add(s),t.set(e,c),n.add(s);let l=y(()=>a(s)),u=$n(e=>{let t=a(s);if(t!==void 0){e(x(t));return}let n=t=>{e(x(t))};return s.wake=n,y(()=>{s.wake===n&&(s.wake=void 0)})});return x(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:y(()=>{if(!i){i=!0,r.delete(s),r.size===0&&sk.delete(e);for(let e of n)o(e)}})})}var gk=200,_k={onExcessProperty:`error`},vk=new TextEncoder,yk=H.pipe(z(V(0))),bk=M.pipe(z(hh(1)),z(B(e=>vk.encode(e).byteLength<=256)));D(P({limit:k(H.pipe(z($m({minimum:1,maximum:gk})))),after:k(M)}),_k);var xk=U(mm([yk,bk]));D(xk),Qp(xk),D(P({session_id:bk,last_activity_at:yk,state:L([`needs_you`,`running`,`errored`,`done`]),bytes:H.pipe(z(V(0)))}),_k);var Sk=O(P({extension_id:M,value_json:M})),Ck=O(U(Dy)),wk=O(Oy),Tk=Qp(U(Dy));function Ek(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
18
|
+
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return mC(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),(r!==`0`||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return rC(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},Q.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},Q.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(XS(i,r))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?YS:XS)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=mC(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},Q.readWord=function(){var e=this.readWord1(),t=J.name;return this.keywords.test(e)&&(t=eC[e]),this.finishToken(t,e)},HC.acorn={Parser:HC,version:`8.18.0`,defaultOptions:yC,Position:gC,SourceLocation:_C,getLineInfo:vC,Node:dw,TokenType:K,tokTypes:J,keywordTypes:eC,TokContext:nw,tokContexts:rw,isIdentifierChar:XS,isIdentifierStart:YS,Token:nT,isNewLine:rC,lineBreak:tC,lineBreakG:nC,nonASCIIwhitespace:aC};function oT(e,t){return HC.parse(e,t)}_(()=>hn(`ok`,[ln({ok:yr(!0),value:xt()}),ln({ok:yr(!1),error:ln({kind:yr(`guest_threw`),name:w().max(80),message:w().max(512),transportMessage:w().max(512).optional()})})]));var sT=_(()=>w().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),cT=sT.refine(e=>{if(e===`env`)return!1;try{return oT(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);_(()=>si(cT,Er(sT).min(1))),_(()=>si(cT,Er(w().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var lT=L([`read`,`write`]),uT=cm,dT=P({access:A(lT),confirm:A(uT)}),fT=L([`none`,`read`,`write`]),pT=D(dT),mT=D(fT);function hT(e){let t=pT({access:e.access,confirm:e.confirm});if(Ae(t))throw new G(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function gT(e,t){let n=`${t.module}.${t.operation}`;switch(e){case`not-granted`:return`${n} is not granted to this Agent.`;case`read-only`:return`${n} changes something, and this Agent has read-only access to ${t.module}.`;case`confirmation-unavailable`:return`${n} needs a person's approval, and no one can be asked here.`;case`declined`:return`${n} was not approved.`}}function _T(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:gT(e,t)})}function vT(e,t,n){let r=e.sessionGrants?.(t),i=r!==void 0&&Object.hasOwn(r,n)?r:e.grants;if(i===void 0||!Object.hasOwn(i,n))return e.required?.includes(n)===!0?`none`:e.defaultGrant??`write`;let a=mT(i[n]);return Wt(a)?a.success:`none`}async function yT(e,t,n,r,i){let a=await bT(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function bT(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=xT(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?_T(`confirmation-unavailable`,n):await e.confirm({module:n.module,operation:n.operation,access:n.access,sessionId:t.sessionId,input:r},i)?(await e.beforeCall?.(i),i.throwIfAborted(),xT(e,t,n)):_T(`declined`,n)}function xT(e,t,n){let r=vT(e,t,n.module);if(r===`none`)return _T(`not-granted`,n);if(r===`read`&&n.access!==`read`)return _T(`read-only`,n)}function ST(e,t,n){let r={module:e.module,operation:e.descriptor.name,...hT(e)};return{...e,prepare:i=>pn({try:e=>yT(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(T(t=>t===void 0?e.prepare(i):x({execute:()=>Kv({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var CT=Cs();async function wT(e){let t=await Kn(e);if(ca(t))return{value:t.value};let n=Yi(t.cause);if(Ae(n))throw Ji(t.cause);return{issues:CT(n.success.issue).issues}}function TT(e){let t=Zh(e),n=Bp(t)[`~standard`].jsonSchema,r=Hp(t),i=qp(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>wT(r(e)),encode:e=>wT(i(e))})}function ET(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function DT(e){return em(e)?TT(e):ET(e)}var OT=Symbol(`mycelium.operation`),kT=Symbol(`mycelium.module`),AT=new WeakMap,jT=new WeakMap;function MT(e){let t=Object.freeze({[OT]:!0}),n=DT(e.input),r=e.output===void 0?void 0:DT(e.output),i={replay:e.replay??`unsafe`,...hT(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new lS(a.issues);let o=await e.execute(a.value,i);if(r===void 0)return o;let s=await r.encode(o);if(s.issues!==void 0)throw new vS({reason:`Capability output failed its declared schema`,rawCause:new uS(s.issues)});return s.value}};e.description!==void 0&&(i.description=e.description),r!==void 0&&(i.output=r.description);let a=Object.freeze(i);return AT.set(t,a),t}function NT(e){let t=Er(sT).safeParse(e.namespace??[]);if(!t.success)throw new G(`Invalid module namespace`);let n=Object.freeze({[kT]:!0}),r={id:e.id,grantKey:e.id,name:e.name??e.id,namespace:Object.freeze(t.data),operations:Object.freeze({...e.operations})};e.description!==void 0&&(r.description=e.description);let i=Object.freeze(r);return jT.set(n,i),n}function PT(e){return jT.has(e)}function FT(e){return AT.get(e)}function IT(e){return jT.get(e)}function LT(e,t,n){let r=IT(e);if(r===void 0)throw new G(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(PT(a)){let n=IT(a);if(n===void 0)throw new G(`Unknown child module registration`);i[e]=LT(a,t,[r,...n.namespace].join(`.`));continue}let o=FT(a);if(o===void 0)throw new G(`Unknown operation registration: ${e}`);let s=Object.freeze({[OT]:!0});AT.set(s,Object.freeze({...o,invoke:async(e,n)=>{let i=await t({operation:r,context:n});return i.kind===`refuse`?i.value:await o.invoke(e,n)}})),i[e]=s}return RT(NT(r.description===void 0?{id:r.id,name:r.name,namespace:r.namespace,operations:i}:{id:r.id,name:r.name,namespace:r.namespace,description:r.description,operations:i}),r.grantKey)}function RT(e,t){let n=IT(e);if(n===void 0)throw new G(`Unknown module registration`);let r=Object.freeze({[kT]:!0});return jT.set(r,Object.freeze({...n,grantKey:t})),r}function zT(e,t){if(t.length===0||t.length>160)throw new G(`Grant key must be non-empty and bounded`);return RT(e,t)}function BT(e,t){return LT(e,t,``)}function VT(e,t){return e<t?-1:+(e>t)}function HT(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var UT=160;function WT(e){if(e.length===0||e.length>UT)throw new G(`Module id must be non-empty and bounded`)}function GT(e){if(!e.split(`.`).every(e=>sT.safeParse(e).success))throw new G(`Operation key must be a path segment or a dotted relative path`)}function KT(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function qT(e){let t=KT(e);return cT.safeParse(t).success?t:`module_${t}`}function JT(e,t){let n=new Set([`forage`,`env`]),r=new Map;for(let i of e){let e=t===`logical`?i.namespace:[],a=t===`logical`?KT(i.name):qT(i.name),o=t=>[...e,t].join(`.`),s=a,c=2;for(;n.has(o(s));)s=`${a}_${String(c)}`,c+=1;n.add(o(s)),r.set(i.id,s)}return r}var YT=14695981039346656037n,XT=1099511628211n,ZT=18446744073709551615n;function QT(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*XT&ZT,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*XT&ZT,n=(n^BigInt(r>>>8&255))*XT&ZT}return n}function $T(e,t,n){let r=QT(YT,e),i=[...t.entries()].sort(([e],[t])=>VT(e,t));for(let[e,t]of i)r=QT(r,e),r=QT(r,t);let a=[...n].sort((e,t)=>VT(e.id,t.id));for(let e of a)r=QT(r,e.id),r=QT(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function eE(){return[nS,tS,rS]}function tE(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(GT(t),PT(o)){let s=IT(o);if(s===void 0)throw new G(`Unknown child module registration`);return tE(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=FT(o);if(s===void 0)throw new G(`Unknown operation registration: ${[...r,t].join(`.`)}`);return[Object.freeze({grantKey:e,path:[...r,t].join(`.`),namespace:n,name:[...a,t].join(`.`),moduleDescription:i,operation:s})]})}function nE(e,t=[]){let n=e.map(e=>{let t=IT(e);if(t===void 0)throw new G(`Unknown module registration`);return WT(t.id),t}).sort((e,t)=>VT(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new G(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=JT(n,`transport`),a=JT(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new G(`Missing logical alias: ${e.id}`);return[t,Object.freeze([...e.namespace,n])]}))),s=n.flatMap(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new G(`Missing namespace path: ${e.id}`);return tE(e.grantKey,e,t,n,e.description)}).sort((e,t)=>VT(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new G(`Duplicate operation path`);for(let e of eE()){if(c.has(e.path))throw new G(`Reserved intrinsic path: ${e.path}`);c.add(e.path)}for(let e of c){let t=e.split(`.`);for(let n=1;n<t.length;n+=1)if(c.has(t.slice(0,n).join(`.`)))throw new G(`Operation conflicts with namespace: ${e}`)}let l;try{l=Zx({revision:`prepared-content-stamp`,operations:[...s.map(({path:e,moduleDescription:t,operation:n})=>{let r={path:e,input:n.input};return n.description!==void 0&&(r.description=n.description),n.output!==void 0&&(r.output=n.output),t!==void 0&&(r.instructions=t),r}),...eE()]})}catch(e){throw new G(HT(e))}let u=$T(l.stamp(),i,t),d=Object.freeze({revision:u,search:l.search,describe:l.describe,list:l.list,stamp:l.stamp}),f=Object.freeze(Object.fromEntries([...i.entries()].map(([e,t])=>[t,e])));return Object.freeze({revision:u,catalog:d,operations:Object.freeze(s),moduleAliases:f,namespacePaths:o})}function rE(){return null}var iE=bn(),aE=_(()=>Qr([wn(),w(),pr(),Mn()])),oE=_(()=>si(w(),xt())),sE=_(()=>IS.extend({timeoutMs:Mn().int().min(1).max(9e5).optional(),abortGraceMs:Mn().int().min(1).max(3e4).optional()}).optional()),cE=64,lE=262144,uE=new TextEncoder,dE=e=>{e(x(void 0))};function fE(e){let t=sE.safeParse(e);if(!t.success)throw new G(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...LS({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function pE(e){return b(function*(){let t=yield*j_(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=$n(t=>e===0?(t(x(void 0)),y(()=>void 0)):(n.add(t),y(()=>n.delete(t))));return Object.freeze({start:r=>ne(i=>y(()=>{e+=1}).pipe(g(re(i(t.withPermits(1)(r)).pipe(rr(y(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(dE)}}))))))),awaitIdle:r})}})})}function mE(e,t=0){if(t>cE)throw Error(`JSON value exceeds the nesting bound`);let n=aE.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>mE(e,t+1));let r=oE.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,mE(n,t+1)]))}function hE(e){return iE.parse(mE(e))}function gE(e){let t=JSON.stringify(hE(e)),n=uE.encode(t).byteLength;if(n>lE)throw new yS({size:n});return Object.freeze({text:t})}function _E(e,t){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.freeze(Object.fromEntries(Object.entries(n).map(([n,r])=>[n,async i=>{t();try{return hE(await r(i))}catch(t){throw DS(t)?t:t instanceof nx?new xS({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof lS?new xS({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Rt({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function vE(e){return $n(t=>{let n=t.bind(void 0,C);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),y(e.removeEventListener.bind(e,`abort`,n))})}function yE(e,t){if(e===void 0)return()=>void 0;let n=t.bind(void 0);return e.aborted?(n(),()=>void 0):(e.addEventListener(`abort`,n,{once:!0}),e.removeEventListener.bind(e,`abort`,n))}function bE(e,t,n){return e===`deadline_exceeded`?new pS({limitMs:t,elapsedMs:n??0}):new hS({by:`caller`})}function xE(e){return Ma.pipe(we(t=>t-e))}function SE(e){return Ma.pipe(T(t=>sr(()=>{let n=e.executionId,r=new AbortController,i=t,a={kind:`waiting`},o,s=e=>{o===void 0&&a.kind!==`refused`&&(o=e,r.abort())},c=t=>{let n=new mS({capacity:e.policy.capacity,waitedMs:Math.max(0,t-i)});return a={kind:`refused`,failure:n},n},l=()=>{if(r.signal.aborted)throw bE(o,e.policy.timeoutMs)},u=yE(e.callerSignal,()=>{s(`cancelled`)}),d=t+e.policy.timeoutMs,f={executionId:n,deadlineAt:d,signal:r.signal,images:e.images};e.toolCallId!==void 0&&Object.assign(f,{toolCallId:e.toolCallId}),e.output!==void 0&&Object.assign(f,{output:e.output});let p=Object.freeze(f),m=sr(()=>Ma.pipe(T(u=>a.kind===`refused`?v(a.failure):(u>=d&&s(`deadline_exceeded`),r.signal.aborted?xE(t).pipe(T(t=>v(bE(o,e.policy.timeoutMs,t)))):u>=i+e.policy.waitMs?v(c(u)):(a={kind:`admitted`},e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:_E(e.createBindings(p),l),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(Br(e=>Ki(e)?Zt(e):v(OS(Ji(e)))))))))),ee=t=>C_(t).pipe(di({duration:e.policy.abortGraceMs,orElse:()=>v(o===`deadline_exceeded`?new pS({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new hS({by:`caller`,acknowledged:!1}))})),te,ne=!1,re=r=>(ne=!0,xE(t).pipe(T(t=>{let i=OS(r),a=i instanceof pS?new pS({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=CS(a,n),s=si(w(),bn()).parse(AS(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??rE(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=sr(()=>e.sandbox.onFailure?.(c)??C);return nt(`sandbox_failure`,c).pipe(fr({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),g(o._tag===`Unknown`?po(mo(fo(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(g(nt(`sandbox_health_alert`).pipe(fr({ref:n,adapter:c.adapter})))):C),g(l.pipe(Br(e=>nt(`sandbox_failure_record_failed`,e)))),Ar(o))})));return b(function*(){if(r.signal.aborted){let n=yield*xE(t);return yield*v(bE(o,e.policy.timeoutMs,n))}i=yield*Ma,te=yield*e.backingWork.start(m);let n=yield*Ma,l=jn(Math.max(0,i+e.policy.waitMs-n)).pipe(g(Ma),T(e=>a.kind===`admitted`?Nt:a.kind===`refused`?x({kind:`busy`,failure:a.failure}):r.signal.aborted?x({kind:`cancelled`}):e>=d?(s(`deadline_exceeded`),x({kind:`deadline`})):x({kind:`busy`,failure:c(e)}))),u=yield*Dn(x_(te).pipe(we(e=>Object.freeze({kind:`settled`,exit:e}))),Dn(jn(Math.max(0,d-n)).pipe(g(y(()=>(s(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),Dn(vE(r.signal).pipe(Ar(Object.freeze({kind:`cancelled`}))),l))),f=a.kind===`refused`?a.failure:u.kind===`busy`?u.failure:void 0;if(f!==void 0)return yield*ee(te).pipe(g(v(f)));if(u.kind===`settled`&&o===void 0)return yield*xe(u.exit,{onFailure:Zt,onSuccess:e=>oi({try:()=>gE(e),catch:t=>DS(t)?t:new bS({kind:kS(e),rawCause:t})})});u.kind===`deadline`&&s(`deadline_exceeded`);let p=yield*xE(t);return yield*ee(te).pipe(g(v(bE(o,e.policy.timeoutMs,p))))}).pipe(ke(()=>(s(`cancelled`),(te===void 0?C:C_(te).pipe(Xr(e.policy.abortGraceMs),mn)).pipe(g(sr(()=>ne?C:re(new hS({by:`operator`})).pipe(mn))))))).pipe(yn(e=>re(e).pipe(T(v))),rr(y(u)))})))}var CE=ym(()=>I([sm,om,cm,N,M,Bh,jm(AbortSignal),F(CE),wE])),wE=fm(M,CE);function TE(e){return O(wE)(e)}var EE=new Map([[`openai`,`OpenAI`],[`openai-codex`,`OpenAI`],[`anthropic`,`Anthropic`],[`cloudflare-workers-ai`,`Cloudflare Workers AI`]]),DE=fm(M,Qh),OE=O(P({samplingParams:k(DE),samplingParamsByThinkingLevel:k(P({off:k(DE),minimal:k(DE),low:k(DE),medium:k(DE),high:k(DE),xhigh:k(DE),max:k(DE)}))}));function kE(e){return{...e,...OE(e)}}function AE(e){if(e===void 0)return;let{onPayload:t,onProviderStreamEvent:n,onResponse:r,...i}=e,a={...i};return t!==void 0&&(a.onPayload=(e,n)=>t(TE(e),kE(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(TE(e),kE(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,kE(t))),a}function jE(e){let t=new Map,n=[],r=e=>{for(let r of t.values())n.push({role:`toolResult`,toolCallId:r.id,toolName:r.name,content:[{type:`text`,text:`Tool execution interrupted.`}],isError:!0,timestamp:e});t.clear()};for(let i of e.messages){if(i.role===`toolResult`){t.delete(i.toolCallId)&&n.push(i);continue}if(i.role!==`system`&&r(i.timestamp),i.role===`assistant`){if(i.stopReason===`error`||i.stopReason===`aborted`)continue;for(let e of i.content)e.type===`toolCall`&&t.set(e.id,e)}n.push(i)}return r(e.messages.at(-1)?.timestamp??0),hi({...e,messages:n})}var ME=async(e,t,n)=>{let{streamSimple:r}=await gi(async()=>{let{streamSimple:e}=await import(`./compat-CfHbT1sC.js`);return{streamSimple:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17]));return r(e,jE(t),AE(n))},NE=P({error:P({code:A(M),type:A(M)})});Wp(P({type:j(`response.failed`),response:NE})),Wp(U(NE)),Wp(P({type:j(`error`),status:A(N.check(nh(),eh({minimum:100,maximum:599}))),code:A(M),error:A(NE.fields.error)})),O(jm(Uint8Array)),Wp(Ih.check(eh({minimum:0,maximum:60}))),Wp(Ih.check(nh(),eh({minimum:0,maximum:864e10}))),Wp(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Wp(j(`rejected`)),Wp(j(`0`)),Wp(qh),Wp(P({type:j(`error`),error:P({type:j(`overloaded_error`)})}));var PE=[/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,/context window exceeded/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,/^(?:[\w -]+ API error \(413\):|413(?:\s|:|$))/i],FE=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,IE=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function LE(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!IE.some(t=>t.test(e.errorMessage))&&(PE.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&FE.test(e.errorMessage))||t&&e.stopReason===`stop`&&e.usage.input+e.usage.cacheRead>t||t&&e.stopReason===`length`&&e.usage.output===0&&e.usage.input+e.usage.cacheRead>=t*.99)}function RE(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function zE(e){return new RegExp(e.join(`|`),`i`)}var BE=zE([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`,`subscription_sharing_workplace_individual_usage_limit_exceeded`,`"code"\\s*:\\s*"?1308(?![0-9])`]),VE=zE([`overloaded`,`server_busy`,`servers are currently busy`,`currently experiencing high demand`,`model is at capacity`,`rate.?limit`,`too many requests`,`(?<![a-z0-9])(?:429|500|502|503|504|520|524)(?![a-z0-9])`,`service.?(?:is.?)?(?:temporarily.?)?unavailable`,`server.?error`,`internal.?error`,`provider.?returned.?(?:an.?)?error`,`exceeded request buffer limit while retrying upstream`,`unable to forward upstream`,`upstream.?request.?failed`,`upstream_stream_read_error`,`stream was interrupted`,`http/?2 stream failed`,`network.?error`,`connection.?error`,`connection.?refused`,`connection.?lost`,`other side closed`,`fetch failed`,`request to \\S+ failed, reason:`,`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`,`stream disconnected before completion`,`cut short after the reply had begun`,`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`]),HE=6e4;function UE(e,t){let n=e.baseDelayMs*2**Math.max(0,t-1);return Math.min(Number.isSafeInteger(n)?n:2**53-1,e.maxAgentDelayMs??6e4)}var WE=class extends Error{constructor(){super(`Aborted`)}};function GE(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new WE);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new WE)},{once:!0})})}async function KE(e,t,n,r){let i=t?.enabled?t.maxRetries:0,a=0,o;for(;;){let s=await e();if(s.stopReason===`aborted`)return o&&await r?.onRetryFinished?.(!1,o.attempt),s;if(s.stopReason!==`error`)return o&&await r?.onRetryFinished?.(!0,o.attempt),s;if(a>=i||!qE(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=UE(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await GE(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof WE){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function qE(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!BE.test(t)&&VE.test(t)}var JE=P({provider:M,cause:I([I([P({code:j(`usage-limit-reached`),cause:k(j(`quota`)),resetAt:k(N),limit:k(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`]))}),P({code:j(`rate-limit`),retryAfterMs:k(N)}),P({code:j(`overloaded`)}),P({code:j(`provider_unavailable`),status:k(N)}),P({code:j(`provider_rejected`),status:N})]),P({code:L([`setup_required`,`tools_unsupported`,`request_failed`])})])}),YE={assign:0,create:0,clone:0,discard:0,update:0};function XE(e){return QE(e,null)}function ZE(e){return QE(typeof e,`object`)&&!XE(e)}function QE(e,t){return e===t}function $E(e){return QE(e,`__proto__`)||QE(e,`constructor`)||QE(e,`prototype`)}function eD(e,t){return $E(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function tD(e){return Object.getOwnPropertyNames(e)}var nD={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function rD(){return nD}function iD(e){return rD().immutableTypes?Object.freeze(e):e}function aD(e,t){for(let n of Object.keys(t))Object.defineProperty(e,n,{configurable:!0,writable:!0,enumerable:!1,value:t[n]});return e}function oD(e,t){return{...e,...t}}function sD(e,t,n={}){YE.create+=1;let r=oD(t,n);return iD(rD().enumerableKind?oD(r,e):aD(r,e))}function cD(e){return ZE(e)}function lD(e){return cD(e)&&eD(e,`~optional`)}function uD(e){return tD(e).filter(t=>!lD(e[t]))}function dD(e,t={}){let n=uD(e);return sD({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var fD;(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`})(fD||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var pD=new Float64Array(1);new DataView(pD.buffer),new Uint8Array(pD.buffer),new TextEncoder;var mD=`-?(?:0|[1-9][0-9]*)`,hD=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function gD(e){return sD({"~kind":`String`},{type:`string`},e)}var _D=`^${mD}$`;`${hD}`;function vD(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var yD=[...vD(97,122),...vD(65,90)],bD=[`0`,...vD(49,57)];[...bD],[...yD,...bD],[...bD],new RegExp(_D);var xD={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},SD={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},CD=1e3,wD=Symbol(`Mule model limit`),TD=Symbol(`Mule model attempt limit`);function ED(e,t){return LE(e,t)}var DD=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),OD=(e,t)=>({kind:e,value:`mule_${e}_${ig()}`,parent:t}),kD=()=>C;function AD(e,t){let n={role:`toolResult`,toolCallId:e.id,toolName:e.name,content:t.content,isError:t.isError,timestamp:Date.now()};return t.usage!==void 0&&(n.usage=t.usage),n}var jD=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function MD(e,t){return e.find(e=>e.descriptor.name===t.name)}function ND(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function PD(e,t,n,r,i){let a=OD(`tool_call`,r);return b(function*(){if(yield*i({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:a,call:t}),e===void 0){let e=jD(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*ND(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*zr(e.prepare(t));if(Ae(o)){let e=jD(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*ND(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function FD(e,t,n,r){return b(function*(){let i,a;yield*yy(iy(e.tool.execute()),o=>Ae(o)?(a=o.failure,C):i===void 0?o.success.type===`result`?(i=o.success.result,C):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):C);let o=a===void 0?i??jD(`Tool "${e.call.name}" returned no result`):jD(a.message),s={call:e.call,identity:e.identity,result:o};return yield*ND(s,t,n,r),s})}function ID(e,t,n,r){let i=AD(e.call,e.result),a=OD(`tool_result`,e.identity);return b(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:a,value:i}),yield*r({type:`message_end`,run:t,turn:n,message:a,value:i,data:e.result.data}),i})}function LD(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>MD(a,e)?.executionMode===`sequential`);return b(function*(){let t=e=>e.kind===`finalized`?x(e.value):FD(e,n,r,i),s=o?yield*Zr(e,e=>T(PD(MD(a,e),e,n,r,i),t)):yield*b(function*(){let o=yield*Zr(e,e=>PD(MD(a,e),e,n,r,i));return yield*Hn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*Zr(s,e=>ID(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var RD=e=>jD(`Tool call "${e.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.`);function zD(e,t,n,r){return b(function*(){let i=yield*Zr(e,e=>b(function*(){let i=OD(`tool_call`,n),a={call:e,identity:i,result:RD(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*ND(a,t,n,r),a}));return yield*Zr(i,e=>ID(e,t,n,r))})}function BD(e,t){return pn({try:n=>{let r=()=>{t.abort(n.reason)};return n.aborted?r():n.addEventListener(`abort`,r,{once:!0}),Promise.resolve(e.next()).finally(()=>{n.removeEventListener(`abort`,r)})},catch:e=>DD(`model`,`Pi model stream failed`,e)})}function VD(e,t,n){return e.pipe(di({duration:t,orElse:()=>v(n())}))}function HD(e,t,n,r,i,a){let o=OD(`message`,r),s,c={started:!1,terminal:void 0};return nr(b(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??SD.firstEventMs,SD.firstEventMs),d=Math.min(l?.attemptMs??SD.attemptMs,SD.attemptMs),f=Math.min(l?.outputBytes??SD.outputBytes,SD.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*v(DD(`model`,`Model stream limits must be positive safe integers`));let p=Date.now(),m=p,ee=0,te=0,ne=new TextEncoder,re=!1,ie=e=>DD(`model`,`Model ${e} after ${String(Date.now()-p)} ms (max provider gap ${String(Math.max(ee,Date.now()-m))} ms, streamed ${String(te)} bytes)${e===`attempt timed out`?`. Write big content with file tools instead of one giant response.`:``}`,e===`attempt timed out`?TD:wD),ae=t=>{let n=Date.now()-p,r=d-n,i=Math.min(re?SD.idleMs:u,e.modelStreamIdleTimeoutMs??SD.idleMs)-(Date.now()-m),a=r<=i?`attempt timed out`:re?`stream timed out (silence)`:`first event timed out`;return VD(t,Math.max(0,Math.min(r,i)),()=>ie(a))},oe=new AbortController,se={};yield*Tr(()=>pn({try:()=>{if(oe.abort(`Mule model scope closed`),se.response===void 0)return Promise.resolve(!0);let e=se.response.then(async e=>{await Promise.all([se.iterator?.return?.(),e.result()])},()=>void 0);return new Promise(t=>{let n=setTimeout(()=>{t(!1)},CD);e.then(()=>{clearTimeout(n),t(!0)},()=>{clearTimeout(n),t(!1)})})},catch:e=>DD(`model`,`Pi model stream failed`,e)}).pipe(Lt(()=>!1),T(t=>t?C:e.onUndrained??C)));let ce=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,le={...e.streamOptions,maxRetries:0,signal:oe.signal};ce!==void 0&&(le.apiKey=ce);let ue=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*i({type:`model_prompt`,run:n,turn:r,attempt:a,systemPrompt:ue}));let de={systemPrompt:ue,messages:t},fe=(e.tools??[]).map(e=>e.descriptor);fe.length>0&&(de.tools=fe);let pe=yield*ae(pn({try:()=>{let t=e.stream??ME;return se.response=Promise.resolve(t(e.model,jE(de),le)),se.response},catch:e=>DD(`model`,`Pi model stream could not start`,e)})),me=pe[Symbol.asyncIterator]();se.iterator=me;let he=e=>{let a=Date.now();if(ee=Math.max(ee,a-m),m=a,re=!0,(e.type===`text_delta`||e.type===`thinking_delta`||e.type===`toolcall_delta`)&&(te+=ne.encode(e.delta).byteLength,te>f))return v(ie(`output limit exceeded`));switch(`partial`in e&&(s=e.partial),e.type){case`start`:return t.push(e.partial),c.started=!0,i({type:`message_start`,run:n,turn:r,message:o,value:e.partial});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`:return c.started&&(t[t.length-1]=e.partial),i({type:`message_update`,run:n,turn:r,message:o,value:e.partial,event:e});case`done`:return c.terminal=e.message,C;case`error`:return c.terminal=e.error,C}},ge=()=>ae(BD(me,oe)),_e=yield*ge();for(;!_e.done;)yield*he(_e.value),_e=yield*ge();let ve=c.terminal??(yield*ae(pn({try:()=>pe.result(),catch:e=>DD(`model`,`Pi model stream did not settle`,e)})));return c.started?t[t.length-1]=ve:(t.push(ve),yield*i({type:`message_start`,run:n,turn:r,message:o,value:ve})),{message:ve,identity:o}}).pipe(yn(l=>{if(l.cause!==wD&&l.cause!==TD)return v(l);let u={role:`assistant`,content:s?.content??[],api:e.model.api,provider:e.model.provider,model:e.model.id,usage:s?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,timestamp:Date.now(),errorMessage:e.retry?.enabled&&a>e.retry.maxRetries?`The model failed ${String(a)} times on this conversation: ${l.message}`:l.message};return b(function*(){return c.started?t[t.length-1]=u:(t.push(u),yield*i({type:`message_start`,run:n,turn:r,message:o,value:u})),{identity:o,message:u,limitReached:!0,attemptTimedOut:l.cause===TD}})})))}function UD(e,t,n,r,i,a){return b(function*(){let o=e.retry===void 0?void 0:{...e.retry};if(o?.enabled&&[o.maxRetries,o.baseDelayMs,o.maxAgentDelayMs??6e4].some(e=>!Number.isSafeInteger(e)||e<0))return yield*v(DD(`model`,`Retry policy requires non-negative safe-integer counts and delays`));let s,c=Math.min(o?.maxRetries??0,a?.maxAttempts??1/0),l=a===void 0?0:a.attempt+ +(a.phase===`dispatched`),u=a?.attempt??0,d=0,f=!1,p=a?.message?.errorMessage,m=t=>e.onRetry===void 0?C:e.onRetry(t),ee=(e,t)=>b(function*(){f=!0,yield*m(t===void 0?{type:`retry_finished`,run:n,turn:r,attempt:u,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:u,success:e,finalError:t})}),te=e=>b(function*(){yield*jn(Math.max(0,e-Date.now())),yield*m({type:`retry_attempt_started`,run:n,turn:r,attempt:u})}),ne=(e,t)=>b(function*(){if(o===void 0)return yield*v(DD(`model`,`Retry policy is unavailable`));u++,p=e;let i=Math.max(UE(o,u),t!==void 0&&Number.isSafeInteger(t)&&t>=0&&t<=6e4?t:0),a=Math.min(1e3,i/4,Math.max(0,6e4-i)),s=i+Math.floor(Math.random()*a),l=Date.now()+s;return{type:`retry_scheduled`,run:n,turn:r,attempt:u,maxAttempts:c,delayMs:s,dueAt:l,errorMessage:p}});return yield*b(function*(){if(a!==void 0){if(!Number.isSafeInteger(a.attempt)||a.attempt<0||a.maxAttempts!==void 0&&(!Number.isSafeInteger(a.maxAttempts)||a.maxAttempts<0)||a.phase===`waiting`&&(!Number.isSafeInteger(a.dueAt)||a.dueAt<0))return yield*v(DD(`model`,`Invalid model retry continuation`));if(!o?.enabled||u>c||a.phase===`dispatched`&&u>=c)return yield*ee(!1,`Model retry budget exhausted after restart`),a.message===void 0?yield*v(DD(`model`,`Model retry budget exhausted after restart`)):{message:a.message};if(a.phase===`waiting`)yield*te(a.dueAt);else{let e={...yield*ne(`Model request interrupted by a restart`),delayMs:0,dueAt:Date.now()};yield*m(e),yield*te(e.dueAt)}}for(;;){if(s!==void 0){let e=t.indexOf(s.message);e!==-1&&t.splice(e,1)}let a=yield*HD(e,t,n,r,i,++l);s=a;let p=a.message,ee=a.attemptTimedOut===!0&&d>0;a.attemptTimedOut&&d++;let re;if(p.stopReason===`error`&&o?.enabled&&u<c&&!ee&&(yield*oi({try:()=>a.limitReached===!0||e.retryable(p),catch:e=>DD(`model`,`Typed model retry decision failed`,e)}))){let t=yield*oi({try:()=>e.retryAfterMs?.(p),catch:e=>DD(`model`,`Model retry delay observation failed`,e)});re=yield*ne(p.errorMessage??`Unknown error`,t)}if(re===void 0&&(p.stopReason===`error`||u>0)){let e={type:`retry_finished`,run:n,turn:r,attempt:u,success:p.stopReason!==`error`&&p.stopReason!==`aborted`};re=p.stopReason===`error`&&p.errorMessage!==void 0?{...e,finalError:p.errorMessage}:e}if(yield*i({type:`message_end`,run:n,turn:r,message:a.identity,value:p,retry:re}),re?.type===`retry_finished`&&(f=!0),re!==void 0&&u>0&&(yield*m(re)),re?.type!==`retry_scheduled`)return s;yield*te(re.dueAt)}}).pipe(ke(()=>u===0||f?C:ee(!1,p)))})}var WD=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function GD(e,t,n,r,i,a){return Zr(e,e=>b(function*(){let o=OD(`message`,i);t.push(e),n.push(e),yield*a({type:`message_start`,run:r,turn:i,message:o,value:e}),yield*a({type:`message_end`,run:r,turn:i,message:o,value:e})})).pipe(mn)}function KD(e,t,n,r,i,a,o,s){return b(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*GD(a,t,n,r,i,o);let c=yield*UD(e,t,r,i,o,s),l=WD(c.message)!==`completed`,u=c.message.content.filter(e=>e.type===`toolCall`),d=u.length===0||l?{messages:[],terminate:!1}:c.message.stopReason===`length`?{messages:yield*zD(u,r,i,o),terminate:!1}:yield*LD(u,e,r,i,o);t.push(...d.messages),n.push(c.message,...d.messages),yield*o({type:`turn_end`,run:r,turn:i,message:c.message,toolResults:d.messages});let f={message:c.message,toolResults:d.messages,terminate:d.terminate};return c.limitReached&&c.message.errorMessage!==void 0?{...f,modelLimitReason:c.message.errorMessage}:f})}function qD(e,t,n,r,i,a){let o=OD(`turn`,i);return b(function*(){if(WD(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*Zr(t.tools,n=>b(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=MD(e.tools??[],n.call),s;if(t.message.stopReason!==`length`&&(n.state===`pending`||n.state===`started`&&n.replay===`safe`&&r?.replay===`safe`)){let e=yield*PD(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*FD(e,i,o,a)}else s={call:n.call,identity:OD(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?RD(n.call):jD(`Interrupted by a restart; it may or may not have completed; check before retrying.`)},yield*a({type:`tool_execution_start`,replay:`unsafe`,run:i,turn:o,toolCall:s.identity,call:s.call}),yield*ND(s,i,o,a);return{message:yield*ID(s,i,o,a),terminate:s.result.terminate===!0,recorded:!1}})),c=s.filter(({recorded:e})=>!e).map(({message:e})=>e);return n.push(...c),r.push(...c),{message:t.message,toolResults:s.map(({message:e})=>e),terminate:s.length>0&&s.every(({terminate:e})=>e)}})}function JD(e,t,n,r){return b(function*(){if(e.shouldStopAfterTurn!==void 0&&(yield*e.shouldStopAfterTurn({message:t.message,toolResults:t.toolResults,context:n,newMessages:r})))return{continue:!1,pending:[]};let i=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()];if(t.message.content.some(e=>e.type===`toolCall`)&&!t.terminate||i.length>0)return{continue:!0,pending:i};let a=e.getFollowUpMessages===void 0?[]:[...yield*e.getFollowUpMessages()];return{continue:a.length>0,pending:a}})}function YD(e,t,n,r,i,a,o){return b(function*(){yield*a({type:`run_end`,run:e,terminal:t,outcome:i});let s={status:i,run:e,terminal:t,message:n,messages:r};return o===void 0?s:{...s,modelLimitReason:o}})}function XD(e,t=kD){return b(function*(){let n=yield*j_(1),r={started:!1,ended:!1},i=e=>sr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(In(()=>y(()=>{e.type===`run_start`&&(r.started=!0)}))),a=OD(`run`),o=OD(`terminal`,a);return yield*QD(e,i,a,o).pipe(Ne(e=>{let t=ZD(e);return!r.started||r.ended||t===void 0?C:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Ve)}))})}function ZD(e){if(ca(e))return;if(Ki(e.cause))return`cancelled`;let t=Xi(e.cause);if(!(Nr(t)&&t.value.phase===`listener`))return`failed`}function QD(e,t,n,r){return b(function*(){let i=[...e.messages],a=[],o=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()],s,c;yield*t({type:`run_start`,run:n});let l=e.resume?.kind===`retry`?e.resume:void 0;if(e.resume?.kind===`assistant`){let s=yield*qD(e,e.resume,i,a,n,t),c=WD(s.message),l=c===`completed`?yield*JD(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*YD(n,r,s.message,a,c,t);o.push(...l.pending)}do{let u=yield*KD(e,i,a,n,OD(`turn`,n),o,t,l);l=void 0,s=u.message;let d=WD(u.message);if(d!==`completed`)return yield*YD(n,r,u.message,a,d,t,u.modelLimitReason);if(e.prepareNextTurn!==void 0&&!u.terminate&&u.message.content.some(e=>e.type===`toolCall`)){let t=yield*e.prepareNextTurn({message:u.message,toolResults:u.toolResults,context:i,newMessages:a});t!==void 0&&i.splice(0,i.length,...t)}let f=yield*JD(e,u,i,a);o=[...f.pending],c=f.continue}while(c);return yield*YD(n,r,s,a,`completed`,t)})}var $D={run:XD},eO=class{#e=new Map;#t;constructor(e=8){this.#t=e}push(e,t){let n=this.#e.get(e)??[];if(n.length>=this.#t)throw new xS({namespace:`execute`,operation:`images`,cause:{kind:`Unavailable`,message:`Image collector cap reached for this execution (max ${String(this.#t)} images). Process images one at a time or write them to files.`}});let r=`img_${String(n.length)}`;return n.push(Object.freeze({...t})),this.#e.set(e,n),r}drain(e){let t=this.#e.get(e);return t===void 0?[]:(this.#e.delete(e),t)}dispose(e){this.#e.delete(e)}},tO=8192,nO=tO*4,rO=new TextEncoder,iO=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),aO=class e{wake;#e={stdout:{decoder:iO(),pending:new Uint8Array},stderr:{decoder:iO(),pending:new Uint8Array}};#t=iO();#n=Array.from({length:tO},()=>void 0);#r=0;#i=0;#a=0;#o=0;#s=0;#c=0;#l=!1;#u=!1;constructor(e){this.wake=e}static make(){return Vg({capacity:1,strategy:`dropping`}).pipe(we(t=>new e(t)))}write(e,t){if(this.#u||t.length===0)return;let n=this.#e[e];this.#c+=t.length;for(let e=0;e<t.length;e+=nO){let r=t.subarray(e,e+nO),i=n.decoder.decode(r,{stream:!0}),a=new Uint8Array(n.pending.length+r.length);a.set(n.pending),a.set(r,n.pending.length);let o=this.#f(a);n.pending=a.slice(a.length-o),this.#h(i,a.length-o,a)}this.#l=!0,Gg(this.wake,void 0)}#d(e,t){let n=this.#t.decode(e.subarray(0,t),{stream:!0});return this.#t.decode(),n}#f(e){for(let t=1;t<=Math.min(3,e.length);t++){let n=e.subarray(e.length-t);if(this.#d(n,n.length).length===0)return t}return 0}#p(){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);this.#n[this.#r]=void 0,this.#r=(this.#r+1)%tO,this.#i--,this.#a-=e.textBytes,this.#o-=e.newlines,this.#s+=e.rawBytes}#m(e,t,n){let r=e.raw;if(r===null){this.#p();return}let i=e=>{let i=this.#d(r,e);return rO.encode(i).length>=t&&i.split(`
|
|
19
|
+
`).length-1>=n},a=Math.min(r.length,Math.max(4,t));for(;a<r.length&&!i(a);)a=Math.min(r.length,a*2);let o=0;for(;o<a;){let e=Math.floor((o+a)/2);i(e)?a=e:o=e+1}let s=this.#d(r,o);if(s.length===e.text.length){this.#p();return}let c=o-this.#f(r.subarray(0,o)),l=rO.encode(s).length,u=s.split(`
|
|
20
|
+
`).length-1;e.raw=r.slice(c),e.text=this.#d(e.raw,e.raw.length),e.rawBytes-=c,e.textBytes-=l,e.newlines-=u,this.#a-=l,this.#o-=u,this.#s+=c}#h(e,t,n){if(e.length===0)return;let r={text:e,raw:n,rawBytes:t,textBytes:rO.encode(e).length,newlines:e.split(`
|
|
21
|
+
`).length-1};for(this.#i===tO&&this.#p(),this.#n[(this.#r+this.#i)%tO]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>tO||this.#o>=200;){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);let t=Math.max(0,this.#a-tO),n=Math.max(0,this.#o-199);e.textBytes<=t||e.newlines<n?this.#p():this.#m(e,t,n)}}snapshot(){let e=``;for(let t=0;t<this.#i;t++){let n=this.#n[(this.#r+t)%tO];if(n===void 0)throw Error(`Missing output ring entry`);e+=n.text}return{tail:e,droppedBytes:this.#s,totalBytes:this.#c}}#g(){if(!this.#l)return;this.#l=!1;let{tail:e,...t}=this.snapshot();return{type:`update`,result:{isError:!1,content:[{type:`text`,text:e}],data:t}}}finish(){if(!this.#u){this.#u=!0;for(let e of[this.#e.stdout,this.#e.stderr]){let t=e.decoder.decode();this.#h(t,e.pending.length,null),e.pending=new Uint8Array,t.length>0&&(this.#l=!0)}return this.#g()}}get updates(){return Qv(this.wake).pipe(ry(()=>jn(`100 millis`).pipe(we(()=>this.#u?void 0:this.#g()))),fy(e=>e!==void 0))}dispose(){this.#u=!0,this.#n.fill(void 0),this.#r=this.#i=this.#a=this.#o=0,this.#c=this.#s=0,this.#l=!1;for(let e of[this.#e.stdout,this.#e.stderr])e.decoder.decode(),e.pending=new Uint8Array}},oO=P({code:M}),sO='Inside execute, call forage.search, forage.list or forage.describe to discover operations and inspect their inputs. forage is available only there, not as a separate tool. Run async JavaScript in the sandbox. Each call is a fresh sandbox, not a REPL: nothing survives between calls, so redefine helpers or persist state to a file. Never shadow injected module names with local bindings. Find operations with await forage.search({ query }) using one short keyword such as read or shell, or page them all with forage.list({limit:50}), optionally by namespace, until nextCursor is null. Inspect input with await forage.describe({ path }) before calling; describe known paths directly. Call an operation as await env.<path>({ ... }) with the exact dotted path, for example await env.computers.local.exec({ command: "pwd" }); a bare computers.local.exec is not defined. Put multiline shell commands in a template literal. Code is JavaScript first, so double each backslash the shell needs (`\\\\(` passes `\\(`; `\\(` becomes `(`). For file edits, prefer Files operations when available. Explicitly return the final value. Before treating a shell or process result as success, check status, exitCode and stderr.';function cO(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await yT(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function lO(e,t,n,r){let i=0,a=new Map;for(let o of e){let e=o.namespace,s=o.name,c=a.get(e)??new Map;c.set(s,e=>cO(o,Object.freeze({...t,operationOrdinal:i++}),n,r)(e)),a.set(e,c)}return Object.freeze(Object.fromEntries([...a].map(([e,t])=>[e,Object.freeze(Object.fromEntries(t))])))}function uO(e,t){let n=e.safeParse(t);if(!n.success)throw new lS(n.error.issues);return n.data}function dO(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(uO(Kb,t))),describe:t=>Promise.resolve().then(()=>e.describe(uO(Gb,t))),search:t=>Promise.resolve().then(()=>e.search(uO(Wb,t)))})}function fO(e,t,n,r,i){return Object.freeze({...lO(e,n,r,i),forage:dO(t)})}function pO(e,t,n,r,i,a,o,s){let c=n.execution??fE(void 0),l=new eO,u=(u,d,f,p,m)=>SE({executionId:u,toolCallId:p,output:m,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>fO(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>sr(()=>{let n=ig();return u(n,e,t).pipe(rr(y(()=>{l.dispose(n)})))}),f=(e,t,n)=>sr(()=>{let r=ig(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(Tt({onSuccess:e=>x(mO({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof yS&&t.length>0?x(mO({text:wS(e),isError:!0},t)):v(hO(e))}}),rr(y(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:sO,parameters:dD({code:gD()},{additionalProperties:!1})},prepare:e=>Hp(oO)(e.arguments).pipe(we(({code:t})=>({execute:()=>ty(b(function*(){let n=yield*aO.make();yield*Tr(()=>y(()=>{n.dispose()}));let r=yield*Yn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return dy(n.updates,Rv(x_(r)).pipe(ay(e=>{let t=n.finish();return cy(Xv(t===void 0?[]:[t]),Rv(e))})),{haltStrategy:`right`}).pipe(gy(e=>e.type===`result`))}))})),ut(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function mO(e,t){let n=t.map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})),r=[{type:`text`,text:e.text},...n];return t.length===0?{type:`result`,result:{content:r,isError:e.isError}}:{type:`result`,result:{content:r,data:{images:t.map(e=>({bytes:e.bytes,mimeType:e.mimeType,path:e.path}))},isError:e.isError}}}function hO(e){let t={_tag:`MuleError`,phase:`tool`,message:DS(e)?wS(e):e.message};return e instanceof mS?{...t,cause:e}:t}function gO(e,t){return e<t?-1:+(e>t)}var _O=128,vO=_(()=>w().min(1).max(160)),yO=_(()=>Qt({version:w().min(1).max(160),modules:Er(xt())})),bO=1e3;function xO(e){if(e.length>_O)throw new G(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>gO(e.id,t.id)),n=new Set;for(let e of t){if(!vO.safeParse(e.id).success)throw new G(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new G(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function SO(e){if(e>bO)throw new G(`Candidate module count exceeds bound`)}function CO(e,t){let n=yO.safeParse(e);if(!n.success)throw new G(`Capability source snapshot must have a non-empty bounded version`);SO(t+n.data.modules.length)}function wO(e,t,n,r,i){return ne(a=>b(function*(){let o=t=>pn({try:()=>t.release(),catch:()=>new cS(e.id,`release`)}).pipe(yn(e=>y(()=>{n.push(e)}))),s=yield*oi({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(i===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:i}).then(e=>ra(e),()=>aa(new cS(e.id,`acquire`)))}},catch:()=>new cS(e.id,`acquire`)});yield*Da(t,qt(()=>s.outcome).pipe(T(e=>ca(e)?o(e.value):C)));let c=yield*a(qt(()=>s.outcome)).pipe(ke(()=>y(()=>{s.controller.abort()})));return la(c)?yield*Zt(c.cause):c.value}))}function TO(e){return b(function*(){let t=yield*oi({try:()=>xO(e.sources),catch:e=>e instanceof G?e:new G(`Capability sources are invalid`)});yield*oi({try:()=>{SO(e.modules.length)},catch:e=>e instanceof G?e:new G(`Static capability modules are invalid`)});let n=yield*Ca(),r=[],i=!1,a=[...e.modules],o=[];return yield*b(function*(){for(let s of t){let t=yield*wO(s,n,r,()=>{i=!0},e.session);yield*oi({try:()=>{CO(t.snapshot,a.length)},catch:e=>e instanceof G?e:new G(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*oi({try:()=>nE(a,o),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=pO(s.operations,s.catalog,e.sandbox,c,s.moduleAliases,s.namespacePaths,e.session?.sessionId??null,e.access),u=!1;return Object.freeze({compiled:s,executeDoor:l,isStale:()=>i,close:()=>b(function*(){u||(u=!0,yield*c.awaitIdle,yield*Aa(n,sa));let e=r[0];e!==void 0&&(yield*v(e))})})}).pipe(Ne(e=>ca(e)?C:Aa(n,e)))})}var EO=2;function DO(e){return b(function*(){for(let t=0;t<EO;t+=1){let t=yield*TO(e);if(!t.isStale())return t;yield*t.close()}return yield*v(new cS(void 0,`stale`))})}function OO(e,t,n){return ne(r=>r(e.take(1)).pipe(T(()=>y(t).pipe(rr(e.release(1)))),T(n)))}function kO(e,t){return yt(e.candidate.close().pipe(Tt({onFailure:t=>ya(e.settled,t).pipe(g(v(t))),onSuccess:()=>ba(e.settled,void 0).pipe(g(y(()=>{t.delete(e)})))})))}function AO(e,t){return e.runCleanup?kO(e.installed,t):_a(e.installed.settled)}function jO(e,t){return Hn(e.map(e=>AO(e,t).pipe(Ln)),{concurrency:`unbounded`}).pipe(T(e=>{let t=e.find(la);return t===void 0?C:Zt(t.cause)}))}function MO(e){return b(function*(){let t=yield*j_(1),n=yield*oi({try:()=>fE(e.execution),catch:e=>e instanceof G?e:new G(`Execution policy is invalid`)}),r=yield*pE(n.capacity),i=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:n}),a=e.modules.length===0&&e.sources.length>0?void 0:yield*oi({try:()=>nE(e.modules),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)}),o=yield*oi({try:()=>Object.freeze(e.tools.map(t=>ST(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof G?e:new G(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*DO({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*ga(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>OO(t,()=>(l=!0,[...c].map(e=>{e.retired=!0;let t=e.leases===0&&!e.closing;return t&&(e.closing=!0),{installed:e,runCleanup:t}})),e=>jO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({acquire:()=>t.withPermits(1)(b(function*(){if(l)return yield*v(new sS);if(s===void 0||s.candidate.isStale()){let t=yield*DO({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*ga(),leases:0,retired:!1,closing:!1};s=a,c.add(a),n!==void 0&&(n.retired=!0,n.leases===0&&!n.closing&&(n.closing=!0,yield*kO(n,c)))}let n=s;n.leases+=1;let a,u=()=>OO(t,()=>{if(a!==void 0)return a?{installed:n,runCleanup:!1}:void 0;if(--n.leases,a=n.retired&&n.leases===0&&!n.closing,a)return n.closing=!0,{installed:n,runCleanup:!0}},e=>e===void 0?C:AO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({revision:n.candidate.compiled.revision,catalog:n.candidate.compiled.catalog,executeDoor:n.candidate.executeDoor,effectExecuteTool:n.candidate.executeDoor.effectTool,tools:o,release:u})})),close:u})})}function NO(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>yt(pn({try:()=>e.execute(t,n),catch:OS}))})}function PO(e){return MO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:e.sandbox,onSandboxFailure:e.onSandboxFailure,tools:e.tools??[],access:e.access??{}}).pipe(we(e=>Object.freeze({acquire:()=>e.acquire().pipe(we(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function FO(e,t){let n=await Kn(e,t);if(ca(n))return n.value;let r=Xi(n.cause);if(Nr(r))throw r.value;if(Ki(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Ji(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function IO(e){let t=await FO(Ca()),n=e.onSandboxFailure;try{let r=await FO(MO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:NO(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>qt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(Ta(t))),i=async e=>{let t=await FO(Ca());try{let n=await FO(r.acquire().pipe(Ta(t)),e?.signal===void 0?void 0:{signal:e.signal}),i;return Object.freeze({revision:n.revision,catalog:n.catalog,executeTool:n.effectExecuteTool,tools:n.tools,release:()=>(i??=FO(n.release().pipe(rr(Aa(t,sa)))),i)})}catch(e){throw await FO(Aa(t,sa)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=FO(r.close().pipe(rr(Aa(t,sa)))),a)})}catch(e){throw await FO(Aa(t,sa)),e}}var LO=ym(()=>I([om,cm,Um,M,gm(F(LO)),tm(fm(M,LO))])),RO=M.check(gh(1),yh(256)),zO=M.check(gh(1),yh(128)),BO=P({kind:j(`sandbox_failure`),ref:RO,executionId:RO,adapter:zO,buildSha:R(zO),tag:L([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:fm(M,LO),healthAlert:cm});function VO(e){return MT(e)}function HO(e){return NT(e)}var UO=Object.freeze({module:HO,operation:VO,make:IO,gate:BT,grantAs:zT}),WO=Qh,GO=4096,KO=new TextEncoder,qO=WO.check(B(e=>KO.encode(JSON.stringify(e)).byteLength<=GO)),JO=D(qO);function YO(e,t){if(em(e))return Wt(D(e)(t));let n=e[`~standard`].validate(t);if(br(n,`then`))throw new W(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function XO(e,t){let n=JO(t);if(Ae(n))throw new W(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!YO(e.schema,n.success))throw new W(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function ZO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function QO(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function $O(e){return QO({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function ek(e,t,n){dr(nt(`shiitake_operation_failed`,Lo(t)).pipe(fr({operation:e,errorKind:t instanceof Error?`error`:`non-error`,...n})))}var tk=64,nk=256,rk=new WeakMap,ik=new TextEncoder;function ak(e){let t=rk.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:ik.encode(n).byteLength});return rk.set(e,r),r}function ok(e){if(e.kind===`update`&&e.sandboxFailures!==void 0){let t={...e};return delete t.sandboxFailures,t}if(e.kind===`reset`&&e.baseline.sandboxFailures!==void 0){let t={...e.baseline};return delete t.sandboxFailures,{...e,baseline:t}}return e}function sk(e){let t=new Set,n=!1,r,i=e=>{_r(Qg(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:_r(Ug(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=sr(()=>o.closed?x(`closed`):r===void 0?o.lagged?x(`reset`):n?x(`closed`):t_(o.frames).pipe(Qa(()=>x(`closed`)),T(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=ak(e).bytes),x(e)):v(r))):v(r));return Object.freeze({take:s,checkpoint:(e=-1)=>{i(o),o.lagged=!1,o.observed=e},close:()=>{o.closed||(o.closed=!0,i(o),t.delete(o),Yg(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=ok(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=ak(t);n.bytes+o>1048576||!Gg(n.frames,t)?(i(n),n.lagged=!0,Gg(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Yg(e.frames)}}}}var ck=new WeakMap;function lk(e,t){for(let n of ck.get(e)??[])if(n.observes(t))return!0;return!1}function uk(e,t){return e===`closed`||t===`closed`?`closed`:e===`reset`||t===`reset`?`reset`:e===`durable`||t===`durable`?`durable`:e===`activity`||t===`activity`?`activity`:`progress`}function dk(e,t){if(e.pendingCount>=nk){e.pendingCount=0,e.pendingReason=void 0,e.reset=!0;return}e.pendingCount+=1,e.pendingReason=e.pendingReason===`durable`||t===`durable`?`durable`:e.pendingReason===`activity`||t===`activity`?`activity`:`progress`}function fk(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){dk(e,t);return}e.wake=void 0;try{n(t)}catch(t){ek(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function pk(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&fk(n,`activity`)}function mk(e,t,n=`durable`){let r=ck.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){ek(`owner-observation-publish`,e);continue}}function hk(e){let t=ck.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){ek(`owner-execution-change-publish`,e)}}function gk(e){let t=new Map,n=new Set,r=ck.get(e)??new Set,i=!1,a=e=>{if(e.closed)return`closed`;if(e.reset)return e.reset=!1,`reset`;if(e.pendingCount===0)return;e.pendingCount=0;let t=e.pendingReason;return e.pendingReason=void 0,t??`progress`},o=e=>{if(e.closed)return;e.closed=!0,e.pendingCount=0,e.pendingReason=void 0,e.reset=!1;let r=e.wake;e.wake=void 0,n.delete(e);let i=t.get(e.sessionId);if(i?.delete(e),i?.size===0&&t.delete(e.sessionId),r!==void 0)try{r(`closed`)}catch(e){ek(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){pk(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&pk(n,e.sessionId);let r=e.sessionId===null?n:t.get(e.sessionId);if(r!==void 0)for(let t of r)t.settlementOnly&&e.reason!==`settlement`||fk(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),ck.set(e,r),Object.freeze({register:(e,r)=>sr(()=>{if(i)return v(new W(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=tk)return v(new W(`runtime`,`rejected`,`Observation capacity is exhausted`));let s={revision:0,sessionId:e,settlementOnly:r===`settlement`,closed:!1,pendingCount:0,pendingReason:void 0,queued:!0,reset:!1,wake:void 0},c=t.get(e)??new Set;c.add(s),t.set(e,c),n.add(s);let l=y(()=>a(s)),u=$n(e=>{let t=a(s);if(t!==void 0){e(x(t));return}let n=t=>{e(x(t))};return s.wake=n,y(()=>{s.wake===n&&(s.wake=void 0)})});return x(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:y(()=>{if(!i){i=!0,r.delete(s),r.size===0&&ck.delete(e);for(let e of n)o(e)}})})}var _k=200,vk={onExcessProperty:`error`},yk=new TextEncoder,bk=H.pipe(z(V(0))),xk=M.pipe(z(gh(1)),z(B(e=>yk.encode(e).byteLength<=256)));D(P({limit:k(H.pipe(z(eh({minimum:1,maximum:_k})))),after:k(M)}),vk);var Sk=U(mm([bk,xk]));D(Sk),Qp(Sk),D(P({session_id:xk,last_activity_at:bk,state:L([`needs_you`,`running`,`errored`,`done`]),bytes:H.pipe(z(V(0)))}),vk);var Ck=O(P({extension_id:M,value_json:M})),wk=O(U(Oy)),Tk=O(ky),Ek=Qp(U(Oy));function Dk(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
22
22
|
extension_id TEXT PRIMARY KEY
|
|
23
23
|
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention (
|
|
24
24
|
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
@@ -26,22 +26,22 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
|
|
|
26
26
|
id TEXT NOT NULL,
|
|
27
27
|
value_json TEXT NOT NULL,
|
|
28
28
|
PRIMARY KEY (session_id, extension_id, id)
|
|
29
|
-
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_attention_owner ON session_attention(extension_id, session_id)`)}function
|
|
30
|
-
ON CONFLICT (session_id, extension_id, id) DO UPDATE SET value_json = excluded.value_json`,t,n,r.id,
|
|
29
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_attention_owner ON session_attention(extension_id, session_id)`)}function Ok(e,t){return e.sql.exec(`SELECT a.extension_id, a.value_json FROM session_attention a JOIN shiitake_extension_status s ON s.extension_id = a.extension_id AND s.status = 'running' JOIN session_attention_grants g ON g.extension_id = a.extension_id WHERE a.session_id = ? ORDER BY a.extension_id, a.id LIMIT ?`,t,64).toArray().map(e=>{let t=Ck(e);return Tk({...wk(t.value_json),extensionId:t.extension_id})})}function kk(e,t){return e.sql.exec(`SELECT 1 FROM session_attention a JOIN shiitake_extension_status s ON s.extension_id = a.extension_id AND s.status = 'running' JOIN session_attention_grants g ON g.extension_id = a.extension_id WHERE a.session_id = ? AND json_extract(a.value_json, '$.inbox') IS NOT 0 LIMIT 1`,t).toArray().length>0}function Ak(e,t){return Ok(e,t).some(e=>e.inbox!==!1||e.waitingOn!==void 0)}function jk(e,t,n,r){if(O(P({count:H}))(e.sql.exec(`SELECT COUNT(*) AS count FROM session_attention WHERE session_id = ? AND NOT (extension_id = ? AND id = ?)`,t,n,r.id).one()).count>=64)throw new W(`contract`,`invalid`,`Session attention capacity reached`);if(O(P({count:H}))(e.sql.exec(`SELECT COUNT(*) AS count FROM session_attention WHERE extension_id = ? AND NOT (session_id = ? AND id = ?)`,n,t,r.id).one()).count>=4096)throw new W(`contract`,`invalid`,`Extension attention capacity reached`);e.sql.exec(`INSERT INTO session_attention (session_id, extension_id, id, value_json) VALUES (?, ?, ?, ?)
|
|
30
|
+
ON CONFLICT (session_id, extension_id, id) DO UPDATE SET value_json = excluded.value_json`,t,n,r.id,Ek(r))}function Mk(e,t,n,r){e.sql.exec(`DELETE FROM session_attention WHERE session_id = ? AND extension_id = ? AND id = ?`,t,n,r)}function Nk(e,t,n){let r=O(P({session_id:M}));return e.sql.exec(`SELECT DISTINCT session_id FROM session_attention WHERE extension_id = ? AND session_id > ? ORDER BY session_id LIMIT 64`,t,n).toArray().map(e=>r(e).session_id)}function Pk(e,t){let n=O(P({extension_id:M})),r=new Set(e.sql.exec(`SELECT extension_id FROM session_attention_grants LIMIT 64`).toArray().map(e=>n(e).extension_id)),i=new Set(t),a=[];for(let t of r)i.has(t)||(e.sql.exec(`DELETE FROM session_attention_grants WHERE extension_id = ?`,t),a.push(t));for(let t of i)r.has(t)||(e.sql.exec(`INSERT INTO session_attention_grants (extension_id) VALUES (?)`,t),a.push(t));return a}var Fk=M.check(gh(1),yh(256)),Ik=262144,Lk=M.check(B(e=>new TextEncoder().encode(e).byteLength<=Ik,{message:`Mail content must be at most ${String(Ik)} UTF-8 bytes`})),Rk=P({kind:j(`agent`),agentId:Fk,sessionId:Fk}),zk=P({kind:j(`agent`),agentId:Fk,sessionId:k(Fk)}),Bk=P({kind:j(`system`),systemId:j(`hub`)}),Vk=P({itemId:Fk,kind:M.check(gh(1),yh(64)),summary:M.check(gh(1),yh(200))}),Hk=P({commandId:Fk,outcome:L([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:k(M.check(gh(1),yh(200))),waitingOnYou:k(F(Vk).check(gh(1),yh(8)))}),Uk=L([`recipient_offline`,`recipient_left`]),Wk=P({outcome:j(`undeliverable`),reason:Uk}),Gk=P({outcome:j(`accepted`),commandId:Fk});I([Hk,Wk,Gk]);var Kk=I([Hk,Gk,P({outcome:j(`undeliverable`),reason:j(`recipient_left`)})]),qk=`[redacted]`,Jk=/\b(bearer|basic)\s+[^\s"',;]+/giu,Yk=/\b((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization)["']?\s*[:=]\s*["']?)(?!(?:bearer|basic)\s)[^\s"',;&]+/giu,Xk=/[A-Za-z0-9][\w-]{23,}/gu;function Zk(e){return e.replace(Jk,`$1 ${qk}`).replace(Yk,`$1${qk}`).replace(Xk,e=>/\d/u.test(e)&&/[A-Za-z]/u.test(e)?qk:e)}function Qk(e){let t=Zk(e.replace(/[\p{Cc}\p{Zl}\p{Zp}\s]+/gu,` `).trim()).slice(0,200).trimEnd();return t.length===0?void 0:t}var $k={key:Fk,to:zk,replyTo:F(Rk),content:Lk,createdAt:N.check(V(0)),meta:k(Qh)},eA=I([P({...$k,from:Rk,reply:k(Kk)}),P({...$k,from:Bk,reply:P({outcome:j(`undeliverable`),reason:j(`recipient_offline`)})})]),tA=P({jobId:Fk,sessionId:Fk,commandFactId:Fk,recovery:A(P({maxRecoveries:H.check(V(0)),windowMs:k(H.check(Zm(0)))}))}),nA=P({work:P({sessionId:Fk,commandFactId:Fk}),mail:A(eA)}),rA=P({work:tA,delivery:L([`steer`,`followUp`]),mail:A(eA)}),iA=e=>{let t=O(rA)(e),n={sessionId:t.work.sessionId,commandFactId:t.work.commandFactId},r=t.mail===void 0?{work:n}:{work:n,mail:t.mail},i={jobId:t.work.jobId,queue:t.work.sessionId,lane:`default`,priority:+(t.delivery===`steer`),payload:r,state:`queued`};return t.work.recovery===void 0?i:{...i,recovery:t.work.recovery}},aA=e=>O(nA)(e.payload);function oA(e,t,n,r){let i=O(Fk)(t),a=O(Rk)(e.from),o=O(Gk)({outcome:`accepted`,commandId:n});return{key:`${e.key}:accepted`,to:a,from:{...e.to,sessionId:i},replyTo:[],content:`Work accepted.`,createdAt:r,reply:o}}var sA=O(P({mail_key:M,agent_id:M,reply_to_json:U(F(Rk))})),cA=Qp(U(F(Rk)));function lA(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_delegators (
|
|
31
31
|
session_id TEXT PRIMARY KEY,
|
|
32
32
|
mail_key TEXT NOT NULL,
|
|
33
33
|
agent_id TEXT NOT NULL,
|
|
34
34
|
reply_to_json TEXT NOT NULL
|
|
35
|
-
)`)}function
|
|
35
|
+
)`)}function uA(e,t,n){n!==void 0&&n.reply===void 0&&n.from.kind===`agent`&&n.replyTo.length!==0&&e.sql.exec(`INSERT OR IGNORE INTO session_delegators (session_id, mail_key, agent_id, reply_to_json) VALUES (?, ?, ?, ?)`,t,n.key,n.to.agentId,cA(n.replyTo))}function dA(e,t){let[n]=e.sql.exec(`SELECT mail_key, agent_id, reply_to_json FROM session_delegators WHERE session_id = ?`,t).toArray();if(n===void 0)return;let r=sA(n);return{key:r.mail_key,agentId:r.agent_id,replyTo:r.reply_to_json}}var fA=8,pA=O(P({agent_id:M,sender_session_id:M,name:M})),mA=O(Ey);function hA(e,t){let n=dA(e,t)?.replyTo[0];if(n===void 0)return;let r=e.sql.exec(`SELECT agent_id, sender_session_id, name FROM session_work_senders WHERE session_id = ? AND agent_id = ? AND sender_session_id = ? LIMIT 1`,t,n.agentId,n.sessionId).toArray()[0];return mA({agentId:n.agentId,sessionId:n.sessionId,name:r===void 0?n.agentId:pA(r).name})}function gA(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_work_senders (
|
|
36
36
|
session_id TEXT NOT NULL,
|
|
37
37
|
work_id TEXT NOT NULL,
|
|
38
38
|
agent_id TEXT NOT NULL,
|
|
39
39
|
sender_session_id TEXT NOT NULL,
|
|
40
40
|
name TEXT NOT NULL,
|
|
41
41
|
PRIMARY KEY (session_id, work_id)
|
|
42
|
-
)`)}function
|
|
42
|
+
)`)}function _A(e,t,n,r){e.sql.exec(`INSERT OR IGNORE INTO session_work_senders
|
|
43
43
|
(session_id, work_id, agent_id, sender_session_id, name)
|
|
44
|
-
VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function
|
|
44
|
+
VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function vA(e,t,n){let r=e.sql.exec(`SELECT agent_id, sender_session_id, name FROM session_work_senders WHERE session_id = ? AND work_id = ?`,t,n).toArray()[0];if(r===void 0)return;let i=pA(r);return mA({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function yA(e,t,n){let r=vA(e,t,n);return r===void 0?[]:bA(e,t,[r])}function bA(e,t,n){return Ok(e,t).filter(e=>n.some(t=>e.waitingOn?.agentId===t.agentId&&e.waitingOn.sessionId===t.sessionId)).slice(0,fA).map(e=>({itemId:e.id,kind:e.kind,summary:e.summary}))}var xA=new TextEncoder,SA=new TextDecoder,CA=/^[A-Za-z0-9_-]+$/u,wA=P({v:j(1),generation:M.pipe(z(gh(1)),z(yh(128)),z(B(e=>xA.encode(e).byteLength<=128))),sequence:H.pipe(z(Zm(0)),z($m(2**53-1)))}),TA={onExcessProperty:`error`},EA=D(wA,TA),DA=D(U(wA),TA);function OA(e){let t=EA({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(xA.encode(n).byteLength>384)return;let r=Fs(n);return xA.encode(r).byteLength<=512?r:void 0}function kA(e){if(xA.encode(e).byteLength>512||!CA.test(e))return;let t=Is(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=SA.decode(t.success),r=DA(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&Fs(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var AA=M.check(gh(1),yh(256)),jA=I([P({agentId:AA,sessionId:AA,...Hk.fields}),P({agentId:AA,sessionId:k(AA),...Wk.fields})]),MA=`fungi_agent_reply`,NA=RegExp(`<(?=\\s*/?\\s*${MA})`,`giu`);function PA(e){return e.replace(NA,`<`)}function FA(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function IA(e){let t=[[`agent_id`,e.agentId]];return e.sessionId!==void 0&&t.push([`session_id`,e.sessionId]),e.outcome!==`undeliverable`&&t.push([`command_id`,e.commandId]),t.push([`outcome`,e.outcome]),e.outcome!==`undeliverable`&&e.diagnostic!==void 0&&t.push([`diagnostic`,e.diagnostic]),e.outcome!==`undeliverable`&&e.waitingOnYou!==void 0&&t.push([`waiting_on_you`,JSON.stringify(e.waitingOnYou)]),e.outcome===`undeliverable`&&t.push([`reason`,e.reason]),`<${MA} ${t.map(([e,t])=>`${e}="${FA(t)}"`).join(` `)}>`}function LA(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:PA(e.text)}:e):PA(e.content);if(t===void 0)return{...e,content:n};let r=IA(t),i=`</${MA}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var RA={onExcessProperty:`error`},zA=new TextEncoder,BA=e=>M.pipe(z(gh(1)),z(B(t=>zA.encode(t).byteLength<=e))),VA=BA(256),HA=BA(4096),UA=M.pipe(z(Fm(/^[0-9a-f]{64}$/u))),WA=ym(()=>I([M,N,cm,om,F(WA),fm(M,WA)])),GA=P({type:j(`text`),text:M,textSignature:k(M)}),KA=P({type:j(`thinking`),thinking:M,thinkingSignature:k(M),redacted:k(cm)}),qA=P({type:j(`image`),data:M,mimeType:M}),JA=P({type:j(`toolCall`),id:M,name:M,arguments:fm(M,WA),thoughtSignature:k(M),namespace:k(M),argumentsError:k(M)}),YA=P({input:N,output:N,cacheRead:N,cacheWrite:N,cacheWrite1h:k(N),reasoning:k(N),totalTokens:N,cost:P({input:N,output:N,cacheRead:N,cacheWrite:N,total:N,totalFromProvider:k(cm)})}),XA=P({role:j(`user`),content:I([M,gm(F(I([GA,qA])))]),timestamp:N}),ZA=P({role:j(`user`),content:M,timestamp:N}),QA=P({name:M,description:M,parameters:fm(M,WA),constrainedSampling:k(I([j(!1),P({type:j(`json_schema`),strict:L([`prefer`,`require`])}),P({type:j(`grammar`),variants:P({openai_lark:k(M),openai_regex:k(M)})})]))}),$A=I([P({role:j(`system`),content:I([M,gm(F(GA))]),sections:k(fm(M,I([M,om]))),toolsAdded:k(gm(F(QA))),toolsRemoved:k(gm(F(P({name:M})))),timestamp:N}),XA,P({role:j(`assistant`),content:gm(F(I([GA,KA,JA]))),api:M,provider:M,model:M,responseModel:k(M),responseId:k(M),diagnostics:k(gm(F(P({type:M,timestamp:N,error:k(P({name:k(M),message:M,stack:k(M),code:k(I([M,N]))})),details:k(fm(M,WA))})))),usage:YA,stopReason:L([`pending`,`stop`,`length`,`toolUse`,`error`,`aborted`,`deferred`]),deferred:k(P({provider:M,modelId:M,api:M,id:M,expiresAt:k(N),pollAfterMs:k(N),data:k(WA)})),errorMessage:k(M),providerError:k(M),modelFailure:k(JE),rawStopReason:k(M),providerThinkingLevel:k(M),endTurn:k(cm),timestamp:N,durationMs:k(N)}),P({role:j(`toolResult`),toolCallId:M,toolName:M,content:gm(F(I([GA,qA]))),usage:k(YA),isError:cm,timestamp:N,durationMs:k(N)})]),ej=L([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),tj=ym(()=>P({kind:ej,value:VA,parent:A(tj)})),nj=I([P({type:j(`auto_retry_start`),run:tj,attempt:N,maxAttempts:N,delayMs:N,dueAt:H.check(V(0)),errorMessage:M}),P({type:j(`auto_retry_attempt`),run:tj,attempt:N}),P({type:j(`auto_retry_end`),run:tj,attempt:N,success:cm,finalError:k(M)})]),rj=P({core:UA,extensions:F(mm([VA,M.pipe(z(Fm(/^sha256:[0-9a-f]{64}$/u)))])).pipe(z(yh(128)))}),ij=P({content:gm(F(I([GA,qA]))),usage:A(YA),isError:cm,terminate:A(cm)}),aj={workId:VA},oj=98304,sj=L([`manual`,`threshold`,`overflow`]),cj=I([P({...aj,kind:j(`sandbox_failure`),event:BO}),P({kind:j(`document`),workId:om,extensionId:VA,name:VA,valueJson:M}),P({kind:j(`model_preference`),workId:om,preference:R(Py)}),P({...aj,kind:j(`command`),meta:k(qO),reply:k(jA),delivery:k(L([`steer`,`followUp`])),requestId:VA,targetWorkId:k(VA),receiptId:VA,message:XA,contract:rj}),P({...aj,kind:j(`command`),work:j(`compact`),instructions:k(ab),meta:k(qO),requestId:VA,receiptId:VA,timestamp:H.check(V(0)),contract:rj}),P({kind:j(`operator`),workId:om,requestId:VA,author:L([`operator`,`party`]),meta:k(qO),message:ZA}),P({...aj,kind:j(`cancellation`),requestId:VA,receiptId:VA,targetWorkId:VA,meta:k(qO)}),P({...aj,kind:j(`model_selection`),provider:VA,model:VA,catalogRevision:VA,definitionRevision:VA,selectionPolicyRevision:VA}),P({...aj,kind:j(`run_started`),run:tj,contract:rj}),P({...aj,kind:j(`turn_started`),run:tj,turn:tj}),P({...aj,kind:j(`model_prompt`),run:tj,turn:tj,attempt:N.pipe(z(nh()),z(Zm(0))),contract:rj,systemPrompt:M.pipe(z(B(e=>zA.encode(e).byteLength<=1048576)))}),P({...aj,kind:j(`message_start`),run:tj,turn:tj,message:tj,role:L([`assistant`,`system`,`toolResult`,`user`]),partial:k(P({text:M.pipe(z(B(e=>zA.encode(e).byteLength<=oj))),offset:N.pipe(z(nh()),z(V(0)))}))}),P({...aj,kind:j(`message`),data:k(WA),run:tj,turn:tj,message:tj,value:$A}),P({...aj,kind:j(`tool_intent`),replay:L([`safe`,`unsafe`]).pipe(km(x(`unsafe`))),contract:rj,run:tj,turn:tj,toolCall:tj,call:JA}),P({...aj,kind:j(`tool_outcome`),data:k(WA),run:tj,turn:tj,toolCall:tj,call:JA,result:ij}),P({...aj,kind:j(`live_retry`),event:nj}),P({...aj,kind:j(`compaction`),head:VA,model:mm([XA]),data:P({reason:k(sj),resumesRun:cm,tokensBefore:N,tokensAfter:k(N),usage:YA,contextRevision:VA,receipt:k(HA),details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})}),P({...aj,kind:j(`compaction_checkpoint`),trigger:sj,resumesRun:cm,head:VA,contextRevision:VA,summary:M,tokensBefore:N,usage:YA,details:P({readFiles:F(M),modifiedFiles:F(M)})}),P({...aj,kind:j(`compaction_notice`),trigger:sj,result:j(`nothing_to_compact`),diagnostic:k(M.check(yh(200)))}),P({...aj,kind:j(`compaction_notice`),trigger:sj,result:j(`failed`),usage:k(YA),diagnostic:k(M.check(yh(200)))}),P({...aj,kind:j(`compaction_notice`),trigger:sj,result:j(`stale`),usage:k(YA)}),P({...aj,kind:j(`compaction_notice`),trigger:sj,result:j(`insufficient`),usage:k(YA)}),P({...aj,kind:j(`run_terminal`),run:tj,terminal:tj,diagnostic:k(M.check(yh(200))),outcome:L([`completed`,`cancelled`,`failed`])}),P({...aj,kind:j(`work_terminal`),diagnostic:k(M),outcome:L([`completed`,`interrupted`,`cancelled`,`failed`])})]),lj=Jh(cj);function uj(e){return{kind:e.kind,workId:e.workId,run:e.run,turn:e.turn,message:e.message,role:e.role}}function dj(e,t){return lj(gj(hj(e)),gj(hj(t)))}var fj=U(cj),pj=U(am),mj=D(fj,RA),hj=Qp(pj),gj=O(fj,RA);function _j(e){return`work`in e}function vj(e){return e.kind===`command`&&!_j(e)?e:void 0}function yj(e){return _j(e)?e.timestamp:e.message.timestamp}function bj(e){return LA(e.author===`party`?e.message:{role:`user`,content:`[A human operator replied to the user on your behalf]\n${e.message.content}`,timestamp:e.message.timestamp})}function xj(e){return LA(e.message,e.reply)}function Sj(e){return e.author===`party`?e.message:{role:`assistant`,content:[{type:`text`,text:e.message.content}],api:`operator`,provider:`operator`,model:`operator`,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:e.message.timestamp}}function Cj(e){return zt(mj(e),e=>e.kind===`command`&&!_j(e)&&e.delivery===void 0?{...e,delivery:`followUp`}:e)}function wj(e){let t=hj(e);return gj(t),t}var Tj=xg({family:`session`,version:1,kinds:{session:{prefix:`session`},work:{prefix:`session_work`},fact:{prefix:`session_fact`},receipt:{prefix:`session_receipt`}}}),Ej=M.pipe(z(gh(1))),Dj=H.pipe(z(V(0))),Oj={onExcessProperty:`error`},kj=P({value_json:M}),Aj=P({state_version:H.pipe(z(V(1))),revision:Ej}),jj=P({status:L([`running`,`stopped`]),reason:R(M),stopped_at:R(Dj),revision:Ej}),Mj=P({extension_id:Ej,key:Ej,job_id:Ej}),Nj=P({collection:Ej,key:Ej,value_json:M}),Pj=P({sequence:Dj});function Fj(e){return new W(`store`,`unavailable`,e)}function Ij(e,t,n){let r=D(e,Oj);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw Fj(n);return t.success})}function Lj(e){e.transactionSync(()=>{Rj(e)})}function Rj(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_records (
|
|
45
45
|
extension_id TEXT NOT NULL,
|
|
46
46
|
collection TEXT NOT NULL,
|
|
47
47
|
key TEXT NOT NULL,
|
|
@@ -69,49 +69,49 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
|
|
|
69
69
|
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_settled_cursors (
|
|
70
70
|
consumer TEXT PRIMARY KEY,
|
|
71
71
|
sequence INTEGER NOT NULL CHECK (sequence >= 0)
|
|
72
|
-
)`)}function
|
|
73
|
-
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r).toArray(),`Stored extension record is invalid`)[0]?.value_json}function
|
|
72
|
+
)`)}function zj(e,t,n,r){return Ij(kj,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
|
|
73
|
+
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r).toArray(),`Stored extension record is invalid`)[0]?.value_json}function Bj(e,t,n,r){return Ij(kj,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
|
|
74
74
|
WHERE extension_id = ? AND collection = ?
|
|
75
75
|
AND (? IS NULL OR index_value = ?)
|
|
76
76
|
AND (? IS NULL OR key > ?)
|
|
77
|
-
ORDER BY key LIMIT ?`,t,n,r.index??null,r.index??null,r.after??null,r.after??null,r.limit).toArray(),`Stored extension record is invalid`).map(({value_json:e})=>e)}function
|
|
77
|
+
ORDER BY key LIMIT ?`,t,n,r.index??null,r.index??null,r.after??null,r.after??null,r.limit).toArray(),`Stored extension record is invalid`).map(({value_json:e})=>e)}function Vj(e,t,n,r,i,a){e.sql.exec(`INSERT INTO shiitake_extension_records
|
|
78
78
|
(extension_id, collection, key, index_value, value_json)
|
|
79
79
|
VALUES (?, ?, ?, ?, ?)
|
|
80
80
|
ON CONFLICT(extension_id, collection, key) DO UPDATE SET
|
|
81
|
-
index_value = excluded.index_value, value_json = excluded.value_json`,t,n,r,i,a)}function
|
|
82
|
-
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r)}function
|
|
83
|
-
WHERE extension_id = ? ORDER BY collection, key`,t).toArray(),`Stored extension record is invalid`).map(e=>({collection:e.collection,key:e.key,valueJson:e.value_json}))}function
|
|
84
|
-
WHERE extension_id = ?`,t).toArray(),`Extension ledger is invalid`)[0];return n===void 0?void 0:{version:n.state_version,revision:n.revision}}function
|
|
81
|
+
index_value = excluded.index_value, value_json = excluded.value_json`,t,n,r,i,a)}function Hj(e,t,n,r){e.sql.exec(`DELETE FROM shiitake_extension_records
|
|
82
|
+
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r)}function Uj(e,t){return Ij(Nj,e.sql.exec(`SELECT collection, key, value_json FROM shiitake_extension_records
|
|
83
|
+
WHERE extension_id = ? ORDER BY collection, key`,t).toArray(),`Stored extension record is invalid`).map(e=>({collection:e.collection,key:e.key,valueJson:e.value_json}))}function Wj(e,t){e.sql.exec(`DELETE FROM shiitake_extension_records WHERE extension_id = ?`,t)}function Gj(e,t){let n=Ij(Aj,e.sql.exec(`SELECT state_version, revision FROM shiitake_extension_state
|
|
84
|
+
WHERE extension_id = ?`,t).toArray(),`Extension ledger is invalid`)[0];return n===void 0?void 0:{version:n.state_version,revision:n.revision}}function Kj(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_state (extension_id, state_version, revision)
|
|
85
85
|
VALUES (?, ?, ?)
|
|
86
86
|
ON CONFLICT(extension_id) DO UPDATE SET
|
|
87
|
-
state_version = excluded.state_version, revision = excluded.revision`,t,n,r)}function
|
|
88
|
-
WHERE extension_id = ?`,t).toArray(),`Extension status is invalid`)[0];return n===void 0?void 0:{status:n.status,reason:n.reason,stoppedAt:n.stopped_at,revision:n.revision}}function
|
|
87
|
+
state_version = excluded.state_version, revision = excluded.revision`,t,n,r)}function qj(e,t){let n=Ij(jj,e.sql.exec(`SELECT status, reason, stopped_at, revision FROM shiitake_extension_status
|
|
88
|
+
WHERE extension_id = ?`,t).toArray(),`Extension status is invalid`)[0];return n===void 0?void 0:{status:n.status,reason:n.reason,stoppedAt:n.stopped_at,revision:n.revision}}function Jj(e,t,n){e.sql.exec(`INSERT INTO shiitake_extension_status
|
|
89
89
|
(extension_id, status, reason, stopped_at, revision)
|
|
90
90
|
VALUES (?, ?, ?, ?, ?)
|
|
91
91
|
ON CONFLICT(extension_id) DO UPDATE SET status = excluded.status,
|
|
92
92
|
reason = excluded.reason, stopped_at = excluded.stopped_at,
|
|
93
|
-
revision = excluded.revision`,t,n.status,n.reason,n.stoppedAt,n.revision)}var
|
|
94
|
-
ON CONFLICT(consumer) DO UPDATE SET sequence = MAX(sequence, excluded.sequence)`,t,n)}var
|
|
93
|
+
revision = excluded.revision`,t,n.status,n.reason,n.stoppedAt,n.revision)}var Yj=`extension_timer`;function Xj(e,t,n){return Ij(Mj,e.sql.exec(`SELECT extension_id,key,job_id FROM shiitake_extension_timers WHERE extension_id=? AND key=?`,t,n).toArray(),`Extension timer is invalid`)[0]?.job_id}function Zj(e,t,n,r,i){Qj(e,t,n,r);let a=Tj.work.generate();t.enqueueAcceptedJob({jobId:a,queue:a,lane:Yj,priority:0,payload:{extensionId:n,key:r},notBefore:i,state:`queued`}),e.sql.exec(`INSERT INTO shiitake_extension_timers(extension_id,key,job_id) VALUES (?,?,?)`,n,r,a)}function Qj(e,t,n,r){let i=Xj(e,n,r);i!==void 0&&t.recordCancellationIntent({jobId:i,cancellationId:`${i}:cancel`,onlyIfQueued:!0}),e.sql.exec(`DELETE FROM shiitake_extension_timers WHERE extension_id=? AND key=?`,n,r)}function $j(e,t){return Ij(Mj,e.sql.exec(`SELECT extension_id,key,job_id FROM shiitake_extension_timers WHERE extension_id=?`,t).toArray(),`Extension timer is invalid`)}function eM(e,t,n){for(let r of $j(e,n))t.recordCancellationIntent({jobId:r.job_id,cancellationId:`${r.job_id}:cancel`,onlyIfQueued:!0})}function tM(e,t,n){for(let r of $j(e,n)){let i=t.readJob(r.job_id);if(i===void 0)throw Fj(`Extension timer job is missing`);i.state!==`queued`&&i.state!==`running`&&Zj(e,t,n,r.key,i.notBefore)}}function nM(e,t,n){for(let r of $j(e,n))Qj(e,t,n,r.key)}function rM(e,t,n,r){let i=Xj(e,n,r);if(i===void 0)return;let a=t.readJob(i);if(a===void 0)throw Fj(`Extension timer job is missing`);return a.notBefore}function iM(e,t){return Ij(Pj,e.sql.exec(`SELECT sequence FROM shiitake_settled_cursors WHERE consumer = ?`,t).toArray(),`Settled cursor is invalid`)[0]?.sequence}function aM(e,t,n){e.sql.exec(`INSERT INTO shiitake_settled_cursors (consumer, sequence) VALUES (?, ?)
|
|
94
|
+
ON CONFLICT(consumer) DO UPDATE SET sequence = MAX(sequence, excluded.sequence)`,t,n)}var oM=P({extension_id:M,name:M,initial_json:M,fork:L([`inherit-at-fork-point`,`current`,`fresh`]),max_bytes:H.pipe(z(Zm(0)))});function sM(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_document_specs (
|
|
95
95
|
extension_id TEXT NOT NULL, name TEXT NOT NULL, initial_json TEXT NOT NULL,
|
|
96
96
|
fork TEXT NOT NULL, max_bytes INTEGER NOT NULL,
|
|
97
97
|
PRIMARY KEY (extension_id, name)
|
|
98
|
-
)`)}function
|
|
98
|
+
)`)}function cM(e,t){e.sql.exec(`INSERT INTO session_document_specs
|
|
99
99
|
(extension_id, name, initial_json, fork, max_bytes) VALUES (?, ?, ?, ?, ?)
|
|
100
100
|
ON CONFLICT(extension_id, name) DO UPDATE SET initial_json = excluded.initial_json,
|
|
101
|
-
fork = excluded.fork, max_bytes = excluded.max_bytes`,t.extensionId,t.name,t.initialJson,t.fork,t.maxBytes)}function
|
|
101
|
+
fork = excluded.fork, max_bytes = excluded.max_bytes`,t.extensionId,t.name,t.initialJson,t.fork,t.maxBytes)}function lM(e,t){return e.sql.exec(`SELECT extension_id, name, initial_json, fork, max_bytes FROM session_document_specs ORDER BY extension_id, name`).toArray().flatMap(e=>{let n=O(oM)(e);if(n.fork===`inherit-at-fork-point`)return[];let r=n.fork===`fresh`?n.initial_json:t(n.extension_id,n.name)??n.initial_json;if(new TextEncoder().encode(r).byteLength>n.max_bytes)throw new W(`store`,`rejected`,`Session document exceeds its declared size bound`);return[{kind:`document`,workId:null,extensionId:n.extension_id,name:n.name,valueJson:r}]})}var uM=Vp(M),dM=`The conversation history before this point was compacted into the following summary:
|
|
102
102
|
|
|
103
103
|
<summary>
|
|
104
|
-
`,
|
|
105
|
-
</summary>`;function
|
|
104
|
+
`,fM=`
|
|
105
|
+
</summary>`;function pM(e,t){return{role:`user`,content:[{type:`text`,text:dM+e+fM}],timestamp:t}}function mM(e){let t=Array.isArray(e.content)?e.content[0]:void 0,n=t?.type===`text`?t.text:void 0;if(n===void 0||!n.startsWith(dM)||!n.endsWith(fM))throw Error(`Compaction model message is not a summary`);return n.slice(dM.length,n.length-fM.length)}function hM(){return{edited:new Set,read:new Set,written:new Set}}function gM(e,t){if(e.role===`assistant`)for(let n of e.content){if(n.type!==`toolCall`)continue;let e=n.arguments.path;uM(e)&&(n.name===`edit`&&t.edited.add(e),n.name===`read`&&t.read.add(e),n.name===`write`&&t.written.add(e))}}function _M(e){let t=new Set([...e.edited,...e.written]);return{modifiedFiles:[...t].sort(),readFiles:[...e.read].filter(e=>!t.has(e)).sort()}}function vM(e,t){let n=[];return e.length>0&&n.push(`<read-files>\n${e.join(`
|
|
106
106
|
`)}\n</read-files>`),t.length>0&&n.push(`<modified-files>\n${t.join(`
|
|
107
107
|
`)}\n</modified-files>`),n.length===0?``:`\n\n${n.join(`
|
|
108
108
|
|
|
109
|
-
`)}`}var
|
|
110
|
-
`)}`),n.length>0&&r.push(`[Assistant tool calls]: ${n.join(`; `)}`),r}function
|
|
109
|
+
`)}`}var yM=2e3;function bM(e){return e.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function xM(e){if(e.length<=yM)return e;let t=String(e.length-yM);return`${e.slice(0,yM)}\n\n[... ${t} more characters truncated]`}function SM(e){let t=uM(e.content)?e.content:bM(e.content);return t?`[User]: ${t}`:void 0}function CM(e){let t=[],n=[];for(let r of e.content)if(r.type===`text`)t.push(r.text);else if(r.type===`toolCall`){let e=Object.entries(r.arguments).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(`, `);n.push(`${r.name}(${e})`)}let r=[];return t.length>0&&r.push(`[Assistant]: ${t.join(`
|
|
110
|
+
`)}`),n.length>0&&r.push(`[Assistant tool calls]: ${n.join(`; `)}`),r}function wM(e){let t=bM(e.content);return t?`[Tool result]: ${xM(t)}`:void 0}function TM(e){let t=[];for(let n of e)if(n.role===`system`){let e=uM(n.content)?n.content:bM(n.content);e&&t.push(`[System]: ${e}`)}else if(n.role===`user`){let e=SM(n);e!==void 0&&t.push(e)}else if(n.role===`assistant`)t.push(...CM(n));else{let e=wM(n);e!==void 0&&t.push(e)}return t.join(`
|
|
111
111
|
|
|
112
|
-
`)}function
|
|
112
|
+
`)}function EM(e,t,n){return n.enabled?e>t-n.reserveTokens:!1}function DM(e,t,n){return!n.enabled||n.backgroundTokens===0?!1:e>t-n.reserveTokens-n.backgroundTokens&&!EM(e,t,n)}var OM={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4,backgroundTokens:32768},kM=`You are a context summarization assistant. Your task is to read a conversation between a user and an AI coding assistant, then produce a structured summary following the exact format specified.
|
|
113
113
|
|
|
114
|
-
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,
|
|
114
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,AM=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
115
115
|
|
|
116
116
|
Use this EXACT format:
|
|
117
117
|
|
|
@@ -142,7 +142,7 @@ Use this EXACT format:
|
|
|
142
142
|
- [Any data, examples, or references needed to continue]
|
|
143
143
|
- [Or "(none)" if not applicable]
|
|
144
144
|
|
|
145
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`,
|
|
145
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,jM=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
146
146
|
|
|
147
147
|
Update the existing structured summary with new information. RULES:
|
|
148
148
|
- PRESERVE all existing information from the previous summary
|
|
@@ -179,7 +179,7 @@ Use this EXACT format:
|
|
|
179
179
|
## Critical Context
|
|
180
180
|
- [Preserve important context, add new if needed]
|
|
181
181
|
|
|
182
|
-
Keep each section concise. Preserve exact file paths, function names, and error messages.`,
|
|
182
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,MM=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
|
|
183
183
|
|
|
184
184
|
Create a concise checkpoint of the user's request and the progress shown above. This checkpoint will be placed before the later messages so the conversation can continue with the necessary context.
|
|
185
185
|
|
|
@@ -192,15 +192,15 @@ Create a concise checkpoint of the user's request and the progress shown above.
|
|
|
192
192
|
## Context Needed to Continue
|
|
193
193
|
- [Information from these messages needed to understand the later work]
|
|
194
194
|
|
|
195
|
-
Only summarize information explicitly present above. Do not infer or recreate later messages.`;function
|
|
195
|
+
Only summarize information explicitly present above. Do not infer or recreate later messages.`;function NM(e,t){if(e.stopReason===`error`){let n=e.errorMessage;return`${t} failed: ${n!==void 0&&n.length>0?n:`Unknown error`}`}return e.stopReason===`length`?`${t} failed: generation hit the token cap and the summary is incomplete`:e.content.some(e=>e.type===`toolCall`)?`${t} attempted to call a tool`:void 0}var PM=fm(M.check(gh(1),yh(160)),L([`none`,`read`,`write`])).check(B(e=>Object.keys(e).length<=256)),FM=D(P({version:H.check(V(0),$m(2**53-1)),grants:PM}),{onExcessProperty:`error`}),IM=D(U(PM)),LM=Qp(U(PM)),RM=D(P({version:H,grants_json:M}));function zM(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_tool_grants (
|
|
196
196
|
session_id TEXT PRIMARY KEY,
|
|
197
197
|
version INTEGER NOT NULL,
|
|
198
198
|
grants_json TEXT NOT NULL
|
|
199
|
-
)`)}function
|
|
199
|
+
)`)}function BM(e,t,n){let r=FM(n);if(Ae(r))throw new W(`contract`,`invalid`,`Session grants delivery is invalid`);let i=LM(r.success.grants),a=VM(e,t);if(a!==void 0){if(r.success.version<a.version)throw new W(`contract`,`conflict`,`Session grants delivery is older than the stored delivery`);if(r.success.version===a.version&&a.grantsJson===i)return`unchanged`}return e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
|
|
200
200
|
VALUES (?, ?, ?)
|
|
201
201
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
202
|
-
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function
|
|
203
|
-
SELECT ?, version, grants_json FROM session_tool_grants WHERE session_id = ?`,n,t)}var
|
|
202
|
+
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function VM(e,t){let[n]=e.sql.exec(`SELECT version, grants_json FROM session_tool_grants WHERE session_id = ?`,t).toArray();if(n===void 0)return;let r=RM(n);if(Ae(r))throw new W(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:r.success.version,grantsJson:r.success.grants_json}}function HM(e,t){let n=VM(e,t);if(n===void 0)return null;let r=IM(n.grantsJson);if(Ae(r))throw new W(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:n.version,grants:r.success}}function UM(e,t,n){e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
|
|
203
|
+
SELECT ?, version, grants_json FROM session_tool_grants WHERE session_id = ?`,n,t)}var WM=200,GM={onExcessProperty:`error`},KM=new TextEncoder,qM=M.pipe(z(gh(1)),z(B(e=>KM.encode(e).byteLength<=256))),JM=H.pipe(z(V(0))),YM=L([0,1,2]),XM=L([`needs_you`,`running`,`errored`,`done`]),ZM=L([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),QM=P({session_id:qM,title:R(M),created_at:JM,last_activity_at:JM,settled_at:R(JM),state:XM,tier:YM}),$M=D(QM,GM);D(QM.mapFields(Ep({revision:JM})),GM),D(P({revision:JM}),GM);var eN=D(P({outcome:R(ZM)}),GM),tN=U(mm([YM,JM,qM])),nN=D(tN),rN=Qp(tN),iN=`session_id, title, created_at, last_activity_at, settled_at, state, tier`;function aN(e){return new W(`store`,`unavailable`,e)}function oN(e){switch(e){case`needs_you`:return 0;case`running`:return 1;case`errored`:case`done`:return 2}}function sN(e,t,n){if(n)return`needs_you`;if(e.state!==`idle`)return`running`;switch(t){case`failed`:case`interrupted`:case`outcome_unknown`:return`errored`;case`completed`:case`cancelled`:case null:return`done`}}function cN(e){e.sql.exec(`
|
|
204
204
|
CREATE TABLE IF NOT EXISTS session_inbox (
|
|
205
205
|
session_id TEXT PRIMARY KEY REFERENCES sessions(id),
|
|
206
206
|
title TEXT,
|
|
@@ -230,30 +230,30 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
230
230
|
session_id TEXT PRIMARY KEY,
|
|
231
231
|
revision INTEGER NOT NULL
|
|
232
232
|
) STRICT
|
|
233
|
-
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_tombstones_revision ON session_inbox_tombstones(revision)`)}function
|
|
233
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_tombstones_revision ON session_inbox_tombstones(revision)`)}function lN(e){e.sql.exec(`UPDATE session_inbox_clock SET revision = revision + 1 WHERE singleton = 1`)}var uN=`(SELECT revision FROM session_inbox_clock WHERE singleton = 1)`;function dN(e,t){let n=t.title===void 0?``:t.title,r=t.title===void 0?0:1;lN(e),e.sql.exec(`INSERT INTO session_inbox
|
|
234
234
|
(session_id, title, created_at, last_activity_at, settled_at, outcome,
|
|
235
235
|
state, tier, revision)
|
|
236
236
|
SELECT id, ?, created_at, COALESCE(?, created_at), NULL, NULL, 'done', 2,
|
|
237
|
-
${
|
|
237
|
+
${uN}
|
|
238
238
|
FROM sessions
|
|
239
239
|
WHERE id = ?
|
|
240
240
|
ON CONFLICT (session_id) DO UPDATE SET
|
|
241
241
|
title = CASE WHEN ? = 1 THEN excluded.title ELSE title END,
|
|
242
242
|
last_activity_at = MAX(last_activity_at, excluded.last_activity_at),
|
|
243
|
-
revision = excluded.revision`,n,t.activityAt??null,t.sessionId,r)}function
|
|
244
|
-
VALUES (?, ${
|
|
245
|
-
ON CONFLICT (session_id) DO UPDATE SET revision = excluded.revision`,t)}function
|
|
246
|
-
SET outcome = ?, state = ?, tier = ?, revision = ${
|
|
243
|
+
revision = excluded.revision`,n,t.activityAt??null,t.sessionId,r)}function fN(e,t){lN(e),e.sql.exec(`INSERT INTO session_inbox_tombstones (session_id, revision)
|
|
244
|
+
VALUES (?, ${uN})
|
|
245
|
+
ON CONFLICT (session_id) DO UPDATE SET revision = excluded.revision`,t)}function pN(e,t,n){let r=e.sql.exec(`SELECT outcome FROM session_inbox WHERE session_id = ?`,t.queue).toArray()[0];if(r===void 0)return;let i=eN(r);if(i._tag===`Failure`)throw aN(`Stored inbox row is invalid`);let a=t.settled?.outcome??i.success.outcome,o=sN(t.head,a,kk(e,t.queue));lN(e),e.sql.exec(`UPDATE session_inbox
|
|
246
|
+
SET outcome = ?, state = ?, tier = ?, revision = ${uN},
|
|
247
247
|
settled_at = CASE WHEN ? = 1 THEN ? ELSE settled_at END,
|
|
248
248
|
last_activity_at = MAX(last_activity_at, ?)
|
|
249
|
-
WHERE session_id = ?`,a,o,
|
|
249
|
+
WHERE session_id = ?`,a,o,oN(o),t.settled===void 0?0:1,n,n,t.queue)}function mN(e,t,n){let r=e.sql.exec(`SELECT outcome FROM session_inbox WHERE session_id = ?`,t).toArray()[0];if(r===void 0)return;let i=eN(r);if(i._tag===`Failure`)throw aN(`Stored inbox row is invalid`);let a=sN(n,i.success.outcome,kk(e,t));lN(e),e.sql.exec(`UPDATE session_inbox SET state = ?, tier = ?, revision = ${uN} WHERE session_id = ?`,a,oN(a),t)}function hN(e){if(e.title===null)return Object.freeze({sessionId:e.session_id,state:`unavailable`});let t={sessionId:e.session_id,title:e.title,createdAt:e.created_at,lastActivityAt:e.last_activity_at,state:e.state};return Object.freeze(e.settled_at===null?t:{...t,settledAt:e.settled_at})}function gN(e){let t=nN(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function _N(e,t){let n=t===void 0?void 0:gN(t),r=n===void 0?e.sql.exec(`SELECT ${iN} FROM session_inbox
|
|
250
250
|
ORDER BY tier ASC, last_activity_at DESC, session_id ASC
|
|
251
|
-
LIMIT ?`,
|
|
251
|
+
LIMIT ?`,WM).toArray():e.sql.exec(`SELECT ${iN} FROM session_inbox
|
|
252
252
|
WHERE tier > ?
|
|
253
253
|
OR (tier = ? AND last_activity_at < ?)
|
|
254
254
|
OR (tier = ? AND last_activity_at = ? AND session_id > ?)
|
|
255
255
|
ORDER BY tier ASC, last_activity_at DESC, session_id ASC
|
|
256
|
-
LIMIT ?`,n[0],n[0],n[1],n[0],n[1],n[2],
|
|
256
|
+
LIMIT ?`,n[0],n[0],n[1],n[0],n[1],n[2],WM).toArray(),i=[],a;for(let e of r){let t=$M(e);if(t._tag===`Failure`)throw aN(`Stored inbox row is invalid`);let n=t.success;a=[n.tier,n.last_activity_at,n.session_id],i.push(hN(n))}return{sessions:i,next:r.length===WM&&a!==void 0?rN(a):void 0}}var vN={onExcessProperty:`error`};function yN(e){return new W(`store`,`incompatible`,e)}var bN=P({id:M,timestamp:N,data_json:M}),xN=U(P({kind:j(`compaction`),workId:M,resumesRun:k(cm),trigger:k(L([`manual`,`threshold`,`overflow`])),tokensAfter:k(N),firstKeptEntryId:M,summary:M,tokensBefore:N,usage:YA,contextRevision:M,details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})),SN=D(bN,vN),CN=D(xN,vN);function wN(e){let t=e.sql.exec(`SELECT id, timestamp, data_json FROM session_entries WHERE type = 'compaction' AND json_extract(data_json, '$.head') IS NULL`).toArray();for(let n of t){let t=SN(n);if(Ae(t))throw yN(`Stored compaction row cannot be read`);let r=CN(t.success.data_json);if(Ae(r))throw yN(`Stored compaction row cannot be rewritten`);let i=r.success,a={resumesRun:i.resumesRun??!1,tokensBefore:i.tokensBefore,usage:i.usage,contextRevision:i.contextRevision};i.trigger!==void 0&&(a.reason=i.trigger),i.tokensAfter!==void 0&&(a.tokensAfter=i.tokensAfter),i.details!==void 0&&(a.details=i.details),e.sql.exec(`UPDATE session_entries SET data_json = ? WHERE id = ?`,wj({kind:`compaction`,workId:i.workId,head:i.firstKeptEntryId,model:[pM(i.summary,t.success.timestamp)],data:a}),t.success.id)}}var TN=D(P({data_json:M}),vN);function EN(e){e.sql.exec(`UPDATE session_entries
|
|
257
257
|
SET data_json = json_set(
|
|
258
258
|
json_remove(data_json, '$.result.details'),
|
|
259
259
|
'$.data', json(json_extract(data_json, '$.result.details'))
|
|
@@ -267,7 +267,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
267
267
|
)
|
|
268
268
|
WHERE type = 'message'
|
|
269
269
|
AND json_type(data_json, '$.value.details') IS NOT NULL
|
|
270
|
-
AND json_type(data_json, '$.data') IS NULL`);for(let t of e.sql.exec(`SELECT data_json FROM session_entries WHERE type IN ('tool_outcome', 'message')`).toArray()){let e=
|
|
270
|
+
AND json_type(data_json, '$.data') IS NULL`);for(let t of e.sql.exec(`SELECT data_json FROM session_entries WHERE type IN ('tool_outcome', 'message')`).toArray()){let e=TN(t);if(Ae(e)||Cj(e.success.data_json)._tag===`Failure`)throw yN(`A stored tool result cannot be read`)}}var DN=M.pipe(z(gh(1))),ON=H.pipe(z(V(0))),kN=P({name:M}),AN=P({sql:M}),jN=P({extension_id:DN,key:DN,due_at:ON}),MN=P({extension_id:DN}),NN=P({seq:ON}),PN=P({count:ON}),FN=P({data_json:M});function IN(e){return new W(`store`,`incompatible`,e)}function LN(e,t,n){let r=D(e);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw IN(n);return t.success})}function RN(e,t,...n){return e.sql.exec(t,...n).toArray()}function zN(e,t){return LN(kN,RN(e,`PRAGMA table_info(${t})`),`Store table description is invalid`).map(e=>e.name)}function BN(e,t){let n=LN(PN,RN(e,`SELECT COUNT(*) AS count FROM ${t}`),`Store row count is invalid`)[0];if(n===void 0)throw IN(`Store row count is missing`);return n.count}var VN=`
|
|
271
271
|
CREATE TABLE watchdog_jobs (
|
|
272
272
|
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
273
273
|
job_id TEXT UNIQUE NOT NULL,
|
|
@@ -298,26 +298,26 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
298
298
|
(state = 'settled' AND outcome IS NOT NULL)
|
|
299
299
|
)
|
|
300
300
|
)
|
|
301
|
-
`,
|
|
301
|
+
`,HN=[`sequence`,`job_id`,`queue_name`,`lane`,`priority`,`payload_json`,`not_before`,`attempt_count`,`recovery_max`,`recovery_window_ms`,`recovery_window_started_at`,`state`,`outcome`,`claim_token`,`recovery_count`,`cancellation_id`,`failure_reason`],UN=[`sequence`,`job_id`,`queue_name`,`lane`,`priority`,`payload_json`,`recovery_max`,`state`,`outcome`,`claim_token`,`recovery_count`,`cancellation_id`,`failure_reason`],WN=`watchdog_jobs_before_marker_6`;function GN(e){let t=zN(e,`watchdog_jobs`);if(t.length===0||LN(AN,RN(e,`SELECT sql FROM sqlite_schema WHERE type = 'table' AND name = 'watchdog_jobs'`),`Watchdog jobs definition is invalid`)[0]?.sql.includes(`watchdog_execution_state`)===!0&&HN.every(e=>t.includes(e)))return;if(!UN.every(e=>t.includes(e)))throw IN(`Watchdog jobs table has an unknown shape`);let n=HN.filter(e=>t.includes(e)),r=BN(e,`watchdog_jobs`);e.sql.exec(`ALTER TABLE watchdog_jobs RENAME TO ${WN}`),e.sql.exec(VN);let i=n.join(`, `);if(e.sql.exec(`INSERT INTO watchdog_jobs (${i}) SELECT ${i} FROM ${WN} ORDER BY sequence`),BN(e,`watchdog_jobs`)!==r)throw IN(`Watchdog jobs were not all carried over`);let a=LN(NN,RN(e,`SELECT seq FROM sqlite_sequence WHERE name = ?`,WN),`Watchdog job counter is invalid`)[0];e.sql.exec(`DROP TABLE ${WN}`),a!==void 0&&(e.sql.exec(`DELETE FROM sqlite_sequence WHERE name = 'watchdog_jobs'`),e.sql.exec(`INSERT INTO sqlite_sequence (name, seq) VALUES ('watchdog_jobs', MAX(?, (SELECT COALESCE(MAX(sequence), 0) FROM watchdog_jobs)))`,a.seq))}var KN=`shiitake_extension_timers_before_marker_6`;function qN(e){let t=zN(e,`shiitake_extension_timers`);if(t.length===0||t.includes(`job_id`))return;let n=LN(jN,RN(e,`SELECT extension_id, key, due_at FROM shiitake_extension_timers ORDER BY extension_id, key`),`Stored extension timer is invalid`);if(n.length>0&&zN(e,`watchdog_jobs`).length===0)throw IN(`Extension timers have no Watchdog jobs to move to`);let r=new Set(zN(e,`shiitake_extension_status`).length===0?[]:LN(MN,RN(e,`SELECT extension_id FROM shiitake_extension_status WHERE status = 'stopped'`),`Stored extension status is invalid`).map(e=>e.extension_id));e.sql.exec(`ALTER TABLE shiitake_extension_timers RENAME TO ${KN}`),e.sql.exec(`CREATE TABLE shiitake_extension_timers (
|
|
302
302
|
extension_id TEXT NOT NULL,
|
|
303
303
|
key TEXT NOT NULL,
|
|
304
304
|
job_id TEXT NOT NULL,
|
|
305
305
|
PRIMARY KEY (extension_id, key)
|
|
306
|
-
)`);for(let t of n){let n=
|
|
306
|
+
)`);for(let t of n){let n=Tj.work.generate();e.sql.exec(`INSERT INTO watchdog_jobs
|
|
307
307
|
(job_id, queue_name, lane, priority, payload_json, not_before,
|
|
308
308
|
state, outcome, claim_token, recovery_count, cancellation_id)
|
|
309
|
-
VALUES (?, ?, ?, 0, ?, ?, 'queued', NULL, NULL, 0, ?)`,n,n,
|
|
309
|
+
VALUES (?, ?, ?, 0, ?, ?, 'queued', NULL, NULL, 0, ?)`,n,n,Yj,JSON.stringify({extensionId:t.extension_id,key:t.key}),t.due_at,r.has(t.extension_id)?`${n}:cancel`:null),e.sql.exec(`INSERT INTO shiitake_extension_timers (extension_id, key, job_id) VALUES (?, ?, ?)`,t.extension_id,t.key,n)}e.sql.exec(`DROP TABLE ${KN}`)}function JN(e){e.sql.exec(`UPDATE session_entries
|
|
310
310
|
SET data_json = json_set(
|
|
311
311
|
data_json, '$.event.dueAt',
|
|
312
312
|
CAST(timestamp + json_extract(data_json, '$.event.delayMs') AS INTEGER)
|
|
313
313
|
)
|
|
314
314
|
WHERE type = 'live_retry'
|
|
315
315
|
AND json_extract(data_json, '$.event.type') = 'auto_retry_start'
|
|
316
|
-
AND json_extract(data_json, '$.event.dueAt') IS NULL`);for(let t of
|
|
316
|
+
AND json_extract(data_json, '$.event.dueAt') IS NULL`);for(let t of LN(FN,RN(e,`SELECT data_json FROM session_entries WHERE type = 'live_retry'`),`Stored retry fact is invalid`))if(Cj(t.data_json)._tag===`Failure`)throw IN(`A stored retry fact cannot be read`)}var YN=[`private_local_exec_rules`,`local_birddog_outbox`];function XN(e){for(let t of YN)e.sql.exec(`DROP TABLE IF EXISTS ${t}`)}var ZN=[{marker:2,apply:wN},{marker:3,apply:EN},{marker:5,apply:JN},{marker:6,apply:GN},{marker:6,apply:qN},{marker:6,apply:XN}],QN=P({version:H});function $N(e){let t=LN(QN,RN(e,`SELECT version FROM woodstock_schema`),`Woodstock schema marker is invalid`)[0];if(t===void 0)throw IN(`Woodstock schema marker is missing`);for(let n of ZN)n.marker>t.version&&n.apply(e)}function eP(e){let t=[...e].reverse().find(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`),n=tP(e,t);if(n!==void 0)return n;if(t?.entry.kind!==`message`||t.entry.value.role!==`assistant`)return;let r=e.filter(({sequence:e})=>e>t.sequence);if(!rP(e)&&r.some(({entry:e})=>e.kind===`turn_started`||e.kind===`compaction`&&e.data.resumesRun||e.kind===`live_retry`&&e.event.type===`auto_retry_start`))return;let i=r.flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`toolResult`?[e.value]:[]),a=t.entry.value.content.flatMap(e=>{if(e.type!==`toolCall`)return[];let t=[...r].reverse().find(({entry:t})=>t.kind===`tool_outcome`&&t.call.id===e.id)?.entry;if(t?.kind===`tool_outcome`)return[{call:e,state:`completed`,result:t.data===void 0?t.result:{...t.result,data:t.data},message:i.find(t=>t.toolCallId===e.id)}];let n=[...r].reverse().find(({entry:t})=>t.kind===`tool_intent`&&t.call.id===e.id)?.entry;return[n?.kind===`tool_intent`?{call:e,state:`started`,replay:n.replay}:{call:e,state:`pending`}]});return{kind:`assistant`,message:t.entry.value,tools:a}}function tP(e,t){let n=Math.max(t?.sequence??0,...e.filter(({entry:e})=>e.kind===`compaction`).map(({sequence:e})=>e)),r=[...e.filter(({sequence:e})=>e>n)].reverse(),i=r.find(({entry:e})=>e.kind===`live_retry`),a=r.find(({entry:e})=>e.kind===`model_prompt`);if(i?.entry.kind===`live_retry`&&i.entry.event.type===`auto_retry_end`&&(a===void 0||a.sequence<i.sequence))return;let o=r.find(({entry:e})=>e.kind===`live_retry`&&e.event.type===`auto_retry_start`),s={kind:`retry`};if(t?.entry.kind===`message`&&t.entry.value.role===`assistant`&&t.entry.value.stopReason===`error`&&(s={...s,message:t.entry.value}),o?.entry.kind===`live_retry`&&o.entry.event.type===`auto_retry_start`&&(s={...s,maxAttempts:o.entry.event.maxAttempts}),i?.entry.kind===`live_retry`){let e=i.entry.event;if(e.type===`auto_retry_start`&&(a===void 0||a.sequence<i.sequence))return{...s,phase:`waiting`,attempt:e.attempt,dueAt:e.dueAt};if(e.type===`auto_retry_attempt`)return{...s,phase:`dispatched`,attempt:e.attempt}}if(a?.entry.kind===`model_prompt`)return{...s,phase:`dispatched`,attempt:a.entry.attempt-1}}function nP(e,t){let n=new Set(e.flatMap(({entry:e})=>e.kind===`run_terminal`?[e.workId]:[])),r=new Set,i=new Map;for(let a of e){let e=a.entry;if(e.kind===`message`&&(e.value.role===`assistant`&&i.set(e.workId,a.id),(n.has(e.workId)||e.workId===t)&&(e.value.role!==`assistant`||e.value.stopReason!==`error`&&e.value.stopReason!==`aborted`)&&r.add(a.id)),e.kind===`compaction`&&e.data.resumesRun||e.kind===`live_retry`&&e.event.type===`auto_retry_start`){let t=i.get(e.workId);t!==void 0&&r.delete(t)}}return r}function rP(e){let t=[...e].reverse().find(({entry:e})=>e.kind===`live_retry`);return t?.entry.kind===`live_retry`&&t.entry.event.type===`auto_retry_end`&&!t.entry.event.success&&!e.some(({sequence:e,entry:n})=>e>t.sequence&&(n.kind===`model_prompt`||n.kind===`compaction`&&n.data.resumesRun))}function iP(e){let t=[...e].reverse(),n=t.find(({entry:e})=>e.kind===`run_terminal`),r=t.find(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`),i=rP(e)&&(r?.entry.kind!==`message`||r.entry.value.role!==`assistant`||r.entry.value.stopReason!==`error`&&r.entry.value.stopReason!==`aborted`)?`failed`:void 0;if(n?.entry.kind!==`run_terminal`||e.some(({sequence:e,entry:t})=>e>n.sequence&&(t.kind===`run_started`||t.kind===`compaction`&&t.data.resumesRun)))return i;if(n.entry.outcome===`cancelled`)return`cancelled`;if(n.entry.outcome!==`failed`)return;let a=t.find(({entry:e})=>e.kind===`turn_started`),o=t.find(({sequence:e,entry:t})=>t.kind===`message`&&t.value.role===`assistant`&&e>(a?.sequence??0));return o?.entry.kind===`message`&&o.entry.value.role===`assistant`&&o.entry.value.stopReason===`error`&&!e.some(({sequence:e,entry:t})=>e>o.sequence&&t.kind===`live_retry`&&t.event.type===`auto_retry_start`)?void 0:`failed`}var aP={onExcessProperty:`error`},oP=new TextEncoder,sP=M.pipe(z(gh(1)),z(B(e=>oP.encode(e).byteLength<=256))),cP=H.pipe(z(Zm(0))),lP=H.pipe(z(V(0))),uP=P({id:sP,leaf_id:R(sP)}),dP=P({session_id:sP}),fP=P({id:sP,leaf_id:R(sP),created_at:lP,updated_at:lP,metadata_json:R(M)}),pP=U(P({title:cb})),mP=D(pP,aP),hP=Qp(pP),gP=P({id:sP}),_P=P({version:H,protocol:M}),vP=P({name:sP}),yP=P({id:sP,session_id:sP,parent_id:R(sP),sequence:cP,type:M,role:R(L([`user`,`assistant`,`tool_result`])),state:L([`complete`,`streaming`]),request_id:R(sP),work_id:R(sP),data_json:M,timestamp:lP,completed_at:R(lP),damaged:L([0,1])}),bP=P({id:sP,session_id:sP,sequence:cP,request_id:sP,work_id:sP,data_json:M,timestamp:lP,origin_kind:L([`user`,`extension`]),origin_id:R(sP),origin_correlation:R(sP)}),xP=P({kind:j(`extension`),extensionId:sP,correlation:R(sP)}),SP=I([P({kind:j(`user`)}),xP]),CP=D(SP,aP),wP=Jh(SP),TP=e=>[`id`,`session_id`,`sequence`,`request_id`,`work_id`,`data_json`,`timestamp`,`origin_kind`,`origin_id`,`origin_correlation`].map(t=>e+t).join(`, `),EP=P({next_sequence:cP}),DP=P({present:j(1)}),OP=D(dP,aP),kP=D(fP,aP),AP=D(gP,aP),jP=D(_P,aP),MP=D(vP,aP),NP=D(P({candidate_id:R(sP),path_count:H.pipe(z(Zm(0))),root_count:H.pipe(z(V(0))),missing_parent_count:H.pipe(z(V(0))),leaf_state:L([`complete`,`streaming`])}),aP),PP=D(yP,aP),FP=D(bP,aP),IP=D(EP,aP),LP=D(DP,aP);function RP(e){return`${[`id`,`session_id`,`parent_id`,`sequence`,`type`,`role`,`state`,`request_id`,`work_id`,`data_json`,`timestamp`,`completed_at`].map(t=>`${e}.${t}`).join(`, `)},
|
|
317
317
|
EXISTS (SELECT 1 FROM session_lineage_damage AS damage
|
|
318
|
-
WHERE damage.session_id = ${e}.session_id) AS damaged`}var RP
|
|
318
|
+
WHERE damage.session_id = ${e}.session_id) AS damaged`}var zP=RP(`session_entries`);function BP(e,t){return t===void 0?e:{...e,meta:t}}function VP(e,t){if(tF(e,t)===void 0)return;let n=e.sql.exec(`SELECT id, leaf_id, created_at, updated_at, metadata_json
|
|
319
319
|
FROM sessions
|
|
320
|
-
WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=
|
|
320
|
+
WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=kP(n);if(r._tag===`Failure`)throw $(`Stored Session summary row is invalid`);let i=GP(e,t,r.success),a=r.success.metadata_json;if(a===null)return i;let o=mP(a);if(o._tag===`Failure`)throw $(`Stored Session title is invalid`);return Object.freeze({createdAt:r.success.created_at,updatedAt:r.success.updated_at,title:o.success.title})}var HP=D(P({id:sP,sequence:cP}),aP);function UP(e,t,n,r){let i=e.sql.exec(`SELECT command.id AS id, command.sequence AS sequence
|
|
321
321
|
FROM session_entries AS command
|
|
322
322
|
WHERE command.session_id = ? AND command.type = 'command'
|
|
323
323
|
AND command.role = 'user' AND command.state = 'complete'
|
|
@@ -328,13 +328,13 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
328
328
|
AND cancelled.type = 'cancellation'
|
|
329
329
|
AND cancelled.sequence < command.sequence
|
|
330
330
|
)
|
|
331
|
-
ORDER BY command.sequence ASC LIMIT 1`,t).toArray()[0];if(i===void 0)return null;let a=
|
|
331
|
+
ORDER BY command.sequence ASC LIMIT 1`,t).toArray()[0];if(i===void 0)return null;let a=HP(i);if(a._tag===`Failure`)throw $(`Stored Session first prompt is invalid`);let o=a.success;return r<o.sequence?null:e.sql.exec(`SELECT 1 AS present FROM session_entries AS parent
|
|
332
332
|
WHERE parent.session_id = ? AND parent.sequence < ?
|
|
333
333
|
AND (SELECT COUNT(*) FROM session_entries AS child
|
|
334
334
|
WHERE child.parent_id = parent.id
|
|
335
335
|
AND child.session_id = parent.session_id
|
|
336
336
|
AND child.state = 'complete') > 1
|
|
337
|
-
LIMIT 1`,t,o.sequence).toArray()[0]===void 0?o.id:
|
|
337
|
+
LIMIT 1`,t,o.sequence).toArray()[0]===void 0?o.id:WP(e,t,n)}function WP(e,t,n){let r=NP(e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, type, role, state, work_id) AS (
|
|
338
338
|
SELECT id, parent_id, sequence, type, role, state, work_id
|
|
339
339
|
FROM session_entries
|
|
340
340
|
WHERE session_id = ? AND id = ?
|
|
@@ -364,31 +364,31 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
364
364
|
SELECT 1 FROM session_entries AS parent
|
|
365
365
|
WHERE parent.session_id = ? AND parent.id = child.parent_id
|
|
366
366
|
)) AS missing_parent_count,
|
|
367
|
-
(SELECT state FROM branch WHERE id = ?) AS leaf_state`,t,n,t,t,n).one());if(r._tag===`Failure`||r.success.leaf_state!==`complete`||r.success.root_count!==1||r.success.missing_parent_count!==0)throw $(`Stored Session summary lineage is invalid`);return r.success.candidate_id}function
|
|
367
|
+
(SELECT state FROM branch WHERE id = ?) AS leaf_state`,t,n,t,t,n).one());if(r._tag===`Failure`||r.success.leaf_state!==`complete`||r.success.root_count!==1||r.success.missing_parent_count!==0)throw $(`Stored Session summary lineage is invalid`);return r.success.candidate_id}function GP(e,t,n){if(n.leaf_id===null)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:``});let r=nF(e,t,n.leaf_id);if(r?.state!==`complete`)throw $(`Stored Session summary leaf is invalid`);let i=UP(e,t,n.leaf_id,r.sequence),a=i===null?void 0:nF(e,t,i)?.entry,o=a===void 0?void 0:vj(a);if(o!==void 0)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:Array.from(aL(o.message.content)?o.message.content.filter(e=>e.type===`text`).map(e=>e.text).join(``)||`Image prompt`:o.message.content).slice(0,120).join(``)})}function KP(e,t){try{return VP(e,t)?.title??``}catch(e){if(e instanceof W&&e.cause===`unavailable`)return null;throw e}}function $(e){return new W(`store`,`unavailable`,e)}function qP(e){return new W(`store`,`incompatible`,e)}function JP(e){return e.kind===`command`||e.kind===`cancellation`||e.kind===`operator`?e.requestId:null}function YP(e){return e.kind===`command`?_j(e)?null:`user`:e.kind===`operator`?e.author===`party`?`user`:`assistant`:e.kind===`message_start`?e.role===`toolResult`?`tool_result`:e.role:e.kind===`message`?e.value.role===`toolResult`?`tool_result`:e.value.role:null}function XP(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function ZP(e,t){let n=PP(t);if(n._tag===`Failure`)throw $(`Stored Session entry row is invalid`);let r=n.success;if(r.damaged===1)throw KF(e,r.session_id);let i=Cj(r.data_json);if(i._tag===`Failure`)throw $(`Stored Session entry data is invalid`);let a=i.success;if(r.type!==a.kind||r.work_id!==a.workId||r.request_id!==JP(a)||r.role!==YP(a))throw $(`Stored Session entry columns disagree with its data`);return Object.freeze({id:r.id,sessionId:r.session_id,parentId:r.parent_id,sequence:r.sequence,state:r.state,timestamp:r.timestamp,completedAt:r.completed_at,entry:a})}function QP(e){let t=FP(e);if(t._tag===`Failure`)throw $(`Stored command admission row is invalid`);let n=t.success,r=Cj(n.data_json);if(r._tag===`Failure`||r.success.kind!==`command`)throw $(`Stored command admission data is invalid`);let i=r.success;if(n.request_id!==i.requestId||n.work_id!==i.workId||n.id!==i.receiptId||n.id!==i.workId||n.timestamp!==yj(i))throw $(`Stored command admission columns disagree with its data`);let a=CP(n.origin_kind===`user`?{kind:`user`}:{kind:`extension`,extensionId:n.origin_id,correlation:n.origin_correlation});if(a._tag===`Failure`||n.origin_kind===`user`&&(n.origin_id!==null||n.origin_correlation!==null))throw $(`Stored command admission origin is invalid`);return Object.freeze({id:n.id,sessionId:n.session_id,sequence:n.sequence,timestamp:n.timestamp,entry:i,origin:a.success})}function $P(e,t){return tF(e,t)!==void 0}var eF=D(P({...uP.fields,damaged:L([0,1])}),aP);function tF(e,t){let n=e.sql.exec(`SELECT id, leaf_id,
|
|
368
368
|
EXISTS (SELECT 1 FROM session_lineage_damage
|
|
369
369
|
WHERE session_id = sessions.id) AS damaged
|
|
370
|
-
FROM sessions WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r
|
|
370
|
+
FROM sessions WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=eF(n);if(r._tag===`Failure`)throw $(`Stored Session row is invalid`);if(r.success.damaged===1)throw KF(e,t);return Object.freeze({id:r.success.id,leaf_id:r.success.leaf_id})}function nF(e,t,n){let r=e.sql.exec(`SELECT ${zP}
|
|
371
371
|
FROM session_entries
|
|
372
|
-
WHERE session_id = ? AND id = ?`,t,n).toArray()[0];return r===void 0?void 0:
|
|
372
|
+
WHERE session_id = ? AND id = ?`,t,n).toArray()[0];return r===void 0?void 0:ZP(e,r)}function rF(e,t){if(t.leaf_id===null){let n=e.sql.exec(`SELECT 1 AS present
|
|
373
373
|
FROM session_entries
|
|
374
374
|
WHERE session_id = ?
|
|
375
|
-
LIMIT 1`,t.id).toArray()[0];if(n===void 0)return;throw
|
|
375
|
+
LIMIT 1`,t.id).toArray()[0];if(n===void 0)return;throw LP(n)._tag===`Failure`?$(`Session entry presence is invalid`):$(`Session leaf is invalid`)}let n=nF(e,t.id,t.leaf_id);if(n?.state!==`complete`)throw $(`Session leaf is invalid`);return n}function iF(e,t){let n=e.sql.exec(`SELECT ${zP}
|
|
376
376
|
FROM session_entries
|
|
377
|
-
WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:
|
|
377
|
+
WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:ZP(e,n)}function aF(e,t,n){let[r,i]=`id`in n?[`id`,n.id]:`requestId`in n?[`request_id`,n.requestId]:[`work_id`,n.workId],a=e.sql.exec(`SELECT ${TP(``)}
|
|
378
378
|
FROM session_command_admissions
|
|
379
|
-
WHERE session_id = ? AND ${r} = ?`,t,i).toArray()[0];return a===void 0?void 0:
|
|
379
|
+
WHERE session_id = ? AND ${r} = ?`,t,i).toArray()[0];return a===void 0?void 0:QP(a)}var oF=`FROM session_command_admissions AS a
|
|
380
380
|
WHERE a.session_id = ?
|
|
381
381
|
AND NOT EXISTS (
|
|
382
382
|
SELECT 1 FROM session_entries AS e
|
|
383
383
|
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
384
384
|
AND e.type IN ('command', 'cancellation', 'run_terminal', 'work_terminal')
|
|
385
|
-
)`;function
|
|
385
|
+
)`;function sF(e,t,n){return e.sql.exec(`SELECT 1 FROM session_entries WHERE session_id = ? AND work_id = ? AND type = 'run_terminal' LIMIT 1`,t,n).toArray().length>0}var cF=O(P({identity:R(M)}));function lF(e,t,n){let{identity:r}=cF(e.sql.exec(`SELECT json_extract(?, ?) AS identity`,JSON.stringify(n??null),t).one());if(r===null||r.length===0)throw new W(`runtime`,`rejected`,`Request author is required`);return{path:t,value:r}}function uF(e,t,n,r){let i=vF(e,t,n);if(i!==void 0&&lF(e,r.path,i.entry.meta).value!==r.value)throw new W(`runtime`,`rejected`,`Message author does not match`)}function dF(e,t,n){let r=e.sql.exec(`SELECT ${TP(`a.`)} ${oF}
|
|
386
386
|
AND json_extract(a.data_json, '$.work') IS NULL
|
|
387
387
|
AND a.origin_kind = 'user'
|
|
388
388
|
AND (? IS NULL OR json_extract(json_extract(a.data_json, '$.meta'), ?) = ?)
|
|
389
|
-
ORDER BY a.sequence DESC LIMIT 1`,t,n?.path??null,n?.path??null,n?.value??null).toArray()[0];return r===void 0?void 0:
|
|
389
|
+
ORDER BY a.sequence DESC LIMIT 1`,t,n?.path??null,n?.path??null,n?.value??null).toArray()[0];return r===void 0?void 0:QP(r)}var fF=O(P({total:H.check(V(0))}));function pF(e,t,n,r=`all`){let i=r===`prompts`?`AND json_extract(a.data_json, '$.work') IS NULL`:``,a=fF(e.sql.exec(`SELECT COUNT(*) AS total ${oF} ${i}`,t).one()).total;return{commands:e.sql.exec(`SELECT ${TP(`a.`)} ${oF} ${i}
|
|
390
390
|
ORDER BY (json_extract(a.data_json, '$.delivery') = 'steer') DESC,
|
|
391
|
-
a.sequence ASC LIMIT ?`,t,n).toArray().map(
|
|
391
|
+
a.sequence ASC LIMIT ?`,t,n).toArray().map(QP),total:a}}function mF(e,t,n,r,i=200){return e.sql.exec(`SELECT ${TP(`a.`)}
|
|
392
392
|
FROM session_command_admissions AS a
|
|
393
393
|
WHERE a.session_id = ?
|
|
394
394
|
AND json_extract(a.data_json, '$.delivery') = ?
|
|
@@ -398,26 +398,26 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
398
398
|
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
399
399
|
AND e.type IN ('command', 'run_terminal', 'work_terminal')
|
|
400
400
|
)
|
|
401
|
-
ORDER BY a.sequence ASC LIMIT ?`,t,n,r??null,r??null,i).toArray().map(
|
|
401
|
+
ORDER BY a.sequence ASC LIMIT ?`,t,n,r??null,r??null,i).toArray().map(QP)}function hF(e,t,n){return mF(e,t,`steer`,n,1).length>0}function gF(e,t,n,r){return e.transactionSync(()=>mF(e,t,n,r).map(n=>{let r=vj(nF(e,t,n.id)?.entry??nI(e,{sessionId:t,id:n.id,entry:n.entry}).entry);if(r===void 0)throw $(`Session control admission is invalid`);return{workId:r.workId,requestId:r.requestId,message:xj(r)}}))}function _F(e,t){e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${TP(`a.`)}
|
|
402
402
|
FROM session_command_admissions AS a
|
|
403
403
|
WHERE a.session_id = ?
|
|
404
404
|
AND json_extract(a.data_json, '$.delivery') = 'steer'
|
|
405
405
|
AND json_extract(a.data_json, '$.targetWorkId') = ?
|
|
406
|
-
ORDER BY a.sequence ASC`,t.sessionId,t.parentWorkId).toArray().map(
|
|
406
|
+
ORDER BY a.sequence ASC`,t.sessionId,t.parentWorkId).toArray().map(QP);for(let r of n){if(e.sql.exec(`SELECT 1 AS present FROM session_entries WHERE session_id = ? AND work_id = ? AND type IN ('run_terminal', 'work_terminal') LIMIT 1`,t.sessionId,r.entry.workId).toArray()[0]!==void 0)continue;if(nF(e,t.sessionId,r.id)===void 0){t.enqueue({jobId:r.entry.workId,sessionId:t.sessionId,commandFactId:r.id,delivery:`steer`});continue}let n=t.outcome===`failed`||t.outcome===`interrupted`?t.diagnostic:void 0,i={kind:`work_terminal`,workId:r.entry.workId,outcome:t.outcome};n!==void 0&&(i={...i,diagnostic:n}),nI(e,{sessionId:t.sessionId,id:Tj.fact.generate(),entry:i})}})}function vF(e,t,n){return aF(e,t,{id:n})}function yF(e,t,n){return aF(e,t,{workId:n})}function bF(e,t,n){return aF(e,t,{requestId:n})}function xF(e,t,n){return tF(e,t),e.sql.exec(`SELECT 1 AS present FROM session_entries
|
|
407
407
|
INDEXED BY idx_session_entries_work_terminal
|
|
408
408
|
WHERE session_id = ? AND work_id = ?
|
|
409
409
|
AND type IN ('run_terminal', 'work_terminal')
|
|
410
|
-
LIMIT 1`,t,n).toArray().length>0}function
|
|
410
|
+
LIMIT 1`,t,n).toArray().length>0}function SF(e,t,n){return tF(e,t),Object.freeze(e.sql.exec(`SELECT ${zP}
|
|
411
411
|
FROM session_entries
|
|
412
412
|
WHERE session_id = ? AND work_id = ?
|
|
413
|
-
ORDER BY sequence ASC`,t,n).toArray().map(t=>
|
|
413
|
+
ORDER BY sequence ASC`,t,n).toArray().map(t=>ZP(e,t)))}function CF(e,t,n){let r=e.sql.exec(`SELECT ${zP}
|
|
414
414
|
FROM session_entries
|
|
415
415
|
WHERE session_id = ? AND work_id = ? AND type = 'live_retry'
|
|
416
416
|
ORDER BY sequence DESC
|
|
417
|
-
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=
|
|
417
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=ZP(e,r);if(i.entry.kind!==`live_retry`)throw $(`Stored live retry entry is invalid`);return{event:i.entry.event,timestamp:i.timestamp}}function wF(e,t,n,r){return e.sql.exec(`SELECT 1 FROM session_entries INDEXED BY idx_session_entries_successful_tool
|
|
418
418
|
WHERE session_id = ? AND work_id = ? AND type = 'tool_outcome'
|
|
419
419
|
AND json_extract(data_json, '$.result.isError') = 0
|
|
420
|
-
AND json_extract(data_json, '$.call.id') = ? LIMIT 1`,t,n,r).toArray().length>0}function
|
|
420
|
+
AND json_extract(data_json, '$.call.id') = ? LIMIT 1`,t,n,r).toArray().length>0}function TF(e,t,n){let r=e.sql.exec(`SELECT ${RP(`intent`)}
|
|
421
421
|
FROM session_entries AS intent
|
|
422
422
|
WHERE intent.session_id = ? AND intent.work_id = ?
|
|
423
423
|
AND intent.type = 'tool_intent'
|
|
@@ -430,9 +430,9 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
430
430
|
json_extract(intent.data_json, '$.toolCall.value')
|
|
431
431
|
)
|
|
432
432
|
ORDER BY intent.sequence DESC
|
|
433
|
-
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=
|
|
433
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=ZP(e,r);if(i.entry.kind!==`tool_intent`)throw $(`Stored tool intent is invalid`);return i.entry.call.name}function EF(e,t){let n=IP(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
434
434
|
FROM session_entries
|
|
435
|
-
WHERE session_id = ?`,t).one());if(n._tag===`Failure`)throw $(`Next Session sequence is invalid`);return n.success.next_sequence}function
|
|
435
|
+
WHERE session_id = ?`,t).one());if(n._tag===`Failure`)throw $(`Next Session sequence is invalid`);return n.success.next_sequence}function DF(e,t){let n=IP(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
436
436
|
FROM (
|
|
437
437
|
SELECT sequence
|
|
438
438
|
FROM session_command_admissions
|
|
@@ -441,9 +441,9 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
441
441
|
SELECT sequence
|
|
442
442
|
FROM session_entries
|
|
443
443
|
WHERE session_id = ? AND type = 'command'
|
|
444
|
-
)`,t,t).one());if(n._tag===`Failure`)throw $(`Next command admission sequence is invalid`);return n.success.next_sequence}function
|
|
444
|
+
)`,t,t).one());if(n._tag===`Failure`)throw $(`Next command admission sequence is invalid`);return n.success.next_sequence}function OF(e,t){let n=tF(e,t);if(n!==void 0)return n;let r=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
445
445
|
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
446
|
-
VALUES (?, '/', NULL, NULL, ?, ?, NULL)`,t,r,r),
|
|
446
|
+
VALUES (?, '/', NULL, NULL, ?, ?, NULL)`,t,r,r),dN(e,{sessionId:t,activityAt:r,title:``});let i=tF(e,t);if(i===void 0)throw $(`Created Session row is unavailable`);return i}function kF(e,t,n){return e.transactionSync(()=>AF(e,t,n))}function AF(e,t,n){let r=e.sql.exec(`SELECT session_id FROM session_creation_receipts WHERE request_id = ?`,t).toArray()[0];if(r!==void 0){let e=OP(r);if(e._tag===`Failure`)throw $(`Session creation receipt is invalid`);return e.success.session_id}n();let i=Tj.session.generate();return OF(e,i),e.sql.exec(`INSERT INTO session_creation_receipts (request_id, session_id) VALUES (?, ?)`,t,i),i}function jF(e,t){return e.transactionSync(()=>{if(!(e.sql.exec(`SELECT id FROM sessions WHERE id = ?`,t.sessionId).toArray().length>0))return!1;t.assertIdleSession(t.sessionId),t.recordInboxDeletion(t.sessionId);for(let n of[`DELETE FROM session_command_admissions WHERE session_id = ?`,`DELETE FROM session_attention WHERE session_id = ?`,`DELETE FROM session_work_senders WHERE session_id = ?`,`DELETE FROM session_tool_grants WHERE session_id = ?`,`DELETE FROM session_inbox WHERE session_id = ?`,`DELETE FROM session_creation_receipts WHERE session_id = ?`,`DELETE FROM sessions WHERE id = ?`,`DELETE FROM session_entries WHERE session_id = ?`,`DELETE FROM session_lineage_damage WHERE session_id = ?`])e.sql.exec(n,t.sessionId);return!0})}var MF=6,NF=1,PF=`shiitake.extension/v0`;function FF(e,t){let n=e.sql.exec(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`,t).toArray()[0];if(n===void 0)return!1;if(MP(n)._tag===`Failure`)throw $(`Store catalog row is invalid`);return!0}function IF(e){if(!FF(e,`woodstock_schema`))return FF(e,`sessions`)?`unmarked`:`fresh`;if(!e.sql.exec(`PRAGMA table_info(woodstock_schema)`).toArray().some(e=>e.name===`protocol`))return`unmarked`;let t=e.sql.exec(`SELECT version, protocol FROM woodstock_schema`).toArray();if(t.length!==1)return`unmarked`;let n=jP(t[0]);if(n._tag!==`Success`)return`unmarked`;let r=n.success.version;return r>MF?`newer`:n.success.protocol===PF?r===MF?`v0`:r>=NF&&r<MF?`upgradable`:`unmarked`:`unmarked`}function LF(e){$N(e),e.sql.exec(`UPDATE woodstock_schema SET version = ?`,MF)}function RF(e){let t=IF(e);if(t!==`v0`){if(t===`upgradable`){LF(e);return}if(t===`newer`)throw qP(`This Agent was saved by a newer Fungi. Update Fungi to open it. Its files have not been changed.`);if(t===`unmarked`)throw qP(`Fungi cannot read this Agent store. Its files have not been changed.`);e.sql.exec(`CREATE TABLE woodstock_schema (version INTEGER NOT NULL, protocol TEXT NOT NULL)`),e.sql.exec(`INSERT INTO woodstock_schema (version, protocol) VALUES (?, ?)`,MF,PF)}}function zF(e){e.sql.exec(`
|
|
447
447
|
CREATE TABLE IF NOT EXISTS session_entries (
|
|
448
448
|
id TEXT PRIMARY KEY,
|
|
449
449
|
session_id TEXT NOT NULL,
|
|
@@ -459,9 +459,9 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
459
459
|
completed_at INTEGER,
|
|
460
460
|
UNIQUE (session_id, sequence)
|
|
461
461
|
)
|
|
462
|
-
`)}var
|
|
462
|
+
`)}var BF=[`session_entries_lineage_insert`,`session_entries_lineage_update`,`session_entries_lineage_delete`,`session_entries_damaged_session`,`session_entries_lineage_replace`,`session_entries_lineage_replace_position`],VF=D(P({installed:H.pipe(z(V(0)))}),aP),HF=D(P({session_id:M}),aP),UF=`Woodstock Session holds a broken lineage; a store never repairs itself — delete this Session (deleteSession), or reset the owning store`,WF=D(P({damaged:H.pipe(z(Zm(0))),first:M}),aP),GF=class extends W{store;sessionId;constructor(e,t,n){super(`store`,`unavailable`,n),this.store=e,this.sessionId=t}get diagnostic(){return`${this.store}: Woodstock Session ${this.sessionId} holds a broken lineage; delete it with deleteSession("${this.sessionId}"), or reset the owning store`}};function KF(e,t){let n=e.storeName??`Woodstock store`;return new GF(n,t,`${n}: ${JF(e,t)}`)}function qF(e,t){return e.sql.exec(`SELECT session_id FROM session_lineage_damage WHERE session_id = ?`,t).toArray().length>0}function JF(e,t){let n=WF(e.sql.exec(`SELECT COUNT(*) AS damaged, MIN(session_id) AS first FROM session_lineage_damage`).one());if(n._tag===`Failure`)throw $(`Stored Session lineage damage is invalid`);let{damaged:r,first:i}=n.success;return`Woodstock Session ${t} holds a broken lineage (this store has ${String(r)} damaged Session${r===1?``:`s`}, first ${i}); a store never repairs itself — delete this Session with deleteSession("${t}"), or reset the owning store: for a Durable Object, erase all of its storage (DurableObjectStorage.deleteAll(); a Hub Agent is erased only with its Team, POST /operator/teams/:teamId/erasure-durable-objects); for a local store, remove its file and the file's .owner.sqlite sidecar`}function YF(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_lineage_damage (session_id TEXT PRIMARY KEY)`);let t=VF(e.sql.exec(`SELECT COUNT(*) AS installed FROM sqlite_master
|
|
463
463
|
WHERE type = 'trigger'
|
|
464
|
-
AND name IN (SELECT value FROM json_each(?))`,JSON.stringify(
|
|
464
|
+
AND name IN (SELECT value FROM json_each(?))`,JSON.stringify(BF)).one());if(t._tag===`Failure`)throw $(`Stored Session lineage guards are invalid`);if(t.success.installed!==BF.length){let t=e.sql.exec(`SELECT child.session_id AS session_id
|
|
465
465
|
FROM session_entries AS child
|
|
466
466
|
LEFT JOIN session_entries AS parent ON parent.id = child.parent_id
|
|
467
467
|
WHERE child.parent_id IS NOT NULL
|
|
@@ -472,7 +472,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
472
472
|
UNION
|
|
473
473
|
SELECT session_id FROM session_entries
|
|
474
474
|
WHERE parent_id IS NULL AND state = 'complete'
|
|
475
|
-
GROUP BY session_id HAVING COUNT(*) > 1`).toArray().map(e=>{let t=
|
|
475
|
+
GROUP BY session_id HAVING COUNT(*) > 1`).toArray().map(e=>{let t=HF(e);if(t._tag===`Failure`)throw $(`Stored Session lineage audit is invalid`);return t.success.session_id});for(let n of t)e.sql.exec(`INSERT OR IGNORE INTO session_lineage_damage (session_id) VALUES (?)`,n),dN(e,{sessionId:n,title:null})}e.sql.exec(`
|
|
476
476
|
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_replace
|
|
477
477
|
BEFORE INSERT ON session_entries
|
|
478
478
|
WHEN EXISTS (
|
|
@@ -502,7 +502,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
502
502
|
WHEN EXISTS (
|
|
503
503
|
SELECT 1 FROM session_lineage_damage WHERE session_id = NEW.session_id)
|
|
504
504
|
BEGIN
|
|
505
|
-
SELECT RAISE(ABORT, '${
|
|
505
|
+
SELECT RAISE(ABORT, '${UF}');
|
|
506
506
|
END
|
|
507
507
|
`),e.sql.exec(`
|
|
508
508
|
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_insert
|
|
@@ -537,7 +537,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
537
537
|
BEGIN
|
|
538
538
|
SELECT RAISE(ABORT, 'Session entry still has children');
|
|
539
539
|
END
|
|
540
|
-
`)}function
|
|
540
|
+
`)}function XF(e){e.transactionSync(()=>{ZF(e)})}function ZF(e){RF(e),e.sql.exec(`
|
|
541
541
|
CREATE TABLE IF NOT EXISTS sessions (
|
|
542
542
|
id TEXT PRIMARY KEY,
|
|
543
543
|
cwd TEXT NOT NULL,
|
|
@@ -547,7 +547,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
547
547
|
updated_at INTEGER NOT NULL,
|
|
548
548
|
metadata_json TEXT
|
|
549
549
|
)
|
|
550
|
-
`),
|
|
550
|
+
`),zF(e),sM(e),Dk(e),gA(e),lA(e),zM(e),cN(e),e.sql.exec(`
|
|
551
551
|
CREATE TABLE IF NOT EXISTS session_creation_receipts (
|
|
552
552
|
request_id TEXT PRIMARY KEY,
|
|
553
553
|
session_id TEXT NOT NULL UNIQUE REFERENCES sessions(id)
|
|
@@ -568,7 +568,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
568
568
|
ON session_entries(session_id, json_extract(data_json, '$.targetWorkId'))
|
|
569
569
|
WHERE type = 'cancellation'`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_successful_tool
|
|
570
570
|
ON session_entries(session_id, work_id, json_extract(data_json, '$.call.id'))
|
|
571
|
-
WHERE type = 'tool_outcome' AND json_extract(data_json, '$.result.isError') = 0`),
|
|
571
|
+
WHERE type = 'tool_outcome' AND json_extract(data_json, '$.result.isError') = 0`),YF(e),e.sql.exec(`
|
|
572
572
|
CREATE TABLE IF NOT EXISTS session_request_withdrawals (
|
|
573
573
|
session_id TEXT NOT NULL,
|
|
574
574
|
request_id TEXT NOT NULL,
|
|
@@ -593,14 +593,14 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
593
593
|
UNIQUE (session_id, request_id),
|
|
594
594
|
UNIQUE (session_id, work_id)
|
|
595
595
|
)
|
|
596
|
-
`),
|
|
596
|
+
`),Rj(e)}function QF(e,t){let n=tF(e,t)?.leaf_id;return n==null?null:AI(e,t,n)}function $F(e,t){let n=tF(e,t)?.leaf_id;return n==null?null:kI(e,t,n)?.sequence??null}function eI(e,t,n){return e.transactionSync(()=>nI(e,{sessionId:t,id:Tj.fact.generate(),entry:{kind:`model_preference`,workId:null,preference:n}}))}function tI(e,t,n){e.transactionSync(()=>{OF(e,t);let r=n===null?null:hP({title:n});e.sql.exec(`SELECT 1 FROM sessions WHERE id = ? AND metadata_json IS ?`,t,r).toArray().length>0||(e.sql.exec(`UPDATE sessions SET metadata_json = ? WHERE id = ?`,r,t),dN(e,{sessionId:t,title:KP(e,t)}))})}function nI(e,t){let n=rF(e,OF(e,t.sessionId)),r=t.state??`complete`;if(r===`streaming`!=(t.entry.kind===`message_start`))throw $(`A message start must be the streaming entry`);if(r===`streaming`&&t.entry.kind===`message_start`&&t.id!==t.entry.message.value)throw $(`Message placeholder identity does not match its row`);let i=Date.now(),a=EF(e,t.sessionId);e.sql.exec(`INSERT INTO session_entries
|
|
597
597
|
(id, session_id, parent_id, sequence, type, role, state,
|
|
598
598
|
request_id, work_id, data_json, timestamp, completed_at)
|
|
599
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.id,t.sessionId,n?.id??null,a,t.entry.kind,
|
|
599
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.id,t.sessionId,n?.id??null,a,t.entry.kind,YP(t.entry),r,JP(t.entry),t.entry.workId,wj(t.entry),i,r===`complete`?i:null),r===`complete`&&(e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,t.id,i,t.sessionId),dN(e,t.entry.kind===`command`?{sessionId:t.sessionId,activityAt:i,title:KP(e,t.sessionId)}:{sessionId:t.sessionId,activityAt:i}));let o=nF(e,t.sessionId,t.id);if(o===void 0)throw $(`Appended Session entry is unavailable`);return o}function rI(e,t){let n=rF(e,OF(e,t.sessionId)),r=nF(e,t.sessionId,t.id),i=Date.now(),a=r?.state===`streaming`&&r.parentId!==(n?.id??null),o=a?n?.id??null:r?.parentId??n?.id??null,s=a?EF(e,t.sessionId):r?.sequence??EF(e,t.sessionId),c=r?.timestamp??i;if(t.id!==t.entry.message.value)throw $(`Completed message identity does not match its row`);if(r!==void 0){let e=r.entry;if(e.kind!==`message_start`&&e.kind!==`message`)throw $(`Completed Session leaf is not a message entry`);if(e.workId!==t.entry.workId||!XP(e.run,t.entry.run)||!XP(e.turn,t.entry.turn)||!XP(e.message,t.entry.message)||e.kind===`message_start`&&e.role!==t.entry.value.role)throw $(`Completed message does not match its placeholder`)}e.sql.exec(`INSERT OR REPLACE INTO session_entries
|
|
600
600
|
(id, session_id, parent_id, sequence, type, role, state,
|
|
601
601
|
request_id, work_id, data_json, timestamp, completed_at)
|
|
602
602
|
VALUES (?, ?, ?, ?, 'message', ?, 'complete',
|
|
603
|
-
NULL, ?, ?, ?, ?)`,t.id,t.sessionId,o,s,
|
|
603
|
+
NULL, ?, ?, ?, ?)`,t.id,t.sessionId,o,s,YP(t.entry),t.entry.workId,wj(t.entry),c,i),e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,t.id,i,t.sessionId),dN(e,{sessionId:t.sessionId,activityAt:i});let l=nF(e,t.sessionId,t.id);if(l===void 0)throw $(`Completed Session leaf is unavailable`);return l}var iI=4e3,aI=4194304,oI={selected:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
|
|
604
604
|
SELECT id, parent_id, sequence, state
|
|
605
605
|
FROM session_entries
|
|
606
606
|
WHERE session_id = ? AND id = ?
|
|
@@ -622,10 +622,10 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
622
622
|
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
623
623
|
AND child.sequence > ?
|
|
624
624
|
AND parent.state != 'streaming'
|
|
625
|
-
)`},
|
|
625
|
+
)`},sI={selected:{empty:`Selected Session leaf is unavailable`,missingParent:`Selected Session path has a missing parent`,invalid:`Selected Session path is invalid`},fork:{empty:`Fork entry is unavailable`,missingParent:`Fork path has a missing parent`,invalid:`Fork path is invalid`}},cI=D(P({id:sP,parent_id:R(M),sequence:cP,state:L([`complete`,`streaming`])}),aP),lI=new WeakMap;function uI(e,t,n,r=2**53-1){let i=lI.get(e);lI.set(e,{sessionId:t,before:r,encoded:new Map});try{return e.transactionSync(n)}finally{i===void 0?lI.delete(e):lI.set(e,i)}}function dI(e,t,n){return lI.get(e)?.sessionId===t?n():e.transactionSync(n)}function fI(e,t,n,r){let i=lI.get(e);if(i?.sessionId!==t)return;i.ancestry??=e.sql.exec(`WITH RECURSIVE read_window (before_sequence, rows) AS (VALUES (?, ?)),
|
|
626
626
|
ancestry (id, parent_id, sequence, state, head, context_closed, taken) AS (
|
|
627
627
|
SELECT id, parent_id, sequence, state,
|
|
628
|
-
${
|
|
628
|
+
${BI(`session_entries`)}, 0,
|
|
629
629
|
CASE WHEN state != 'streaming'
|
|
630
630
|
AND sequence < (SELECT before_sequence FROM read_window)
|
|
631
631
|
THEN 1 ELSE 0 END
|
|
@@ -633,7 +633,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
633
633
|
WHERE session_id = ? AND id = ?
|
|
634
634
|
UNION ALL
|
|
635
635
|
SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
|
|
636
|
-
COALESCE(child.head, ${
|
|
636
|
+
COALESCE(child.head, ${BI(`parent`)}),
|
|
637
637
|
child.context_closed OR
|
|
638
638
|
(child.head IS child.id AND child.state != 'streaming'),
|
|
639
639
|
child.taken + CASE WHEN parent.state != 'streaming'
|
|
@@ -650,13 +650,13 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
650
650
|
SELECT id, parent_id, sequence, state FROM ancestry
|
|
651
651
|
WHERE context_closed = 0
|
|
652
652
|
OR sequence <= (SELECT before_sequence FROM read_window)
|
|
653
|
-
ORDER BY sequence DESC`,i.before,201,t,n,t).toArray().map(e=>{let t=
|
|
653
|
+
ORDER BY sequence DESC`,i.before,201,t,n,t).toArray().map(e=>{let t=cI(e);if(t._tag===`Failure`)throw $(`Stored Session ancestry is invalid`);return t.success});let a=i.ancestry.findIndex(({id:e})=>e===n);if(a===-1)return;let o=i.ancestry.slice(a);if(r!==void 0){let e=o.at(-1);if(e!==void 0&&e.parent_id!==null&&e.sequence>r.floor+1)return;let t=r.ceiling??2**53-1;for(let e=1;e<o.length;e+=1){let n=o[e-1],i=o[e];if(n!==void 0&&i!==void 0&&n.parent_id!==i.id&&r.floor<n.sequence-1&&t>i.sequence)return}}let s=i.encoded.get(n);if(s!==void 0)return s;let c=JSON.stringify(o);return i.encoded.set(n,c),c}function pI(e){return`${e} AS MATERIALIZED (
|
|
654
654
|
SELECT json_extract(value, '$.id') AS id,
|
|
655
655
|
json_extract(value, '$.parent_id') AS parent_id,
|
|
656
656
|
json_extract(value, '$.sequence') AS sequence,
|
|
657
657
|
json_extract(value, '$.state') AS state
|
|
658
658
|
FROM json_each(?)
|
|
659
|
-
)`}var
|
|
659
|
+
)`}var mI=H.pipe(z(V(0))),hI=D(P({length:mI,root_id:R(sP),root_parent_id:R(M),broken:mI,newest_id:R(sP),newest_sequence:R(cP)}),aP),gI=D(P({sequence:cP}),aP),_I=D(P({work_id:sP}),aP),vI=D(P({work_id:sP,diagnostic:M}),aP);function yI(e,t,n,r,...i){let a=t.walk===`selected`?fI(e,t.sessionId,t.tipId,n):void 0;return a===void 0?e.sql.exec(`${oI[t.walk]} ${r}`,t.sessionId,t.tipId,t.sessionId,n.floor,...i).toArray():e.sql.exec(`WITH ${pI(`branch`)} ${r}`,a,...i).toArray()}function bI(e,t,n,r){let i=sI[r],a=hI(e.sql.exec(`${oI[r]},
|
|
660
660
|
kept AS MATERIALIZED (
|
|
661
661
|
SELECT id, parent_id, sequence FROM branch
|
|
662
662
|
WHERE state != 'streaming'
|
|
@@ -674,7 +674,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
674
674
|
WHERE previous IS NOT NULL AND parent_id IS NOT previous) AS broken,
|
|
675
675
|
(SELECT id FROM kept ORDER BY sequence DESC LIMIT 1) AS newest_id,
|
|
676
676
|
(SELECT sequence FROM kept ORDER BY sequence DESC LIMIT 1)
|
|
677
|
-
AS newest_sequence`,t,n,t,0).one());if(a._tag===`Failure`)throw $(`Stored Session lineage check is invalid`);let o=a.success;if(o.length===0||o.root_id===null||o.newest_id===null||o.newest_sequence===null)throw $(i.empty);if(o.root_parent_id!==null)throw $(i.missingParent);if(o.broken!==0)throw $(i.invalid);return Object.freeze({sessionId:t,walk:r,tipId:n,rootId:o.root_id,newestId:o.newest_id,newestSequence:o.newest_sequence})}var
|
|
677
|
+
AS newest_sequence`,t,n,t,0).one());if(a._tag===`Failure`)throw $(`Stored Session lineage check is invalid`);let o=a.success;if(o.length===0||o.root_id===null||o.newest_id===null||o.newest_sequence===null)throw $(i.empty);if(o.root_parent_id!==null)throw $(i.missingParent);if(o.broken!==0)throw $(i.invalid);return Object.freeze({sessionId:t,walk:r,tipId:n,rootId:o.root_id,newestId:o.newest_id,newestSequence:o.newest_sequence})}var xI=D(P({state:L([`complete`,`streaming`]),newest_sequence:cP,root_id:R(sP),root_parent_id:R(M)}),aP);function SI(e,t){let n=tF(e,t.sessionId),r=t.leafId??n?.leaf_id;if(r==null)return;let i=sI.selected,a=e.sql.exec(`SELECT tip.state AS state, tip.sequence AS newest_sequence,
|
|
678
678
|
root.id AS root_id, root.parent_id AS root_parent_id
|
|
679
679
|
FROM session_entries AS tip
|
|
680
680
|
LEFT JOIN (
|
|
@@ -682,12 +682,12 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
682
682
|
WHERE session_id = ? AND state = 'complete'
|
|
683
683
|
ORDER BY sequence ASC LIMIT 1
|
|
684
684
|
) AS root
|
|
685
|
-
WHERE tip.session_id = ? AND tip.id = ?`,t.sessionId,t.sessionId,r).toArray()[0];if(a===void 0)throw $(i.empty);let o=
|
|
685
|
+
WHERE tip.session_id = ? AND tip.id = ?`,t.sessionId,t.sessionId,r).toArray()[0];if(a===void 0)throw $(i.empty);let o=xI(a);if(o._tag===`Failure`)throw $(`Stored Session lineage ends are invalid`);if(o.success.state!==`complete`||o.success.root_id===null)throw $(i.empty);if(o.success.root_parent_id!==null)throw $(i.missingParent);return Object.freeze({sessionId:t.sessionId,walk:`selected`,tipId:r,rootId:o.success.root_id,newestId:r,newestSequence:o.success.newest_sequence})}function CI(e,t,n,r){let i=Object.freeze(yI(e,t,{floor:n-1,ceiling:r},`SELECT ${zP}
|
|
686
686
|
FROM session_entries
|
|
687
687
|
WHERE session_id = ? AND state != 'streaming'
|
|
688
688
|
AND sequence BETWEEN ? AND ?
|
|
689
689
|
AND id IN (SELECT id FROM branch)
|
|
690
|
-
ORDER BY sequence ASC`,t.sessionId,n,r).map(t=>
|
|
690
|
+
ORDER BY sequence ASC`,t.sessionId,n,r).map(t=>ZP(e,t))),a=sI.selected,o=i[0];if(o!==void 0&&o.parentId!==null&&o.sequence!==n)throw $(a.missingParent);let s;for(let e of i){if(s!==void 0&&e.parentId!==s.id)throw $(a.invalid);s=e}return i}var wI=D(P({sizes:U(F(mm([cP,mI]))),deepest_parent:R(M),deepest_sequence:R(cP)}),aP);function TI(e,t,n,r,i,a){let o=t.walk===`selected`?fI(e,t.sessionId,t.tipId):void 0;if(o!==void 0){let s=lI.get(e)?.ancestry?.filter(e=>e.sequence<=t.newestSequence&&e.state!==`streaming`&&e.sequence>r&&e.sequence<i),c=n===`newest`?s?.[a-1]:void 0;o=fI(e,t.sessionId,t.tipId,{floor:c===void 0?r:c.sequence-1,ceiling:i-1})}let s=n===`newest`?`DESC`:`ASC`,c=`SELECT
|
|
691
691
|
(SELECT json_group_array(json_array(sequence, bytes)) FROM (
|
|
692
692
|
SELECT sequence, octet_length(data_json) AS bytes
|
|
693
693
|
FROM session_entries
|
|
@@ -702,7 +702,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
702
702
|
(SELECT sequence FROM branch ORDER BY sequence ASC LIMIT 1)
|
|
703
703
|
AS deepest_sequence`,l=e=>`CASE WHEN ${e}.state != 'streaming'
|
|
704
704
|
AND ${e}.sequence < ? AND ${e}.sequence > ?
|
|
705
|
-
THEN 1 ELSE 0 END`,u=
|
|
705
|
+
THEN 1 ELSE 0 END`,u=wI((o===void 0?n===`newest`?e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, state, taken) AS (
|
|
706
706
|
SELECT id, parent_id, sequence, state,
|
|
707
707
|
${l(`session_entries`)}
|
|
708
708
|
FROM session_entries
|
|
@@ -716,26 +716,26 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
716
716
|
AND +parent.sequence < child.sequence
|
|
717
717
|
AND child.taken < ? AND child.sequence > ?
|
|
718
718
|
)
|
|
719
|
-
${c}`,i,r,t.sessionId,t.tipId,i,r,t.sessionId,a,r,r,i,a).toArray():
|
|
719
|
+
${c}`,i,r,t.sessionId,t.tipId,i,r,t.sessionId,a,r,r,i,a).toArray():yI(e,t,{floor:r},c,t.sessionId,r,i,a):e.sql.exec(`WITH ${pI(`branch`)},
|
|
720
720
|
candidates AS MATERIALIZED (
|
|
721
721
|
SELECT id FROM branch
|
|
722
722
|
WHERE state != 'streaming' AND sequence > ? AND sequence < ?
|
|
723
723
|
ORDER BY sequence ${s} LIMIT ?
|
|
724
|
-
) ${c}`,o,r,i,a,...n===`newest`?[]:[t.sessionId],r,i,a).toArray())[0]);if(u._tag===`Failure`)throw $(`Stored Session entry size is invalid`);let{sizes:d,deepest_parent:f,deepest_sequence:p}=u.success;if(!(f===null||p===null||p<=r||n===`newest`&&d.length===a))throw $(
|
|
724
|
+
) ${c}`,o,r,i,a,...n===`newest`?[]:[t.sessionId],r,i,a).toArray())[0]);if(u._tag===`Failure`)throw $(`Stored Session entry size is invalid`);let{sizes:d,deepest_parent:f,deepest_sequence:p}=u.success;if(!(f===null||p===null||p<=r||n===`newest`&&d.length===a))throw $(sI.selected.missingParent);return Object.freeze(d.map(([e,t])=>({sequence:e,bytes:t})).sort((e,t)=>n===`newest`?t.sequence-e.sequence:e.sequence-t.sequence))}function EI(e,t,n){let r=TI(e,t,n.from,n.after??0,n.before??2**53-1,n.rows+1),i=0,a=0;for(let e of r){if(i===n.rows||i>0&&a+e.bytes>aI)break;a+=e.bytes,i+=1}let o=r[0],s=r[i-1];return Object.freeze(o===void 0||s===void 0?{rows:Object.freeze([]),more:!1}:{rows:CI(e,t,Math.min(o.sequence,s.sequence),Math.max(o.sequence,s.sequence)),more:r.length>i})}function DI(e,t,n){return yI(e,t,{floor:n-1,ceiling:n},`SELECT 1 AS present
|
|
725
725
|
FROM session_entries
|
|
726
726
|
WHERE session_id = ? AND state != 'streaming' AND sequence = ?
|
|
727
|
-
AND id IN (SELECT id FROM branch)`,t.sessionId,n).length>0}function
|
|
728
|
-
WHERE session_id = ? AND id = ? AND state != 'streaming'`,t.sessionId,n).toArray()[0];if(r===void 0)return;let i=
|
|
727
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,n).length>0}function OI(e,t,n){let r=e.sql.exec(`SELECT sequence FROM session_entries
|
|
728
|
+
WHERE session_id = ? AND id = ? AND state != 'streaming'`,t.sessionId,n).toArray()[0];if(r===void 0)return;let i=gI(r);if(i._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return DI(e,t,i.success.sequence)?i.success.sequence:void 0}function kI(e,t,n){let[r]=FI(e,t,n,`SELECT id, sequence FROM session_entries
|
|
729
729
|
WHERE session_id = ? AND type = 'model_preference'
|
|
730
730
|
AND state != 'streaming'`,[t],e=>`${e}.id NOT IN (SELECT id FROM targets)
|
|
731
|
-
AND ${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return r===void 0?void 0:
|
|
731
|
+
AND ${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return r===void 0?void 0:nF(e,t,r)}function AI(e,t,n){let r=kI(e,t,n)?.entry;return r?.kind===`model_preference`?r.preference:null}function jI(e,t,n,r){if(t===void 0)return;let i=yI(e,t,{floor:0},`SELECT ${zP}
|
|
732
732
|
FROM session_entries
|
|
733
733
|
WHERE session_id = ? AND state != 'streaming' AND type = 'document'
|
|
734
734
|
AND json_extract(data_json, '$.extensionId') = ?
|
|
735
735
|
AND json_extract(data_json, '$.name') = ?
|
|
736
736
|
AND id IN (SELECT id FROM branch)
|
|
737
737
|
ORDER BY sequence DESC
|
|
738
|
-
LIMIT 1`,t.sessionId,n,r)[0],a=i===void 0?void 0:
|
|
738
|
+
LIMIT 1`,t.sessionId,n,r)[0],a=i===void 0?void 0:ZP(e,i).entry;if(a!==void 0){if(a.kind!==`document`||a.extensionId!==n||a.name!==r)throw $(`Stored Session document disagrees with its row`);return a.valueJson}}var MI=D(P({oldest:R(cP),newest:R(cP)}),aP);function NI(e,t,n){if(n.size===0)return Object.freeze({commands:new Set,diagnostics:new Map,cancellations:new Map});let r=JSON.stringify([...n]),i=MI(e.sql.exec(`SELECT MIN(oldest) AS oldest, MAX(newest) AS newest FROM (
|
|
739
739
|
SELECT MIN(sequence) AS oldest, MAX(sequence) AS newest
|
|
740
740
|
FROM session_entries INDEXED BY idx_session_entries_work
|
|
741
741
|
WHERE work_id IN (SELECT value FROM json_each(?))
|
|
@@ -746,11 +746,11 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
746
746
|
WHERE session_id = ? AND type = 'cancellation'
|
|
747
747
|
AND json_extract(data_json, '$.targetWorkId')
|
|
748
748
|
IN (SELECT value FROM json_each(?))
|
|
749
|
-
)`,r,t.sessionId,t.sessionId,r).one());if(i._tag===`Failure`)throw $(`Stored Session work order is invalid`);if(i.success.oldest===null||i.success.newest===null)return Object.freeze({commands:new Set,diagnostics:new Map,cancellations:new Map});let a=i.success.oldest-1,o={floor:a,ceiling:i.success.newest},s=new Set(
|
|
749
|
+
)`,r,t.sessionId,t.sessionId,r).one());if(i._tag===`Failure`)throw $(`Stored Session work order is invalid`);if(i.success.oldest===null||i.success.newest===null)return Object.freeze({commands:new Set,diagnostics:new Map,cancellations:new Map});let a=i.success.oldest-1,o={floor:a,ceiling:i.success.newest},s=new Set(yI(e,t,o,`SELECT DISTINCT work_id
|
|
750
750
|
FROM session_entries
|
|
751
751
|
WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'command'
|
|
752
752
|
AND work_id IN (SELECT value FROM json_each(?))
|
|
753
|
-
AND id IN (SELECT id FROM branch)`,t.sessionId,a,r).map(e=>{let t=
|
|
753
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,a,r).map(e=>{let t=_I(e);if(t._tag===`Failure`)throw $(`Stored Session command work is invalid`);return t.success.work_id})),c=new Map;for(let n of yI(e,t,o,`SELECT work_id, diagnostic FROM (
|
|
754
754
|
SELECT work_id, sequence,
|
|
755
755
|
json_extract(data_json, '$.diagnostic') AS diagnostic
|
|
756
756
|
FROM session_entries
|
|
@@ -760,13 +760,13 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
760
760
|
AND id IN (SELECT id FROM branch)
|
|
761
761
|
)
|
|
762
762
|
WHERE diagnostic IS NOT NULL
|
|
763
|
-
ORDER BY sequence ASC`,t.sessionId,a,r)){let e=
|
|
763
|
+
ORDER BY sequence ASC`,t.sessionId,a,r)){let e=vI(n);if(e._tag===`Failure`)throw $(`Stored Session diagnostic is invalid`);c.set(e.success.work_id,e.success.diagnostic)}let l=new Map;for(let{entry:n}of yI(e,t,o,`SELECT ${zP}
|
|
764
764
|
FROM session_entries
|
|
765
765
|
WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'cancellation'
|
|
766
766
|
AND json_extract(data_json, '$.targetWorkId')
|
|
767
767
|
IN (SELECT value FROM json_each(?))
|
|
768
768
|
AND id IN (SELECT id FROM branch)
|
|
769
|
-
ORDER BY sequence ASC`,t.sessionId,a,r).map(t=>
|
|
769
|
+
ORDER BY sequence ASC`,t.sessionId,a,r).map(t=>ZP(e,t)))n.kind===`cancellation`&&n.meta!==void 0&&l.set(n.targetWorkId,n.meta);return Object.freeze({commands:s,diagnostics:c,cancellations:l})}function PI(e,t,n,r){return r===void 0?{sql:`walk (id, parent_id, sequence, state) AS (
|
|
770
770
|
SELECT id, parent_id, sequence, state
|
|
771
771
|
FROM session_entries
|
|
772
772
|
WHERE session_id = ? AND id = ?
|
|
@@ -777,7 +777,7 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
777
777
|
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
778
778
|
AND +parent.sequence < child.sequence
|
|
779
779
|
AND ${n}
|
|
780
|
-
)`,bindings:[e,t,e],recursive:!0}:{sql:`${
|
|
780
|
+
)`,bindings:[e,t,e],recursive:!0}:{sql:`${pI(`ancestors`)},
|
|
781
781
|
stopped AS (
|
|
782
782
|
SELECT child.*,
|
|
783
783
|
COALESCE(SUM(CASE WHEN ${n} THEN 0 ELSE 1 END)
|
|
@@ -787,32 +787,32 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
787
787
|
),
|
|
788
788
|
walk AS (
|
|
789
789
|
SELECT id, parent_id, sequence, state FROM stopped WHERE stops = 0
|
|
790
|
-
)`,bindings:[r],recursive:!1}}function
|
|
790
|
+
)`,bindings:[r],recursive:!1}}function FI(e,t,n,r,i,a){let o=fI(e,t,n),s=o=>{let s=PI(t,n,a(`child`),o);return e.sql.exec(`WITH ${s.recursive?`RECURSIVE `:``}targets AS MATERIALIZED (
|
|
791
791
|
${r}
|
|
792
792
|
),
|
|
793
793
|
${s.sql}
|
|
794
|
-
${
|
|
794
|
+
${II(a(`walk`))}`,...i,...s.bindings).toArray()},c=s(o);if(o!==void 0){let r=c.at(-1);if(r!==void 0){let i=RI(r);if(i._tag===`Failure`)throw $(`Stored Session walk row is invalid`);(i.success.continues===1&&i.success.parent_id!==null||fI(e,t,n,{floor:i.success.sequence-1})===void 0)&&(c=s(void 0))}}return zI(c)}function II(e){return`SELECT id, parent_id, sequence, target, continues FROM (
|
|
795
795
|
SELECT id, parent_id, sequence,
|
|
796
796
|
id IN (SELECT id FROM targets) AS target,
|
|
797
797
|
COALESCE((${e}), 0) AS continues
|
|
798
798
|
FROM walk
|
|
799
799
|
)
|
|
800
800
|
WHERE target = 1 OR sequence = (SELECT MIN(sequence) FROM walk)
|
|
801
|
-
ORDER BY sequence DESC`}var
|
|
802
|
-
THEN json_extract(${e}.data_json, '$.head') END`}var
|
|
801
|
+
ORDER BY sequence DESC`}var LI=L([0,1]),RI=D(P({id:sP,parent_id:R(M),sequence:cP,target:LI,continues:LI}),aP);function zI(e){let t=sI.selected;if(e.length===0)throw $(t.empty);let n=e.map(e=>{let t=RI(e);if(t._tag===`Failure`)throw $(`Stored Session walk row is invalid`);return t.success}),r=n.at(-1);if(r?.continues===1&&r.parent_id!==null)throw $(t.missingParent);return n.flatMap(e=>e.target===1?[e.id]:[])}function BI(e){return`CASE WHEN ${e}.type = 'compaction' AND ${e}.state != 'streaming'
|
|
802
|
+
THEN json_extract(${e}.data_json, '$.head') END`}var VI=`WITH RECURSIVE walk (id, parent_id, sequence, state, head) AS (
|
|
803
803
|
SELECT id, parent_id, sequence, state,
|
|
804
|
-
${
|
|
804
|
+
${BI(`session_entries`)}
|
|
805
805
|
FROM session_entries
|
|
806
806
|
WHERE session_id = ? AND id = ?
|
|
807
807
|
UNION ALL
|
|
808
808
|
SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
|
|
809
|
-
COALESCE(child.head, ${
|
|
809
|
+
COALESCE(child.head, ${BI(`parent`)})
|
|
810
810
|
FROM walk AS child
|
|
811
811
|
CROSS JOIN session_entries AS parent
|
|
812
812
|
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
813
813
|
AND +parent.sequence < child.sequence
|
|
814
814
|
AND (child.head IS NOT child.id OR child.state = 'streaming')
|
|
815
|
-
)`;function
|
|
815
|
+
)`;function HI(e,t,n,r,i){let a=JSON.stringify(r.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[])),o=FI(e,t,n.id,`SELECT id, sequence FROM session_entries
|
|
816
816
|
WHERE session_id = ? AND type = 'compaction' AND work_id = ?
|
|
817
817
|
AND sequence < ? AND state != 'streaming'
|
|
818
818
|
UNION ALL
|
|
@@ -822,10 +822,10 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
822
822
|
WHERE session_id = ? AND type = 'cancellation'
|
|
823
823
|
AND json_extract(data_json, '$.targetWorkId')
|
|
824
824
|
IN (SELECT value FROM json_each(?))
|
|
825
|
-
AND sequence < ? AND state != 'streaming'`,[t,i,n.sequence,t,a,n.sequence],e=>`${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return o.length===0?Object.freeze([]):Object.freeze(e.sql.exec(`SELECT ${
|
|
825
|
+
AND sequence < ? AND state != 'streaming'`,[t,i,n.sequence,t,a,n.sequence],e=>`${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return o.length===0?Object.freeze([]):Object.freeze(e.sql.exec(`SELECT ${zP}
|
|
826
826
|
FROM session_entries
|
|
827
827
|
WHERE id IN (SELECT value FROM json_each(?))
|
|
828
|
-
ORDER BY sequence ASC`,JSON.stringify(o)).toArray().map(t=>
|
|
828
|
+
ORDER BY sequence ASC`,JSON.stringify(o)).toArray().map(t=>ZP(e,t)))}function UI(e,t,n){let r=sI.selected,i=fI(e,t,n);lI.get(e)?.ancestry?.[0]?.id!==n&&(i=void 0);let a=i===void 0?{sql:VI,bindings:[t,n,t]}:{sql:`WITH ${pI(`ancestors`)},
|
|
829
829
|
boundary AS (
|
|
830
830
|
SELECT sequence, json_extract(data_json, '$.head') AS head
|
|
831
831
|
FROM session_entries
|
|
@@ -843,27 +843,27 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
843
843
|
AND ancestors.sequence <= boundary.sequence
|
|
844
844
|
), 0)
|
|
845
845
|
)`,bindings:[i,t]},o=e.sql.exec(`${a.sql}
|
|
846
|
-
SELECT ${
|
|
846
|
+
SELECT ${zP}
|
|
847
847
|
FROM session_entries
|
|
848
848
|
WHERE id IN (SELECT id FROM walk) AND state != 'streaming'
|
|
849
|
-
ORDER BY sequence ASC`,...a.bindings).toArray().map(t=>
|
|
849
|
+
ORDER BY sequence ASC`,...a.bindings).toArray().map(t=>ZP(e,t)),s=o[0];if(s===void 0)throw $(r.empty);let c,l;for(let e of o){if(l!==void 0&&e.parentId!==l.id)throw $(r.invalid);e.entry.kind===`compaction`&&(c=e.entry.head),l=e}let u=c===s.id;if(!u&&s.parentId!==null)throw $(r.missingParent);return Object.freeze({rows:Object.freeze(o),compacted:u})}function WI(e,t){let n=tF(e,t.sessionId)?.leaf_id;if(n==null)return Object.freeze([]);let r=UI(e,t.sessionId,n),i=r.rows[0];return!r.compacted||i===void 0?r.rows:Object.freeze([...HI(e,t.sessionId,i,r.rows,t.workId??null),...r.rows])}function GI(e,t,n){return e.entry.kind===`compaction`&&e.entry.workId===t||e.entry.kind===`cancellation`&&n.has(e.entry.targetWorkId)}function KI(e,t,n,r,i){let a=SI(e,{sessionId:t,leafId:n.id});if(a===void 0)throw $(`Accepted Session command lineage is unavailable`);let o=r===void 0?[]:yI(e,r,{floor:n.sequence},`SELECT ${zP}
|
|
850
850
|
FROM session_entries
|
|
851
851
|
WHERE session_id = ? AND sequence > ? AND state != 'streaming'
|
|
852
852
|
AND id IN (SELECT id FROM branch)
|
|
853
853
|
AND (work_id = ?
|
|
854
854
|
OR (type = 'command'
|
|
855
855
|
AND json_extract(data_json, '$.targetWorkId') = ?))
|
|
856
|
-
ORDER BY sequence ASC`,t,n.sequence,i,i).map(t=>
|
|
856
|
+
ORDER BY sequence ASC`,t,n.sequence,i,i).map(t=>ZP(e,t)),s;for(let e of o)e.entry.kind===`compaction`&&(s=e.entry.head);let c=0,l;if(s===void 0){let r=UI(e,t,n.id);l=r.rows,r.compacted&&(c=r.rows[0]?.sequence??0)}else{let t=s;c=o.find(({id:e})=>e===t)?.sequence??OI(e,a,t)??0,l=c>n.sequence?[]:CI(e,a,Math.max(c,1),n.sequence)}if(c===0)return Object.freeze([...l,...o]);let u=[...l,...o.filter(({sequence:e})=>e>=c)],d=new Set(u.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[]));return Object.freeze([...HI(e,t,l[0]??n,u,i),...o.filter(e=>e.sequence<c&&GI(e,i,d)),...u])}function qI(e){let t=new Set,n=new Set;for(let{entry:r}of e)r.kind===`command`&&t.add(r.workId),r.kind===`cancellation`&&!t.has(r.targetWorkId)&&n.add(r.targetWorkId);return n}function JI(e,t){let n=qI(e),r;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.entry.kind===`compaction`){r=n;break}}let i=r?.entry.kind===`compaction`?r.entry:void 0,a=i===void 0?-1:e.findIndex(({id:e})=>e===i.head),o=a>=0?e.slice(a):e,s=nP(o,t),c=[];i!==void 0&&c.push(...i.model);for(let e of o){let t=vj(e.entry);t!==void 0&&!n.has(t.workId)&&c.push(xj(t)),e.entry.kind===`operator`&&c.push(bj(e.entry)),e.entry.kind===`message`&&s.has(e.id)&&c.push(e.entry.value)}return Object.freeze(c)}function YI(e,t){return e.transactionSync(()=>{let n=nF(e,t.sessionId,t.commandFactId),r=`replay`,i=vF(e,t.sessionId,t.commandFactId);if(n===void 0&&i!==void 0&&(n=nI(e,{sessionId:i.sessionId,id:i.id,entry:i.entry}),r=`new`),n?.entry.kind!==`command`)throw $(`Accepted Session command is unavailable`);if(i!==void 0&&wj(n.entry)!==wj(i.entry))throw $(`Accepted Session command disagrees with its admission`);let a=XI(e,t.sessionId,n.entry.workId),o=SF(e,t.sessionId,n.entry.workId),s=n.entry.workId,c=SI(e,{sessionId:t.sessionId}),l=KI(e,t.sessionId,n,c,s),u=Object.freeze({...n,entry:n.entry});return Object.freeze({command:u,modelPreference:AI(e,t.sessionId,n.id),messages:JI(l,n.entry.workId),path:l,entryDelivery:r,resume:eP(o),abnormalTerminal:iP(o),recoveredPartial:a})})}function XI(e,t,n){let r=SF(e,t,n).filter(({state:e})=>e===`streaming`),i=[...r].reverse().find(({entry:e})=>e.kind===`message_start`&&e.role===`assistant`&&(e.partial?.text.length??0)>0);for(let{id:n}of r)n!==i?.id&&e.sql.exec(`DELETE FROM session_entries WHERE session_id = ? AND id = ?`,t,n);return i?.entry.kind===`message_start`&&i.entry.partial?{messageId:i.id,...i.entry.partial}:void 0}function ZI(e,t){e.sql.exec(`UPDATE session_entries SET data_json = ? WHERE session_id = ? AND id = ? AND state = 'streaming'`,wj({...t.entry,partial:{text:t.text,offset:t.offset}}),t.sessionId,t.entry.message.value)}function QI(e,t){let n=tF(e,t.sessionId)?.leaf_id;if(n==null)return`stale`;let r=e.sql.exec(`${VI}
|
|
857
857
|
SELECT sequence
|
|
858
858
|
FROM session_entries
|
|
859
|
-
WHERE state != 'streaming' AND id = ? AND id IN (SELECT id FROM walk)`,t.sessionId,n,t.sessionId,t.head).toArray()[0];if(r===void 0)return`stale`;if(
|
|
859
|
+
WHERE state != 'streaming' AND id = ? AND id IN (SELECT id FROM walk)`,t.sessionId,n,t.sessionId,t.head).toArray()[0];if(r===void 0)return`stale`;if(gI(r)._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return`current`}function $I(e,t){return e.transactionSync(()=>{let n={kind:`compaction_notice`,workId:t.workId,trigger:t.trigger},r;if(t.result===`stale`||t.result===`insufficient`){let e={...n,result:t.result};r=t.usage===void 0?e:{...e,usage:t.usage}}else if(t.result===`failed`){let e={...n,result:`failed`},i=t.diagnostic===void 0?e:{...e,diagnostic:t.diagnostic.slice(0,200)};r=t.usage===void 0?i:{...i,usage:t.usage}}else{let e={...n,result:`nothing_to_compact`};r=t.diagnostic===void 0?e:{...e,diagnostic:t.diagnostic.slice(0,200)}}return nI(e,{sessionId:t.sessionId,id:Tj.fact.generate(),entry:r})})}D(P({session_id:M,work_id:M,timestamp:N,diagnostic:R(M)}),aP);function eL(e,t){return e.transactionSync(()=>nI(e,{sessionId:t.sessionId,id:Tj.fact.generate(),entry:{kind:`compaction_checkpoint`,workId:t.workId,trigger:t.trigger,resumesRun:t.resumesRun,head:t.head,contextRevision:t.contextRevision,summary:t.summary,tokensBefore:t.tokensBefore,usage:t.usage,details:t.details}}))}function tL(e){for(let t=e.length-1;t>=0;--t){let n=e[t]?.entry;if(n!==void 0){if(n.kind===`compaction`||n.kind===`compaction_notice`)return;if(n.kind===`compaction_checkpoint`)return n}}}function nL(e,t){return e.transactionSync(()=>iL(e,t))}function rL(e,t){return e.transactionSync(()=>QI(e,{sessionId:t.sessionId,head:t.head})===`stale`?`stale`:iL(e,t))}function iL(e,t){if(tF(e,t.sessionId)?.leaf_id!==t.expectedLeafId)throw new W(`store`,`conflict`,`Session leaf changed during compaction`);let n={kind:`compaction`,workId:t.workId,head:t.head,model:[pM(t.summary,Date.now())],data:{reason:t.trigger,resumesRun:t.resumesRun??!1,tokensBefore:t.tokensBefore,tokensAfter:t.tokensAfter,usage:t.usage,contextRevision:t.contextRevision}},r=t.receipt===void 0?n:{...n,data:{...n.data,receipt:t.receipt}};return nI(e,{sessionId:t.sessionId,id:Tj.fact.generate(),entry:t.details===void 0?r:{...r,data:{...r.data,details:t.details}}})}function aL(e){return Array.isArray(e)}function oL(e){if(e.images===void 0)return e.text;let t=[];return e.text.length>0&&t.push({type:`text`,text:e.text}),t.push(...e.images),t}function sL(e,t){return!aL(e)||!aL(t)?e===t:e.length===t.length&&e.every((e,n)=>{let r=t[n];return e.type===`text`?r?.type===`text`&&e.text===r.text:r?.type===`image`&&e.data===r.data&&e.mimeType===r.mimeType})}function cL(e,t){if(t.type===`compact`)return _j(e)&&e.instructions===t.instructions;let n=vj(e);return n?.delivery===t.delivery&&sL(n.message.content,oL(t))}function lL(e,t,n,r,i,a){let o={kind:`command`,requestId:e.requestId,receiptId:t,workId:t};if(e.type===`compact`){let t={...o,work:`compact`,timestamp:n,contract:r};return e.instructions===void 0?t:{...t,instructions:e.instructions}}let s={...o,delivery:e.delivery,message:{role:`user`,content:oL(e),timestamp:n},contract:r},c=i===void 0?s:{...s,targetWorkId:i};return a===void 0?c:{...c,reply:a}}function uL(e,t){return e?.agentId===t?.agentId&&e?.sessionId===t?.sessionId&&e?.outcome===t?.outcome&&(e?.outcome===`undeliverable`?t?.outcome===`undeliverable`&&e.reason===t.reason:t?.outcome!==`undeliverable`&&e?.commandId===t?.commandId&&e?.diagnostic===t?.diagnostic)}function dL(e,t,n,r,i,a,o,s,c){let l=bF(e,t,n.requestId);if(l!==void 0){if(!cL(l.entry,n)||!ZO(l.entry.meta,r)||!uL(vj(l.entry)?.reply,c)||!wP(l.origin,i))throw new W(`contract`,`conflict`,`Request id conflicts with an accepted Session command`);return mL(l,`replay`)}let u=Tj.fact.generate();OF(e,t);let d=Date.now(),f=lL(n,u,d,a,s,c);e.sql.exec(`INSERT INTO session_command_admissions
|
|
860
860
|
(id, session_id, sequence, request_id, work_id, data_json, timestamp,
|
|
861
861
|
origin_kind, origin_id, origin_correlation)
|
|
862
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,u,t,
|
|
862
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,u,t,DF(e,t),n.requestId,u,wj(BP(f,r)),d,i.kind,i.kind===`user`?null:i.extensionId,i.kind===`user`?null:i.correlation);let p=vF(e,t,u);if(p===void 0)throw $(`Accepted Session command admission is unavailable`);return o?.({jobId:u,sessionId:t,commandFactId:u,delivery:n.type===`prompt`?n.delivery:`followUp`}),mL(p,`new`)}function fL(e,t,n){if(e.sql.exec(`SELECT 1 FROM session_request_withdrawals WHERE session_id = ? AND request_id = ?`,t,n).toArray().length>0)throw new W(`contract`,`closed`,`Request was withdrawn`,n)}function pL(e,t,n){let r=bF(e,t,n);if(r!==void 0)return{status:`accepted`,commandId:r.id};let i=e.sql.exec(`SELECT id FROM session_entries WHERE session_id = ? AND request_id = ? AND type = 'operator'`,t,n).toArray()[0];if(i!==void 0){let e=AP(i);if(e._tag===`Failure`)throw $(`Stored operator receipt is invalid`);return{status:`accepted`,commandId:e.success.id}}return e.sql.exec(`INSERT OR IGNORE INTO session_request_withdrawals(session_id, request_id) VALUES (?, ?)`,t,n),{status:`unknown`}}function mL(e,t){let n=Object.freeze({sessionId:e.sessionId,requestId:e.entry.requestId,commandId:e.id});return Object.freeze({accepted:n,command:e,delivery:t})}function hL(e,t,n){if(e.entry.kind!==`cancellation`)throw $(`Accepted Session cancellation is unavailable`);return Object.freeze({accepted:Object.freeze({commandId:e.entry.targetWorkId,entryId:e.id}),delivery:t,active:n})}function gL(e,t,n,r,i){return e.transactionSync(()=>{let a=n(),o=a.state===`running`?yF(e,t,a.jobId):void 0,s=o===void 0?void 0:vL(e,t,o.id,n,r,!1,i);for(let a=DF(e,t);a>0;){let{commands:o}=pF(e,t,64);if(o.length===0)return s;a-=o.length;for(let a of o){if(vL(e,t,a.id,n,r,!1,i,!0)===void 0)throw $(`Pending Session command could not be cancelled`);nI(e,{sessionId:t,id:a.id,entry:a.entry})}}throw $(`Session cancellation did not settle its pending admissions`)})}function _L(e,t,n,r,i,a=!1,o){return e.transactionSync(()=>vL(e,t,n,r,i,a,o))}function vL(e,t,n,r,i,a=!1,o,s=!1){let c=r(),l=vF(e,t,n);if(l?.entry.kind!==`command`)return;let u=SF(e,t,l.entry.workId),d=u.find(({entry:e})=>e.kind===`cancellation`);if(d?.entry.kind===`cancellation`)return hL(d,`replay`,c.state===`running`&&c.jobId===l.entry.workId);let f=c.state===`running`&&c.jobId===l.entry.workId;if(!f&&u.some(({entry:e})=>e.kind===`run_terminal`||e.kind===`work_terminal`)||a&&(f||u.some(({entry:e})=>e.kind===`command`))||vj(l.entry)?.delivery===`steer`&&u.some(({entry:e})=>e.kind===`command`)&&!f)return;let p=Tj.fact.generate(),m=i({jobId:l.entry.workId,cancellationId:p,onlyIfPending:a});if(m.status===`missing`&&vj(l.entry)?.delivery!==`steer`&&!s||m.status===`decided`||m.status===`conflict`&&a)return;if(m.status!==`recorded`&&m.status!==`missing`)throw new W(`store`,`conflict`,`Session cancellation identity conflicts`);let ee=nI(e,{sessionId:t,id:p,entry:BP({kind:`cancellation`,requestId:p,receiptId:p,workId:l.entry.workId,targetWorkId:l.entry.workId},o)});return m.status===`missing`&&nI(e,{sessionId:t,id:Tj.fact.generate(),entry:{kind:`work_terminal`,workId:l.entry.workId,outcome:`cancelled`}}),hL(ee,`new`,f)}function yL(e,t){e.transactionSync(()=>{t.assertIdleSession?.(t.sessionId);let n=tF(e,t.sessionId);if(n===void 0)throw $(`Session is unavailable for branch selection`);rF(e,n);let r=nF(e,t.sessionId,t.entryId);if(r?.state!==`complete`)throw $(`Selected branch entry is unavailable`);let i=Date.now();e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,r.id,i,n.id),dN(e,{sessionId:n.id,activityAt:i,title:KP(e,n.id)})})}function bL(e,t){return e.transactionSync(()=>{if(fL(e,t.sessionId,t.requestId),tF(e,t.sessionId)===void 0)throw $(`Session is unavailable for an operator entry`);let n=e.sql.exec(`SELECT id FROM session_entries WHERE session_id = ? AND request_id = ?`,t.sessionId,t.requestId).toArray()[0];if(n!==void 0){let r=AP(n);if(r._tag===`Failure`)throw $(`Stored Session entry identity is invalid`);let i=nF(e,t.sessionId,r.success.id);if(i?.entry.kind===`operator`&&i.entry.author===t.author&&ZO(i.entry.meta,t.meta)&&i.entry.message.content===t.text)return!1;throw new W(`store`,`conflict`,`Request id already names another Session entry`)}t.assertIdleSession(t.sessionId);let r={kind:`operator`,workId:null,requestId:t.requestId,author:t.author,message:{role:`user`,content:t.text,timestamp:Date.now()}};return nI(e,{sessionId:t.sessionId,id:Tj.fact.generate(),entry:BP(r,t.meta)}),!0})}function xL(e,t){return e.transactionSync(()=>{if(t.assertIdleSession?.(t.sessionId),tF(e,t.sessionId)===void 0)throw $(`Source Session is unavailable`);let n=bI(e,t.sessionId,t.entryId,`fork`),r=Tj.session.generate(),i=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
863
863
|
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
864
|
-
VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),
|
|
864
|
+
VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),UM(e,t.sessionId,r);let a=null,o=null,s=1,c=new Map,l=0;for(;;){let t=EI(e,n,{after:l,from:`oldest`,rows:iI});for(let n of t.rows){let t=Tj.fact.generate();c.set(n.id,t);let i=n.entry.kind===`compaction`?{...n.entry,head:c.get(n.entry.head)??(()=>{throw $(`Fork compaction boundary is unavailable`)})()}:n.entry;e.sql.exec(`INSERT INTO session_entries
|
|
865
865
|
(id, session_id, parent_id, sequence, type, role, state,
|
|
866
866
|
request_id, work_id, data_json, timestamp, completed_at)
|
|
867
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,JP(i),n.state,qP(i),i.workId,Cj(i),n.timestamp,n.completedAt),a=t,o=t,s+=1,l=n.sequence}if(!t.more)break}if(o===null)throw $(`Fork path is empty`);e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,o,i,r);let u=xI(e,{sessionId:t.sessionId});for(let t of cM(e,(t,n)=>AI(e,u,t,n)))tI(e,{sessionId:r,id:wj.fact.generate(),entry:t});return uN(e,{sessionId:r,activityAt:i,title:GP(e,r)}),r})}function xL(e,t,n,r){if(eF(e,t)===void 0)throw $(`Session document owner is unavailable`);return AI(e,xI(e,{sessionId:t}),n,r)}function SL(e,t,n,r,i){if(eF(e,t)===void 0)throw $(`Session document owner is unavailable`);tI(e,{sessionId:t,id:wj.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var CL=2097152,wL=200,TL=200,EL=new TextEncoder;function DL(e){return new W(`store`,`unavailable`,e)}function OL(e,t,n){let r=new Map;for(let e of n)e.entry.kind===`command`&&r.set(e.entry.workId,e.entry.workId);let i=n.flatMap(({entry:e})=>(e.kind===`run_terminal`||e.kind===`work_terminal`)&&!r.has(e.workId)?[e.workId]:[]);for(let n of i)_F(e,t,n)!==void 0&&r.set(n,n);return r}function kL(e,t){return n=>{let r=_F(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function AL(e,t,n){return{commandIds:OL(e,t,n),diagnostics:NL(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:kL(e,t)}}function jL(e,t,n,r){let i=MI(e,n,new Set(r.flatMap(({entry:e})=>e.kind===`message`||e.kind===`run_terminal`||e.kind===`work_terminal`?[e.workId]:[]))),a=new Map;for(let e of i.commands)a.set(e,e);for(let{entry:n}of r)(n.kind===`run_terminal`||n.kind===`work_terminal`)&&!a.has(n.workId)&&_F(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:kL(e,t)}}function ML(e,t){let n=_j(e.entry);if(n!==void 0){let r=t.origin(n.workId),i={id:e.id,sequence:e.sequence,commandId:n.workId,requestId:n.requestId,value:n.message};return n.meta!==void 0&&(i={...i,meta:n.meta}),r!==void 0&&(i={...i,origin:r}),Object.freeze(i)}if(e.entry.kind===`operator`){let t={id:e.id,sequence:e.sequence,commandId:null,requestId:e.entry.requestId,value:xj(e.entry)};return e.entry.meta!==void 0&&(t={...t,meta:e.entry.meta}),Object.freeze(t)}if(e.entry.kind===`message`){let n={id:e.entry.message.value,sequence:e.sequence,commandId:t.commandIds.get(e.entry.workId)??null,value:e.entry.value};return Object.freeze(e.entry.data===void 0?n:{...n,data:e.entry.data})}}function NL(e){let t=new Map;for(let{entry:n}of e)(n.kind===`work_terminal`||n.kind===`run_terminal`)&&n.diagnostic!==void 0&&t.set(n.workId,n.diagnostic);return t}function PL(e,{commandIds:t,diagnostics:n,cancellations:r}){if(e.entry.kind!==`run_terminal`&&e.entry.kind!==`work_terminal`)return;let i=t.get(e.entry.workId);if(i===void 0)return;let a={commandId:i,outcome:e.entry.outcome,sequence:e.sequence,diagnostic:n.get(e.entry.workId)??null},o=e.entry.outcome===`cancelled`?r.get(e.entry.workId):void 0;return Object.freeze(o===void 0?a:{...a,meta:o})}var FL=new WeakMap;function IL(e){let t=FL.get(e);if(t===void 0)throw DL(`Session compaction entry position is unavailable`);return t}function LL(e,t,n){let r=[];for(let i of n){let a=i.entry;if(a.kind!==`compaction`)continue;let o=n.find(e=>e.id===a.head)?.sequence??DI(e,t,a.head);if(o===void 0)throw DL(`Session compaction horizon is unavailable`);let s=Object.freeze({id:i.id,sequence:o,at:i.timestamp,tokensBefore:a.data.tokensBefore,tokensAfter:a.data.tokensAfter??null,trigger:a.data.reason??null});FL.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function RL(e){return Object.freeze(e.flatMap(({id:e,sequence:t,timestamp:n,entry:r})=>r.kind===`compaction_notice`?[Object.freeze({id:e,sequence:t,at:n,trigger:r.trigger,result:r.result,diagnostic:r.result===`stale`||r.result===`insufficient`?null:r.diagnostic??null})]:[]))}function zL(e){return EL.encode(JSON.stringify(e)).byteLength}function BL(e,t){let n=DA({generation:e,sequence:t});if(n===void 0)throw DL(`Session cursor is unavailable`);return n}function VL(e,t,n,r,i=!1){let a=ML(t,r),o=PL(t,r),s=i&&t.entry.kind===`sandbox_failure`?t.entry.event:void 0;if(a!==void 0&&e.messages.length===n)return!1;let c=(a===void 0?0:zL(a))+(o===void 0?0:zL(o))+(s===void 0?0:zL(s));if(c>CL)throw DL(`Session projection entry exceeds the read bound`);return e.bytes+c>CL?!1:(a!==void 0&&e.messages.push(a),o!==void 0&&e.terminals.push(o),s!==void 0&&e.sandboxFailures.push(s),e.bytes+=c,!0)}function HL(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==TL;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!VL(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw DL(`Session page cannot make bounded progress`);let c=i===`backward`?[...o.messages].reverse():o.messages,l=i===`backward`?[...o.terminals].reverse():o.terminals,u=i===`backward`?[...o.sandboxFailures].reverse():o.sandboxFailures;return Object.freeze({messages:Object.freeze(c),terminals:Object.freeze(l),sandboxFailures:Object.freeze(u),consumed:s,hasMore:t||s<e.length})}function UL(e){return Array.isArray(e)}function WL(e,t){let{commands:n,total:r}=fF(e,t,TL+1,`prompts`),i=[],a=EL.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=KL(e),n=EL.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===TL||a+n>CL)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function GL(e,t,n){let r=uF(e,t,n);return r===void 0?null:KL(r)}function KL(e){let t=_j(e.entry);if(t===void 0)throw DL(`Pending Session prompt is unavailable`);let n=t.message.content,r=UL(n)?{commandId:e.entry.workId,requestId:t.requestId,text:n.filter(e=>e.type===`text`).map(e=>e.text).join(``),images:n.filter(e=>e.type===`image`),delivery:t.delivery??`followUp`}:{commandId:e.entry.workId,requestId:t.requestId,text:n,delivery:t.delivery??`followUp`},i=e.entry.meta===void 0?r:{...r,meta:e.entry.meta};return e.origin.kind===`extension`?{...i,origin:{extensionId:e.origin.extensionId,correlation:e.origin.correlation}}:i}function qL(e,t,n){let r=OA(n);if(r?.generation===t.rootId)return EI(e,t,r.sequence)?r.sequence:void 0}function JL(e,t,n,r,i=()=>({})){return uI(e,t,()=>{let a=WL(e,t),o=xI(e,{sessionId:t});if(o===void 0)return Object.freeze({sessionId:t,cursor:null,hasMore:!1,oldestCursor:null,messages:Object.freeze([]),terminals:Object.freeze([]),compactions:Object.freeze([]),compactionNotices:Object.freeze([]),pending:a,activity:r.facts,progress:r.readProgress(),toolOutput:r.toolOutput,extensions:i(),attention:Dk(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:qL(e,o,n.before);if(c===void 0)throw DL(`Session read cursor is unavailable`);let l=TI(e,o,{before:c,from:`newest`,rows:TL}),u=HL(l.rows,l.more,n.limit,jL(e,t,o,l.rows),`backward`,n.includeSandboxFailures===!0),d=l.rows.slice(l.rows.length-u.consumed),f=l.rows.at(-1),p=d[0],m={sessionId:t,cursor:f===void 0?null:BL(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?BL(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:LL(e,o,d),compactionNotices:RL(d),pending:a,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:Dk(e,t)},ee=mA(e,t);return ee!==void 0&&Object.assign(m,{parent:ee}),Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var YL=Object.freeze({kind:`reset`});function XL(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return EI(e,t,n.sequence)?n.sequence:void 0}function ZL(e,t,n,r,i,a,o,s,c){let l=TI(e,t,{after:n,from:`oldest`,rows:TL}),u=HL(l.rows,l.more,wL,jL(e,t.sessionId,t,l.rows),`forward`,c),d=l.rows.slice(0,u.consumed),f=d.at(-1)?.sequence??t.newestSequence,p={kind:`update`,delivery:r,cursor:BL(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:LL(e,t,d),compactionNotices:RL(d),pending:s,activity:i.facts,extensions:a,attention:o},m=[Object.freeze(c?{...p,sandboxFailures:u.sandboxFailures}:p)];return Object.freeze({kind:`page`,frames:Object.freeze(u.hasMore?m:[...m,{kind:`tool_output`,toolOutput:i.toolOutput,activity:i.facts}]),hasMore:u.hasMore})}function QL(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:OA(n);return n!==void 0&&s===void 0?YL:uI(e,t,()=>{let c=WL(e,t),l=xI(e,{sessionId:t});if(l===void 0)return n===void 0?{kind:`page`,frames:[{kind:`update`,delivery:r,cursor:null,messages:[],terminals:[],compactions:[],compactionNotices:[],activity:i.facts,extensions:a(),attention:Dk(e,t),pending:c}],hasMore:!1}:YL;let u=XL(e,l,s);return u===void 0?YL:ZL(e,l,u,r,i,a(),Dk(e,t),c,o)})}function $L(e,t,n){let r=_F(e,t,n);if(r===void 0)throw DL(`Accepted Session command is unavailable`);if(!bF(e,t,r.entry.workId))return;let i=xF(e,t,r.entry.workId),a=AL(e,t,i),o=i.flatMap(e=>{let t=PL(e,a);return t===void 0?[]:[t]}).at(-1);if(o===void 0)return;let s=i.flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`?[e.value]:[]),c=s.at(-1),l=o.outcome===`cancelled`?o.meta:r.entry.meta,u=Tg(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:uA(e,t)?.replyTo[0]?.agentId??null,terminal:l===void 0?o:{...o,meta:l},content:o.outcome===`cancelled`?``:c?.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()??``,usage:s.map(({provider:e,model:t,usage:n})=>({provider:e,model:t,usage:n})),toolCalls:new Set(i.flatMap(({entry:e})=>e.kind===`tool_intent`?[e.call.id]:[])).size,waitingOnYou:vA(e,t,r.entry.workId)}}var eR=65536,tR=250,nR=2048,rR=new TextEncoder,iR=()=>({chunks:[],length:0,bytes:0});function aR(e,t){for(let n=0;n<t.length;){let r=Math.min(n+nR,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=rR.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=nR?(s.text+=a,s.bytes+=o):e.chunks.push({offset:e.length,text:a,bytes:o}),e.length+=a.length,e.bytes+=o,n=r;e.bytes>eR&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function oR(e){return e.chunks[0]?.offset??0}function sR(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function cR(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:sR(e.text,oR(e.text)),thinking:sR(e.thinking,oR(e.thinking)),textOffset:oR(e.text),thinkingOffset:oR(e.thinking),textTruncated:oR(e.text)>0,thinkingTruncated:oR(e.thinking)>0}}function lR(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function uR(e,t,n,r){let i=dR.get(e)?.get(t),a=i?.workId===n?i.value:null;if(a===null)return null;let o=r?.messageId===a.messageId?r:null;if(o!==null&&o.revision>=a.revision)return null;let s=o?.text??0,c=o?.thinking??0;if(!(s<oR(a.text)||c<oR(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:sR(a.text,s)},thinking:{offset:c,append:sR(a.thinking,c)}}}var dR=new WeakMap;function fR(e,t,n){let r=dR.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var pR=D(P({droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))}),{onExcessProperty:`error`});function mR(e,t){return b(function*(){let n=yield*gR(e,t),r=()=>{pk(e,t.sessionId,`progress`)};return{started:e=>y(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>y(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=pR(e.result.data);if(Ae(i))return;let a=e.result.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);new TextEncoder().encode(a).byteLength>8192||a.split(`
|
|
868
|
-
`).length>200||i.success.droppedBytes>i.success.totalBytes||(n.slots.set(e.toolCall.value,{toolCallId:e.call.id,revision:(t?.revision??0)+1,tail:a,...i.success}),r())}),terminal:e=>y(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function hR(e){let t=dR.get(e);if(t!==void 0)return t;let n=new Map;return dR.set(e,n),n}function gR(e,t){return b(function*(){let n=hR(e),r=n.get(t.sessionId);if(r?.workId===t.commandId)return r;let i={workId:t.commandId,value:null,slots:new Map};return n.set(t.sessionId,i),yield*Tr(()=>y(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&pk(e,t.sessionId,`progress`))})),i})}function _R(e){return new W(`runtime`,`rejected`,e)}function vR(e,t,n){let r=hR(e).get(t);return cR(r?.workId===n?r.value:null)}function yR(e,t,n){let r=dR.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function bR(e,t,n,r){return b(function*(){let i=yield*gR(e,t);if(r!==void 0&&i.value===null){let n=iR();n.length=r.offset,aR(n,r.text),i.value={recovered:!0,messageId:r.messageId,revision:1,text:n,thinking:iR()},pk(e,t.sessionId,`progress`)}let a,o=0,s=0,c,l=()=>{c!==void 0&&clearTimeout(c),c=void 0},u=()=>{l();let n=i.value;n!==null&&(s=n.text.length+n.thinking.length,pk(e,t.sessionId,`progress`))},d=y(()=>{l();let n=i.value!==null;i.value=null,n&&pk(e,t.sessionId,`progress`),a=void 0});return yield*Tr(()=>d),Object.freeze({started:e=>y(()=>{l(),a=e,o=0,i.value?.recovered!==!0&&(i.value=null),s=0}),update:n=>sr(()=>{let r=a;if(r===void 0)return v(_R(`Mule progress arrived before its message start`));if(r.run.value!==n.run.value||r.turn.value!==n.turn.value||r.message.value!==n.message.value)return v(_R(`Mule progress identity conflicts`));let l=n.event;if(l.type!==`text_delta`&&l.type!==`thinking_delta`||l.delta.length===0)return C;let d=i.value===null||i.value.recovered===!0,f=(d?null:i.value)??{messageId:n.message.value,revision:0,text:iR(),thinking:iR()};aR(l.type===`text_delta`?f.text:f.thinking,l.delta),f.revision++,i.value=f;let p=f.text.length+f.thinking.length;d||p-s>=4096?u():c??=setTimeout(u,100);let m=Date.now();return l.type!==`text_delta`||m-o<tR?C:(o=m,oi({try:()=>{XI(e,{sessionId:t.sessionId,entry:{kind:`message_start`,workId:t.commandId,run:r.run,turn:r.turn,message:r.message,role:`assistant`},text:sR(f.text,oR(f.text)),offset:oR(f.text)})},catch:e=>new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)}))}),terminal:e=>d.pipe(g(n(e)))})})}var xR=new WeakMap;function SR(e){let t=xR.get(e);if(t!==void 0)return t;let n=new Map;return xR.set(e,n),n}function CR(e,t){return SR(e).get(t)??null}function wR(e,t,n){SR(e).set(t,Object.freeze({trigger:n})),pk(e,t,`progress`)}function TR(e,t){SR(e).delete(t)&&pk(e,t,`progress`)}var ER=Object.freeze({admitNew:()=>{}});function DR(e){return e===void 0?ER:Object.freeze({admitNew:()=>{if(e.underPressure())throw new W(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function OR(e,t){let n=QI(e,t);return pk(e,t.sessionId),n}function kR(e,t){let n=tL(e,t);return pk(e,t.sessionId),n}function AR(e,t){let n=nL(e,t);return n!==`stale`&&pk(e,t.sessionId),n}function jR(e){return new W(`store`,`rejected`,e)}function MR(e){return new W(`store`,`conflict`,e)}function NR(e){return oi({try:e,catch:e=>e instanceof W?e:new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function PR(e){return NR(()=>{YF(e)})}function FR(e,t,n,r,i,a,o){return NR(()=>{let s=gL(e,t,n,i,a,r,o);return s?.delivery===`new`&&pk(e,t,`settlement`),s})}function IR(e,t){return NR(()=>{let n=hF(e,t.sessionId,t.delivery,t.workId);return n.length>0&&pk(e,t.sessionId),n})}function LR(e,t){return NR(()=>{gF(e,t),pk(e,t.sessionId,`settlement`)})}function RR(e,t,n,r,i){return NR(()=>{let a=hL(e,t,n,r,i);return pk(e,t,`settlement`),a?.accepted})}function zR(e,t){return NR(()=>{vL(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),pk(e,t.sessionId)})}function BR(e,t){return NR(()=>{yL(e,t)&&pk(e,t.sessionId)})}function VR(e,t){return NR(()=>{let n=bL(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return pk(e,n),Object.freeze({sessionId:n})})}function HR(e,t){return NR(()=>{let n=JI(e,{sessionId:xb(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&pk(e,t.sessionId),n})}function UR(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function WR(e,t){return NR(()=>{let n=_F(e,t.sessionId,t.commandFactId);if(n===void 0)throw jR(`Accepted Session command is unavailable`);let r=xF(e,t.sessionId,n.entry.workId);for(let e=r.length-1;e>=0;--e){let t=r[e]?.entry;if(t?.kind===`message`&&t.value.role===`assistant`){let e=UR(t.value);if(e!==``)return e}}return``})}function GR(e,t){return b(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*WR(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*NR(()=>{let n=_F(e,t.sessionId,i);if(n===void 0)throw jR(`Accepted Session command is unavailable`);if(az(e,t.sessionId,i,n.entry.workId)===null)return;let r=rF(e,i);if(r===void 0)throw jR(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=rF(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw jR(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function KR(e,t,n){return NR(()=>{let r=_F(e,t.sessionId,t.commandFactId);if(r===void 0)throw jR(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=xF(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function qR(e,t){return NR(()=>{let n=_F(e,t.sessionId,t.commandFactId);if(n===void 0)throw jR(`Accepted Session command is unavailable`);return NL(xF(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function JR(e,t,n,r,i,a){return NR(()=>{let o=xb(t),s=wb(r);return lI(e,o,()=>a(JL(e,o,s,n(),i)),s.before===void 0?void 0:OA(s.before)?.sequence)})}function YR(e,t,n){return NR(()=>OF(e,Cb({requestId:t}),n))}function XR(e,t,n){return kF(e,Cb({requestId:t}),n)}function ZR(e,t){return NR(()=>AF(e,{sessionId:xb(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{dN(e,t)}}))}function QR(e,t){return NR(()=>gN(e,t))}function $R(e,t,n,r,i,a,o,s){return NR(()=>{let c=xb(t);return lI(e,c,()=>s(QL(e,c,n,r,i,a,o)))})}function ez(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function tz(e,t){return e.core===t.core&&e.extensions.length===t.extensions.length&&e.extensions.every(([e,n],r)=>{let i=t.extensions[r];return i?.[0]===e&&i[1]===n})}function nz(e,t,n,r,i){i?.();let a=xF(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||uj(a.entry,n))return`replay`;throw MR(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=wj.fact.generate();if(rF(e,r)===void 0&&_F(e,t.sessionId,r)===void 0)return tI(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw jR(`Session fact identity allocation failed`)}function rz(e,t,n,r,i){e.transactionSync(()=>nz(e,t,n,r,i))===`new`&&pk(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`)}function iz(e,t,n){return NR(()=>{rz(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function az(e,t,n,r){let i=_F(e,t,n);if(i?.entry.workId!==r)throw jR(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function oz(e,t,n,r){let i=az(e,t,n,r),a=xF(e,t,r).map(({entry:e})=>e),o=new Set(a.flatMap(e=>e.kind===`tool_intent`?[e.call.id]:[])).size,s=a.filter(e=>e.kind===`run_terminal`||e.kind===`work_terminal`).at(-1);return Object.freeze({terminal:s?.kind===`run_terminal`||s?.kind===`work_terminal`?s.outcome:`missing`,origin:i,toolCalls:o})}function sz(e,t){return NR(()=>{if(_F(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw jR(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};rz(e,{sessionId:t.sessionId,commandId:t.workId},t.diagnostic===void 0?n:{...n,diagnostic:t.diagnostic},({entry:e})=>e.kind===`work_terminal`||e.kind===`run_terminal`&&e.outcome===t.outcome,()=>{e.sql.exec(`DELETE FROM session_entries WHERE session_id = ? AND work_id = ? AND state = 'streaming' AND type = 'message_start'`,t.sessionId,t.workId)})})}function cz(e,t,n,r,i){return NR(()=>{let a=r.type===`run_start`?{kind:`run_started`,workId:t.commandId,run:r.run,contract:n}:r.type===`turn_start`?{kind:`turn_started`,workId:t.commandId,run:r.run,turn:r.turn}:{kind:`run_terminal`,workId:t.commandId,run:r.run,terminal:r.terminal,outcome:r.outcome};a.kind===`run_terminal`&&i!==void 0&&(a={...a,diagnostic:i}),rz(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?ez(e.run,a.run)&&tz(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?ez(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&ez(e.terminal,a.terminal):!1)})}function lz(e,t,n){return NR(()=>{let r={kind:`message_start`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,role:n.value.role};e.transactionSync(()=>{let i=xF(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&ez(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!ez(i.entry.run,r.run)||!ez(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw MR(`Mule message-start identity conflicts`);return`replay`}if(i.entry.kind!==`message_start`||!uj(lj(i.entry),r))throw MR(`Mule message-start identity conflicts`);return`replay`}return tI(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&pk(e,t.sessionId)})}function uz(e,t,n,r){return NR(()=>{rz(e,t,{kind:`model_prompt`,workId:t.commandId,run:r.run,turn:r.turn,attempt:r.attempt,contract:n,systemPrompt:r.systemPrompt},({entry:e})=>e.kind===`model_prompt`&&ez(e.turn,r.turn)&&e.attempt===r.attempt&&tz(e.contract,n))})}function dz(e,t,n,r){return NR(()=>{let i={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value},a=n.data===void 0?i:{...i,data:n.data};e.transactionSync(()=>{let i=xF(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&ez(e.message,n.message));if(i?.entry.kind===`message`){if(!uj(i.entry,a))throw MR(`Mule completed-message identity conflicts`)}else nI(e,{sessionId:t.sessionId,id:n.message.value,entry:a});let o=n.retry===void 0||n.value.role!==`assistant`?`replay`:hz(e,t,mz(n.retry,r),n.turn);return i?.entry.kind===`message`&&o===`replay`?`replay`:`new`})===`new`&&pk(e,t.sessionId)})}function fz(e,t,n,r){return NR(()=>{rz(e,t,{kind:`tool_intent`,replay:r.replay,contract:n,workId:t.commandId,run:r.run,turn:r.turn,toolCall:r.toolCall,call:r.call},({entry:e})=>e.kind===`tool_intent`&&ez(e.toolCall,r.toolCall)&&tz(e.contract,n))})}function pz(e,t,n){return NR(()=>{let{data:r,...i}=n.result,a={kind:`tool_outcome`,workId:t.commandId,run:n.run,turn:n.turn,toolCall:n.toolCall,call:n.call,result:i};rz(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&ez(e.toolCall,n.toolCall))})}function mz(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+ZO({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,dueAt:e.dueAt,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function hz(e,t,n,r){let i=xF(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&ez(e.turn,r));if(i===void 0)throw MR(`Retry has no recorded turn`);return nz(e,t,{kind:`live_retry`,workId:t.commandId,event:n},({entry:e,sequence:t})=>t>i.sequence&&e.kind===`live_retry`&&e.event.type===n.type&&e.event.attempt===n.attempt&&ez(e.event.run,n.run))}function gz(e,t,n,r){return NR(()=>{e.transactionSync(()=>hz(e,t,n,r))===`new`&&pk(e,t.sessionId)}).pipe(ut(_z))}var _z=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function vz(e,t,n,r,i){return b(function*(){let a=yield*bR(e,t,n=>dz(e,t,n,r),i),o=yield*mR(e,t),s=(i,s)=>{switch(i.type){case`model_prompt`:return uz(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return cz(e,t,n,i,s);case`message_start`:return i.value.role===`user`?C:lz(e,t,i).pipe(g(i.value.role===`assistant`?a.started(i):C));case`message_update`:return a.update(i);case`message_end`:return i.value.role===`user`?C:i.value.role===`assistant`?a.terminal(i):dz(e,t,i,r);case`tool_execution_start`:return fz(e,t,n,i).pipe(g(o.started(i)));case`tool_execution_end`:return pz(e,t,i).pipe(g(o.terminal(i)));case`tool_execution_update`:return o.update(i);case`turn_end`:return C}};return(e,t)=>s(e,t).pipe(ut(_z))})}function yz(e,t,n){return NR(()=>$L(e,xb(t),xb(n)))}var bz=bP.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),xz=P({requestId:k(M),meta:k(KO),data:k(UO),origin:k(bz),id:M,sequence:H.check(Xm(0)),commandId:R(M),value:QA}),Sz=L([`manual`,`threshold`,`overflow`]),Cz=P({queue:I([P({state:j(`idle`)}),P({state:j(`queued`),commandId:jh,runningWork:R(P({phase:L([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),P({state:j(`running`),commandId:jh})]),cancellationRequested:cm,retry:R(P({attempt:H.check(Xm(0)),maxAttempts:H.check(Xm(0)),delayMs:H.check(V(0)),errorMessage:M,scheduledAt:H.check(V(0))})),activeTool:R(M),lastModelChoiceSequence:R(H.check(Xm(0))),compaction:R(P({trigger:Sz}))}),wz=M,Tz=fm(M,I([P({status:j(`running`),revision:wz,value:UO,catalog:k(UO)}),P({status:j(`stopped`),revision:wz,reason:M})])),Ez=P({id:M,version:M,revision:wz,status:L([`running`,`stopped`]),reason:R(M),stoppedAt:R(N)}),Dz=P({commandId:M,outcome:L([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:H.check(Xm(0)),diagnostic:R(M),meta:k(KO)}),Oz=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),tokensBefore:N,tokensAfter:R(N),trigger:R(Sz)}),kz=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),trigger:Sz,result:L([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:R(M)}),Az=M.check(B(e=>new TextEncoder().encode(e).byteLength<=65536)),jz=P({messageId:M,revision:H.check(V(0)),text:Az,thinking:Az,textOffset:H.check(V(0)),thinkingOffset:H.check(V(0)),textTruncated:cm,thinkingTruncated:cm}),Mz=P({commandId:M,requestId:M,meta:k(KO),origin:k(bz),text:M,images:k(F(Gy)),delivery:L([`steer`,`followUp`])}),Nz=F(P({toolCallId:M,revision:H.check(V(0)),tail:M.check(B(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
|
|
869
|
-
`).length<=200)),droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))})).check(vh(4)),Pz=P({total:H.check(V(0)),prompts:F(Mz),hasMore:cm}),Fz=P({tokens:H.check(V(0)),window:R(H.check(Xm(0)))}),Iz=P({parent:k(Ty),sessionId:M,cursor:R(M),hasMore:cm,oldestCursor:k(R(M)),messages:F(xz),terminals:F(Dz),sandboxFailures:k(F(zO)),compactions:k(F(Oz)),compactionNotices:k(F(kz)),pending:Pz,activity:Cz,progress:R(jz),toolOutput:Nz,extensions:Tz,attention:Ay,context:k(Fz)}),Lz=I([P({kind:j(`heartbeat`)}),P({kind:j(`activity`),activity:Cz}),P({kind:j(`tool_output`),toolOutput:Nz,activity:Cz}),P({kind:j(`update`),delivery:L([`replay`,`live`]),cursor:R(M),messages:F(xz),terminals:F(Dz),sandboxFailures:k(F(zO)),compactions:k(F(Oz)),compactionNotices:k(F(kz)),pending:Pz,activity:Cz,extensions:Tz,attention:Ay,context:k(Fz)}),P({kind:j(`progress`),progress:P({messageId:M,revision:H.check(V(0)),text:P({offset:H.check(V(0)),append:Az}),thinking:P({offset:H.check(V(0)),append:Az})}),activity:Cz}),P({kind:j(`reset`),reason:j(`history_unavailable`),cursor:R(M),baseline:Iz})]),Rz=P({status:j(`accepted`),commandId:M,sessionId:k(M)});O(U(I([Rz,P({status:j(`held`),reason:j(`recipient_offline`),message:j(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var zz=P({status:j(`unknown`)}),Bz=O(U(I([Rz,zz])));function Vz(e){return Bz(e)}var Hz=I([Rz,zz,P({status:j(`too_late`),commandId:M})]),Uz=P({sessionId:M}),Wz=O(U(Iz),{onExcessProperty:`error`}),Gz=O(U(Lz),{onExcessProperty:`error`}),Kz=O(U(Rz)),qz=O(U(Hz)),Jz=O(U(Uz)),Yz=O(U(zy)),Xz=O(U(Ez)),Zz=O(U(F(Ez))),Qz=O(U(UO));function $z(e){return Xz(e)}function eB(e){return Zz(e)}function tB(e){return Qz(e)}function nB(e){return Kz(e)}function rB(e){return qz(e)}function iB(e){return O(U(R(Mz)))(e)}function aB(e){return Jz(e)}var oB=P({acceptedSender:R(M),delegator:R(M),terminal:Dz,content:M,usage:F(P({provider:M,model:M,usage:JA})),toolCalls:H.check(V(0)),waitingOnYou:F(P({itemId:M,kind:M,summary:M})).check(vh(8))});function sB(e){return O(U(R(oB)))(e)??void 0}function cB(e){return Wz(e)}function lB(e){return Gz(e)}function uB(e){let t=Yz(e);return new W(t.boundary,t.cause,t.message,t.requestId)}var dB=O(U(P({sessions:F(I([P({sessionId:jh,createdAt:N,lastActivityAt:N,settledAt:k(N),title:M,state:L([`needs_you`,`running`,`errored`,`done`])}),P({sessionId:jh,state:j(`unavailable`)})])),next:A(jh)})));function fB(e){let t=dB(e);return{sessions:t.sessions,next:t.next}}var pB=O(U(P({sessionId:jh}))),mB=O(U(P({deleted:cm})));function hB(e){return mB(e).deleted}function gB(e){return pB(e).sessionId}function _B(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:MO(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function vB(e,t){return Kn(e,t).then(e=>{if(ca(e))return e.value;let t=Gn(Xi(e.cause))??Ji(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function yB(e){let t=Pr(e);if(ca(t))return t.value;let n=Gn(Xi(t.cause))??Ji(t.cause);throw n instanceof Error?n:Error(String(n))}function bB(e){let t=by(e);return Object.freeze({[Symbol.asyncIterator]:()=>{let e=t[Symbol.asyncIterator]();return{next:()=>e.next(),return:()=>e.return?.()??Promise.resolve({done:!0,value:void 0})}}})}function xB(e,t){function n(e){return vB(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>vB(t.withdraw(e)),abort:()=>vB(t.abort),send:(e,n)=>vB(t.send(e,n)),cancel:e=>vB(t.cancel(e)),latestPending:()=>vB(t.latestPending),modelPreference:Object.freeze({read:()=>vB(t.modelPreference.read),set:e=>vB(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>vB(n.call(e,t,r))})},read:e=>vB(t.read(e)),readSettlement:(e,n)=>vB(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>bB(t.subscribe(e)),watch:e=>vB(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:bB(e.changes),close:()=>vB(e.close)}))})}function SB(e,t){let n=t??`local:${rg()}`;return Object.freeze({createSession:t=>vB(e.createSession(t)),deleteSession:t=>vB(e.deleteSession(t)),listSessions:t=>vB(e.listSessions(t)),extensions:Object.freeze({list:()=>vB(e.extensions.list),resume:t=>vB(e.extensions.resume(t)),call:(t,n,r)=>vB(e.extensions.call(t,n,r))}),session:t=>xB(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>vB(e.close)})}function CB(e){let t=`local:${rg()}`;return Object.freeze({...SB(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:_B(t.tools)});let r=await vB(e.prepareConfiguration(n));return{commit:()=>{yB(r.commit)},discard:()=>vB(r.discard)}},grants:Object.freeze({deliver:(t,n)=>yB(e.grants.deliver(t,n)),read:t=>yB(e.grants.read(t))}),withMeta:n=>SB(e.withMeta(n),t)})}function wB(e=`Remote Shiitake operation is unavailable`){return new W(`runtime`,`unavailable`,e)}function TB(e){return new W(`runtime`,`invalid`,e)}function EB(){return new W(`runtime`,`closed`,`Shiitake client is closed`)}var DB=2,OB=O(M);function kB(e){if(!(e instanceof MessageEvent))throw TB(`Session stream event is invalid`);return OB(e.data)}function AB(e){return e.kind===`source-error`?v(wB(`Session stream is unavailable`)):e.kind===`snapshot`?oi({try:()=>({kind:`snapshot`,value:cB(kB(e.event))}),catch:()=>TB(`Session snapshot is invalid`)}):e.kind===`frame`?oi({try:()=>({kind:`frame`,value:lB(kB(e.event))}),catch:()=>TB(`Session frame is invalid`)}):oi({try:()=>uB(kB(e.event)),catch:()=>TB(`Session runtime error is invalid`)}).pipe(T(v))}function jB(e,t){return y(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function MB(e,t,n,r){return Uv(t=>Fr(oi({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Wg(t,{kind:e,event:r})||(qg(t,Wi(wB(`Session stream client fell behind`))),_r(jB(i,n)))};return i.source.addEventListener(`snapshot`,e=>{a(`snapshot`,e)}),i.source.addEventListener(`frame`,e=>{a(`frame`,e)}),i.source.addEventListener(`runtime-error`,e=>{a(`runtime-error`,e)}),i.source.addEventListener(`error`,e=>{i.source.readyState===DB&&a(`source-error`,e)}),n.add(i),i},catch:()=>wB(`Session stream could not open`)}),e=>jB(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(ny(AB),ay({duration:Sy,orElse:()=>qv(wB(`Session feed is connected but silent; the service may be busy`))}),gy(t.await))}function NB(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function PB(e,t,n=!1){let r=new URLSearchParams({mode:`subscribe`});return t!==void 0&&r.set(`after`,t),n&&r.set(`includeSandboxFailures`,`true`),`${e}?${r.toString()}`}function FB(e,t,n,r){return MB(e,t,n,r).pipe(ny(e=>e.kind===`frame`?x(e.value):v(TB(`Session subscription received a snapshot`))))}function IB(e,t,n,r,i,a){return b(function*(){yield*n;let o=yield*E_(!1),s=yield*Ca();yield*y(()=>t.add(s)),yield*Da(s,y(()=>{t.delete(s)}));let c=yield*Ln(MB(e,r,i,a).pipe(fy(Nv()),Ta(s)));if(la(c))return yield*Aa(s,c),yield*Zt(c.cause);let[l,u]=c.value;if(on(l)||l.value.kind!==`snapshot`){let e=TB(`Session stream did not begin with a snapshot`);return yield*Aa(s,aa(e)),yield*v(e)}let d=u.pipe(ny(e=>e.kind===`frame`?x(e.value):x({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),gy(o.await),py(e=>o.isOpen()&&Ki(e)?Wv:Jv(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(g(Aa(s,sa)))})})}function LB(e,t,n){return pn({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>wB(`${n} request failed`)}).pipe(T(({response:e,body:r})=>e.ok?oi({try:()=>t(r),catch:()=>TB(`${n} response is invalid`)}):oi({try:()=>uB(r),catch:()=>TB(`${n} error response is invalid`)}).pipe(T(v))))}function RB(e){let t=e.baseUrl.replace(/\/+$/u,``),n=e.fetch??globalThis.fetch,r=new Set,i=new Set,a=T_(!1),o=!1,s=sr(()=>o?v(EB()):C),c=(e,t,n)=>Dn(LB(e,t,n),a.await.pipe(g(v(EB())))),l=(e,t)=>s.pipe(g(c(r=>n(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:r}),tB,`Extension command`)));return Object.freeze({createSession:e=>s.pipe(T(()=>{let r=Cb({requestId:e});return c(e=>n(`${t}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:r}),signal:e}),gB,`Session creation`)})),deleteSession:e=>s.pipe(T(()=>{let r=xb(e);return c(e=>n(`${t}/sessions/${encodeURIComponent(r)}`,{method:`DELETE`,signal:e}),hB,`Session deletion`)})),listSessions:e=>s.pipe(T(()=>{let r=new URLSearchParams;e!==void 0&&r.set(`after`,Sb(e));let i=r.size===0?``:`?${r.toString()}`;return c(e=>n(`${t}/sessions${i}`,{signal:e}),fB,`Session discovery`)})),extensions:Object.freeze({list:s.pipe(g(c(e=>n(`${t}/extensions`,{signal:e}),eB,`Extension list`))),resume:e=>s.pipe(g(c(r=>n(`${t}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:r}),$z,`Extension resume`))),call:(e,n,r)=>l(`${t}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(n)}`,r)}),session:o=>{let u=xb(o),d=NB(t,u),f=`${d}/events`;function p(e){return s.pipe(g(c(t=>n(`${d}/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({command:e}),signal:t}),e.type===`prompt`||e.type===`compact`?nB:e.type===`cancel`?rB:e.type===`fork`?aB:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>s.pipe(g(c(t=>n(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),Vz,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>y(()=>t?.requestId??rg()).pipe(T(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return p(t?.images===void 0?r:{...r,images:t.images}).pipe(ut(e=>e.requestId===n?e:new W(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:s.pipe(g(c(e=>n(`${d}/pending/latest`,{signal:e}),iB,`Newest pending prompt`))),modelPreference:Object.freeze({read:s.pipe(g(c(e=>n(`${d}/model-preference`,{signal:e}),Fy,`Model preference read`))),set:e=>s.pipe(g(c(t=>n(`${d}/model-preference`,{signal:t,method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),()=>void 0,`Model preference set`)))}),extension:e=>Object.freeze({call:(t,n)=>l(`${d}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,n)}),read:e=>s.pipe(g(oi({try:()=>wb(e),catch:e=>e instanceof W?e:TB(`Read options are invalid`)})),T(({limit:e,before:t,includeSandboxFailures:r})=>{let i=new URLSearchParams({limit:String(e)});return t!==void 0&&i.set(`before`,t),r===!0&&i.set(`includeSandboxFailures`,`true`),c(e=>n(`${d}?${i.toString()}`,{signal:e}),cB,`Session read`)})),readSettlement:(e,t=0)=>s.pipe(g(c(r=>n(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:r}),sB,`Command settlement`))),subscribe:t=>ey(s.pipe(g(oi({try:()=>Tb(t),catch:e=>e instanceof W?e:TB(`Subscribe options are invalid`)})),we(({after:t,includeSandboxFailures:n})=>FB(PB(f,t,n===!0),a,i,e.eventSource)))),watch:t=>IB(t?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,r,s,a,i,e.eventSource)})},close:sr(()=>o?C:(o=!0,a.open.pipe(g(Zr([...r],e=>Aa(e,sa),{discard:!0})),g(Zr([...i],e=>jB(e,i),{discard:!0})))))})}function zB(e){return SB(RB(e),e.baseUrl.replace(/\/+$/u,``))}D(UO);function BB(e,t){if(t===void 0)return{status:`unavailable`};if(t.status===`stopped`)return{status:`stopped`,reason:t.reason};if(t.value===null||e.projection===null)return{status:`running`,value:null};let n=D(e.projection.schema)(t.value);return n._tag===`Success`?{status:`running`,value:n.success}:{status:`stopped`,reason:`Extension projection does not match this client`}}function VB(e,t){let n=e?.messageId===t.messageId?e:null;if(n!==null&&n.revision>=t.revision)return e;let r=n===null?0:n.textOffset+n.text.length,i=n===null?0:n.thinkingOffset+n.thinking.length;return t.text.offset>r||t.thinking.offset>i?e:{messageId:t.messageId,revision:t.revision,text:(n?.text??``)+t.text.append.slice(Math.max(0,r-t.text.offset)),thinking:(n?.thinking??``)+t.thinking.append.slice(Math.max(0,i-t.thinking.offset)),textOffset:n?.textOffset??0,thinkingOffset:n?.thinkingOffset??0,textTruncated:n?.textTruncated??!1,thinkingTruncated:n?.thinkingTruncated??!1}}var HB=M.pipe(z(hh(1)),z(vh(128)),z(Pm(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),UB=M.pipe(z(hh(1)),z(vh(64)),z(Pm(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u))),WB=HB.pipe(xm(`ExtensionId`)),GB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionRevision`)),KB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionFingerprint`)),qB=class extends zi(`ExtensionHookError`){};function JB(e){return sr(()=>{let t=e();return Ke(t)?t:pn({try:()=>Promise.resolve(t),catch:e=>new qB({cause:e})})})}var YB=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function XB(e,t){let n=e(t);if(n instanceof Promise||Ke(n)&&!gr(n))throw new YB;return n}export{vR as $,Dc as $a,Am as $i,ZO as $n,S_ as $r,iM as $t,az as A,Oh as Aa,mm as Ai,_A as An,la as Ao,My as Ar,SL as At,BR as B,ym as Ba,Gp as Bi,kk as Bn,Qi as Bo,qv as Br,jM as Bt,ZR as C,ch as Ca,R as Ci,yj as Cn,_a as Co,xb as Cr,ZF as Ct,AR as D,Eh as Da,P as Di,mA as Dn,ba as Do,W as Dr,eL as Dt,vz as E,kh as Ea,M as Ei,OA as En,ha as Eo,Eb as Er,eI as Et,WR as F,Im as Fa,am as Fi,aA as Fn,sa as Fo,xy as Fr,zM as Ft,mz as G,zp as Ga,D as Gi,ck as Gn,$v as Gr,mM as Gt,sz as H,Xh as Ha,Hp as Hi,Dk as Hn,$i as Ho,Qv as Hr,fM as Ht,qR as I,B as Ia,xm as Ii,rA as In,Gi as Io,Sy as Ir,VM as It,TR as J,Ad as Ja,Qp as Ji,ok as Jn,by as Jr,wM as Jt,DR as K,Om as Ka,O as Ki,lk as Kn,vy as Kr,hM as Kt,KR as L,A as La,z as Li,Zk as Ln,Wi as Lo,Uv as Lr,DM as Lt,QR as M,eh as Ma,sm as Mi,uA as Mn,da as Mo,Dy as Mr,pN as Mt,$R as N,Pm as Na,vm as Ni,lA as Nn,ua as No,Ty as Nr,fN as Nt,PR as O,bh as Oa,lm as Oi,yA as On,fa as Oo,Ny as Or,fL as Ot,oz as P,zm as Pa,I as Pi,$k as Pn,ra as Po,ky as Pr,gN as Pt,uR as Q,rd as Qa,U as Qi,QO as Qn,b_ as Qr,sM as Qt,GR as R,k as Ra,Mp as Ri,iA as Rn,Zi as Ro,sy as Rr,kM as Rt,XR as S,ph as Sa,om as Si,gj as Sn,Ta as So,Cb as Sr,xI as St,HR as T,vh as Ta,fm as Ti,AA as Tn,ga as To,Tb as Tr,$F as Tt,LR as U,Yh as Ua,Up as Ui,Nk as Un,Ji as Uo,zv as Ur,pM as Ut,iz as V,km as Va,Kp as Vi,Mk as Vn,Ki as Vo,oy as Vr,AM as Vt,IR as W,Jh as Wa,Wp as Wi,Ak as Wn,zi as Wo,ny as Wr,gM as Wt,yR as X,kc as Xa,Jp as Xi,pk as Xn,D_ as Xr,EM as Xt,CR as Y,Nc as Ya,wm as Yi,mk as Yn,ey as Yr,TM as Yt,lR as Z,Ec as Za,Yp as Zi,$O as Zn,T_ as Zr,MM as Zt,OR as _,th as _a,L as _i,Gj as _n,Da as _o,zT as _r,QF as _t,KB as a,yh as aa,Tg as ai,Jj as an,jc as ao,QD as ar,uL as at,FR as b,sh as ba,hm as bi,VA as bn,Ca as bo,wb as br,UI as bt,UB as c,Bm as ca,F as ci,rM as cn,Qu as co,KE as cr,dL as ct,zB as d,uh as da,Nh as di,Wj as dn,Us as do,IE as dr,mF as dt,Vp as ea,x_ as ei,$j as en,xc as eo,YO as er,fR as et,_B as f,ah as fa,Hm as fi,Kj as fn,Ws as fo,LE as fr,oF as ft,RR as g,Vm as ga,j as gi,Bj as gn,Sa as go,jT as gr,cF as gt,nB as h,oh as ha,Qh as hi,eM as hn,Lo as ho,MT as hr,wF as ht,WB as i,lh as ia,wg as ii,Zj as in,Sc as io,TD as ir,WF as it,JR as j,Th as ja,zh as ji,gA as jn,ca as jo,Ey as jr,tP as jt,yz as k,hh as ka,Lh as ki,vA as kn,ia as ko,Py as kr,KI as kt,VB as l,Um as la,um as li,Rj as ln,Ou as lo,GE as lr,qI as lt,CB as m,dh as ma,Zh as mi,Yj as mn,ps as mo,TE as mr,CF as mt,JB as n,mh as na,Gg as ni,tM as nn,Ac as no,HO as nr,GL as nt,HB as o,Ah as oa,bg as oi,Ij as on,Zu as oo,bD as or,$I as ot,vB as p,V as pa,H as pi,nM as pn,Ks as po,jE as pr,QP as pt,wR as q,cf as qa,Xp as qi,hk as qn,ay as qr,_M as qt,XB as r,Sh as ra,Wg as ri,Vj as rn,wc as ro,NO as rr,xP as rt,GB as s,Dh as sa,rg as si,Hj as sn,$u as so,VE as sr,lF as st,YB as t,$m as ta,Jg as ti,Uj as tn,Tc as to,UO as tr,IL as tt,BB as u,Xm as ua,cm as ui,zj as un,pc as uo,HE as ur,ZI as ut,kR as v,Zm as va,nh as vi,qj as vn,Aa as vo,aT as vr,SF as vt,VR as w,xh as wa,N as wi,_j as wn,va as wo,Yy as wr,KF as wt,YR as x,Qm as xa,jh as xi,bj as xn,wa as xo,vb as xr,xL as xt,zR as y,fh as ya,im as yi,Xj as yn,Oa as yo,_b as yr,yF as yt,gz as z,bm as za,jp as zi,jk as zn,Xi as zo,_y as zr,OM as zt};
|
|
867
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,YP(i),n.state,JP(i),i.workId,wj(i),n.timestamp,n.completedAt),a=t,o=t,s+=1,l=n.sequence}if(!t.more)break}if(o===null)throw $(`Fork path is empty`);e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,o,i,r);let u=SI(e,{sessionId:t.sessionId});for(let t of lM(e,(t,n)=>jI(e,u,t,n)))nI(e,{sessionId:r,id:Tj.fact.generate(),entry:t});return dN(e,{sessionId:r,activityAt:i,title:KP(e,r)}),r})}function SL(e,t,n,r){if(tF(e,t)===void 0)throw $(`Session document owner is unavailable`);return jI(e,SI(e,{sessionId:t}),n,r)}function CL(e,t,n,r,i){if(tF(e,t)===void 0)throw $(`Session document owner is unavailable`);nI(e,{sessionId:t,id:Tj.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var wL=2097152,TL=200,EL=200,DL=new TextEncoder;function OL(e){return new W(`store`,`unavailable`,e)}function kL(e,t,n){let r=new Map;for(let e of n)e.entry.kind===`command`&&r.set(e.entry.workId,e.entry.workId);let i=n.flatMap(({entry:e})=>(e.kind===`run_terminal`||e.kind===`work_terminal`)&&!r.has(e.workId)?[e.workId]:[]);for(let n of i)vF(e,t,n)!==void 0&&r.set(n,n);return r}function AL(e,t){return n=>{let r=vF(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function jL(e,t,n){return{commandIds:kL(e,t,n),diagnostics:PL(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:AL(e,t)}}function ML(e,t,n,r){let i=NI(e,n,new Set(r.flatMap(({entry:e})=>e.kind===`message`||e.kind===`run_terminal`||e.kind===`work_terminal`?[e.workId]:[]))),a=new Map;for(let e of i.commands)a.set(e,e);for(let{entry:n}of r)(n.kind===`run_terminal`||n.kind===`work_terminal`)&&!a.has(n.workId)&&vF(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:AL(e,t)}}function NL(e,t){let n=vj(e.entry);if(n!==void 0){let r=t.origin(n.workId),i={id:e.id,sequence:e.sequence,commandId:n.workId,requestId:n.requestId,value:n.message};return n.meta!==void 0&&(i={...i,meta:n.meta}),r!==void 0&&(i={...i,origin:r}),Object.freeze(i)}if(e.entry.kind===`operator`){let t={id:e.id,sequence:e.sequence,commandId:null,requestId:e.entry.requestId,value:Sj(e.entry)};return e.entry.meta!==void 0&&(t={...t,meta:e.entry.meta}),Object.freeze(t)}if(e.entry.kind===`message`){let n={id:e.entry.message.value,sequence:e.sequence,commandId:t.commandIds.get(e.entry.workId)??null,value:e.entry.value};return Object.freeze(e.entry.data===void 0?n:{...n,data:e.entry.data})}}function PL(e){let t=new Map;for(let{entry:n}of e)(n.kind===`work_terminal`||n.kind===`run_terminal`)&&n.diagnostic!==void 0&&t.set(n.workId,n.diagnostic);return t}function FL(e,{commandIds:t,diagnostics:n,cancellations:r}){if(e.entry.kind!==`run_terminal`&&e.entry.kind!==`work_terminal`)return;let i=t.get(e.entry.workId);if(i===void 0)return;let a={commandId:i,outcome:e.entry.outcome,sequence:e.sequence,diagnostic:n.get(e.entry.workId)??null},o=e.entry.outcome===`cancelled`?r.get(e.entry.workId):void 0;return Object.freeze(o===void 0?a:{...a,meta:o})}var IL=new WeakMap;function LL(e){let t=IL.get(e);if(t===void 0)throw OL(`Session compaction entry position is unavailable`);return t}function RL(e,t,n){let r=[];for(let i of n){let a=i.entry;if(a.kind!==`compaction`)continue;let o=n.find(e=>e.id===a.head)?.sequence??OI(e,t,a.head);if(o===void 0)throw OL(`Session compaction horizon is unavailable`);let s=Object.freeze({id:i.id,sequence:o,at:i.timestamp,tokensBefore:a.data.tokensBefore,tokensAfter:a.data.tokensAfter??null,trigger:a.data.reason??null});IL.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function zL(e){return Object.freeze(e.flatMap(({id:e,sequence:t,timestamp:n,entry:r})=>r.kind===`compaction_notice`?[Object.freeze({id:e,sequence:t,at:n,trigger:r.trigger,result:r.result,diagnostic:r.result===`stale`||r.result===`insufficient`?null:r.diagnostic??null})]:[]))}function BL(e){return DL.encode(JSON.stringify(e)).byteLength}function VL(e,t){let n=OA({generation:e,sequence:t});if(n===void 0)throw OL(`Session cursor is unavailable`);return n}function HL(e,t,n,r,i=!1){let a=NL(t,r),o=FL(t,r),s=i&&t.entry.kind===`sandbox_failure`?t.entry.event:void 0;if(a!==void 0&&e.messages.length===n)return!1;let c=(a===void 0?0:BL(a))+(o===void 0?0:BL(o))+(s===void 0?0:BL(s));if(c>wL)throw OL(`Session projection entry exceeds the read bound`);return e.bytes+c>wL?!1:(a!==void 0&&e.messages.push(a),o!==void 0&&e.terminals.push(o),s!==void 0&&e.sandboxFailures.push(s),e.bytes+=c,!0)}function UL(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==EL;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!HL(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw OL(`Session page cannot make bounded progress`);let c=i===`backward`?[...o.messages].reverse():o.messages,l=i===`backward`?[...o.terminals].reverse():o.terminals,u=i===`backward`?[...o.sandboxFailures].reverse():o.sandboxFailures;return Object.freeze({messages:Object.freeze(c),terminals:Object.freeze(l),sandboxFailures:Object.freeze(u),consumed:s,hasMore:t||s<e.length})}function WL(e){return Array.isArray(e)}function GL(e,t){let{commands:n,total:r}=pF(e,t,EL+1,`prompts`),i=[],a=DL.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=qL(e),n=DL.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===EL||a+n>wL)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function KL(e,t,n){let r=dF(e,t,n);return r===void 0?null:qL(r)}function qL(e){let t=vj(e.entry);if(t===void 0)throw OL(`Pending Session prompt is unavailable`);let n=t.message.content,r=WL(n)?{commandId:e.entry.workId,requestId:t.requestId,text:n.filter(e=>e.type===`text`).map(e=>e.text).join(``),images:n.filter(e=>e.type===`image`),delivery:t.delivery??`followUp`}:{commandId:e.entry.workId,requestId:t.requestId,text:n,delivery:t.delivery??`followUp`},i=e.entry.meta===void 0?r:{...r,meta:e.entry.meta};return e.origin.kind===`extension`?{...i,origin:{extensionId:e.origin.extensionId,correlation:e.origin.correlation}}:i}function JL(e,t,n){let r=kA(n);if(r?.generation===t.rootId)return DI(e,t,r.sequence)?r.sequence:void 0}function YL(e,t,n,r,i=()=>({})){return dI(e,t,()=>{let a=GL(e,t),o=SI(e,{sessionId:t});if(o===void 0)return Object.freeze({sessionId:t,cursor:null,hasMore:!1,oldestCursor:null,messages:Object.freeze([]),terminals:Object.freeze([]),compactions:Object.freeze([]),compactionNotices:Object.freeze([]),pending:a,activity:r.facts,progress:r.readProgress(),toolOutput:r.toolOutput,extensions:i(),attention:Ok(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:JL(e,o,n.before);if(c===void 0)throw OL(`Session read cursor is unavailable`);let l=EI(e,o,{before:c,from:`newest`,rows:EL}),u=UL(l.rows,l.more,n.limit,ML(e,t,o,l.rows),`backward`,n.includeSandboxFailures===!0),d=l.rows.slice(l.rows.length-u.consumed),f=l.rows.at(-1),p=d[0],m={sessionId:t,cursor:f===void 0?null:VL(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?VL(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:RL(e,o,d),compactionNotices:zL(d),pending:a,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:Ok(e,t)},ee=hA(e,t);return ee!==void 0&&Object.assign(m,{parent:ee}),Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var XL=Object.freeze({kind:`reset`});function ZL(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return DI(e,t,n.sequence)?n.sequence:void 0}function QL(e,t,n,r,i,a,o,s,c){let l=EI(e,t,{after:n,from:`oldest`,rows:EL}),u=UL(l.rows,l.more,TL,ML(e,t.sessionId,t,l.rows),`forward`,c),d=l.rows.slice(0,u.consumed),f=d.at(-1)?.sequence??t.newestSequence,p={kind:`update`,delivery:r,cursor:VL(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:RL(e,t,d),compactionNotices:zL(d),pending:s,activity:i.facts,extensions:a,attention:o},m=[Object.freeze(c?{...p,sandboxFailures:u.sandboxFailures}:p)];return Object.freeze({kind:`page`,frames:Object.freeze(u.hasMore?m:[...m,{kind:`tool_output`,toolOutput:i.toolOutput,activity:i.facts}]),hasMore:u.hasMore})}function $L(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:kA(n);return n!==void 0&&s===void 0?XL:dI(e,t,()=>{let c=GL(e,t),l=SI(e,{sessionId:t});if(l===void 0)return n===void 0?{kind:`page`,frames:[{kind:`update`,delivery:r,cursor:null,messages:[],terminals:[],compactions:[],compactionNotices:[],activity:i.facts,extensions:a(),attention:Ok(e,t),pending:c}],hasMore:!1}:XL;let u=ZL(e,l,s);return u===void 0?XL:QL(e,l,u,r,i,a(),Ok(e,t),c,o)})}function eR(e,t,n){let r=vF(e,t,n);if(r===void 0)throw OL(`Accepted Session command is unavailable`);if(!xF(e,t,r.entry.workId))return;let i=SF(e,t,r.entry.workId),a=jL(e,t,i),o=i.flatMap(e=>{let t=FL(e,a);return t===void 0?[]:[t]}).at(-1);if(o===void 0)return;let s=i.flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`?[e.value]:[]),c=s.at(-1),l=o.outcome===`cancelled`?o.meta:r.entry.meta,u=Eg(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:dA(e,t)?.replyTo[0]?.agentId??null,terminal:l===void 0?o:{...o,meta:l},content:o.outcome===`cancelled`?``:c?.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()??``,usage:s.map(({provider:e,model:t,usage:n})=>({provider:e,model:t,usage:n})),toolCalls:new Set(i.flatMap(({entry:e})=>e.kind===`tool_intent`?[e.call.id]:[])).size,waitingOnYou:yA(e,t,r.entry.workId)}}var tR=65536,nR=250,rR=2048,iR=new TextEncoder,aR=()=>({chunks:[],length:0,bytes:0});function oR(e,t){for(let n=0;n<t.length;){let r=Math.min(n+rR,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=iR.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=rR?(s.text+=a,s.bytes+=o):e.chunks.push({offset:e.length,text:a,bytes:o}),e.length+=a.length,e.bytes+=o,n=r;e.bytes>tR&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function sR(e){return e.chunks[0]?.offset??0}function cR(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function lR(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:cR(e.text,sR(e.text)),thinking:cR(e.thinking,sR(e.thinking)),textOffset:sR(e.text),thinkingOffset:sR(e.thinking),textTruncated:sR(e.text)>0,thinkingTruncated:sR(e.thinking)>0}}function uR(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function dR(e,t,n,r){let i=fR.get(e)?.get(t),a=i?.workId===n?i.value:null;if(a===null)return null;let o=r?.messageId===a.messageId?r:null;if(o!==null&&o.revision>=a.revision)return null;let s=o?.text??0,c=o?.thinking??0;if(!(s<sR(a.text)||c<sR(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:cR(a.text,s)},thinking:{offset:c,append:cR(a.thinking,c)}}}var fR=new WeakMap;function pR(e,t,n){let r=fR.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var mR=D(P({droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))}),{onExcessProperty:`error`});function hR(e,t){return b(function*(){let n=yield*_R(e,t),r=()=>{mk(e,t.sessionId,`progress`)};return{started:e=>y(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>y(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=mR(e.result.data);if(Ae(i))return;let a=e.result.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);new TextEncoder().encode(a).byteLength>8192||a.split(`
|
|
868
|
+
`).length>200||i.success.droppedBytes>i.success.totalBytes||(n.slots.set(e.toolCall.value,{toolCallId:e.call.id,revision:(t?.revision??0)+1,tail:a,...i.success}),r())}),terminal:e=>y(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function gR(e){let t=fR.get(e);if(t!==void 0)return t;let n=new Map;return fR.set(e,n),n}function _R(e,t){return b(function*(){let n=gR(e),r=n.get(t.sessionId);if(r?.workId===t.commandId)return r;let i={workId:t.commandId,value:null,slots:new Map};return n.set(t.sessionId,i),yield*Tr(()=>y(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&mk(e,t.sessionId,`progress`))})),i})}function vR(e){return new W(`runtime`,`rejected`,e)}function yR(e,t,n){let r=gR(e).get(t);return lR(r?.workId===n?r.value:null)}function bR(e,t,n){let r=fR.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function xR(e,t,n,r){return b(function*(){let i=yield*_R(e,t);if(r!==void 0&&i.value===null){let n=aR();n.length=r.offset,oR(n,r.text),i.value={recovered:!0,messageId:r.messageId,revision:1,text:n,thinking:aR()},mk(e,t.sessionId,`progress`)}let a,o=0,s=0,c,l=()=>{c!==void 0&&clearTimeout(c),c=void 0},u=()=>{l();let n=i.value;n!==null&&(s=n.text.length+n.thinking.length,mk(e,t.sessionId,`progress`))},d=y(()=>{l();let n=i.value!==null;i.value=null,n&&mk(e,t.sessionId,`progress`),a=void 0});return yield*Tr(()=>d),Object.freeze({started:e=>y(()=>{l(),a=e,o=0,i.value?.recovered!==!0&&(i.value=null),s=0}),update:n=>sr(()=>{let r=a;if(r===void 0)return v(vR(`Mule progress arrived before its message start`));if(r.run.value!==n.run.value||r.turn.value!==n.turn.value||r.message.value!==n.message.value)return v(vR(`Mule progress identity conflicts`));let l=n.event;if(l.type!==`text_delta`&&l.type!==`thinking_delta`||l.delta.length===0)return C;let d=i.value===null||i.value.recovered===!0,f=(d?null:i.value)??{messageId:n.message.value,revision:0,text:aR(),thinking:aR()};oR(l.type===`text_delta`?f.text:f.thinking,l.delta),f.revision++,i.value=f;let p=f.text.length+f.thinking.length;d||p-s>=4096?u():c??=setTimeout(u,100);let m=Date.now();return l.type!==`text_delta`||m-o<nR?C:(o=m,oi({try:()=>{ZI(e,{sessionId:t.sessionId,entry:{kind:`message_start`,workId:t.commandId,run:r.run,turn:r.turn,message:r.message,role:`assistant`},text:cR(f.text,sR(f.text)),offset:sR(f.text)})},catch:e=>new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)}))}),terminal:e=>d.pipe(g(n(e)))})})}var SR=new WeakMap;function CR(e){let t=SR.get(e);if(t!==void 0)return t;let n=new Map;return SR.set(e,n),n}function wR(e,t){return CR(e).get(t)??null}function TR(e,t,n){CR(e).set(t,Object.freeze({trigger:n})),mk(e,t,`progress`)}function ER(e,t){CR(e).delete(t)&&mk(e,t,`progress`)}var DR=Object.freeze({admitNew:()=>{}});function OR(e){return e===void 0?DR:Object.freeze({admitNew:()=>{if(e.underPressure())throw new W(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function kR(e,t){let n=$I(e,t);return mk(e,t.sessionId),n}function AR(e,t){let n=nL(e,t);return mk(e,t.sessionId),n}function jR(e,t){let n=rL(e,t);return n!==`stale`&&mk(e,t.sessionId),n}function MR(e){return new W(`store`,`rejected`,e)}function NR(e){return new W(`store`,`conflict`,e)}function PR(e){return oi({try:e,catch:e=>e instanceof W?e:new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function FR(e){return PR(()=>{XF(e)})}function IR(e,t,n,r,i,a,o){return PR(()=>{let s=_L(e,t,n,i,a,r,o);return s?.delivery===`new`&&mk(e,t,`settlement`),s})}function LR(e,t){return PR(()=>{let n=gF(e,t.sessionId,t.delivery,t.workId);return n.length>0&&mk(e,t.sessionId),n})}function RR(e,t){return PR(()=>{_F(e,t),mk(e,t.sessionId,`settlement`)})}function zR(e,t,n,r,i){return PR(()=>{let a=gL(e,t,n,r,i);return mk(e,t,`settlement`),a?.accepted})}function BR(e,t){return PR(()=>{yL(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),mk(e,t.sessionId)})}function VR(e,t){return PR(()=>{bL(e,t)&&mk(e,t.sessionId)})}function HR(e,t){return PR(()=>{let n=xL(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return mk(e,n),Object.freeze({sessionId:n})})}function UR(e,t){return PR(()=>{let n=YI(e,{sessionId:Sb(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&mk(e,t.sessionId),n})}function WR(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function GR(e,t){return PR(()=>{let n=vF(e,t.sessionId,t.commandFactId);if(n===void 0)throw MR(`Accepted Session command is unavailable`);let r=SF(e,t.sessionId,n.entry.workId);for(let e=r.length-1;e>=0;--e){let t=r[e]?.entry;if(t?.kind===`message`&&t.value.role===`assistant`){let e=WR(t.value);if(e!==``)return e}}return``})}function KR(e,t){return b(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*GR(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*PR(()=>{let n=vF(e,t.sessionId,i);if(n===void 0)throw MR(`Accepted Session command is unavailable`);if(oz(e,t.sessionId,i,n.entry.workId)===null)return;let r=iF(e,i);if(r===void 0)throw MR(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=iF(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw MR(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function qR(e,t,n){return PR(()=>{let r=vF(e,t.sessionId,t.commandFactId);if(r===void 0)throw MR(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=SF(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function JR(e,t){return PR(()=>{let n=vF(e,t.sessionId,t.commandFactId);if(n===void 0)throw MR(`Accepted Session command is unavailable`);return PL(SF(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function YR(e,t,n,r,i,a){return PR(()=>{let o=Sb(t),s=Tb(r);return uI(e,o,()=>a(YL(e,o,s,n(),i)),s.before===void 0?void 0:kA(s.before)?.sequence)})}function XR(e,t,n){return PR(()=>kF(e,wb({requestId:t}),n))}function ZR(e,t,n){return AF(e,wb({requestId:t}),n)}function QR(e,t){return PR(()=>jF(e,{sessionId:Sb(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{fN(e,t)}}))}function $R(e,t){return PR(()=>_N(e,t))}function ez(e,t,n,r,i,a,o,s){return PR(()=>{let c=Sb(t);return uI(e,c,()=>s($L(e,c,n,r,i,a,o)))})}function tz(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function nz(e,t){return e.core===t.core&&e.extensions.length===t.extensions.length&&e.extensions.every(([e,n],r)=>{let i=t.extensions[r];return i?.[0]===e&&i[1]===n})}function rz(e,t,n,r,i){i?.();let a=SF(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||dj(a.entry,n))return`replay`;throw NR(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=Tj.fact.generate();if(iF(e,r)===void 0&&vF(e,t.sessionId,r)===void 0)return nI(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw MR(`Session fact identity allocation failed`)}function iz(e,t,n,r,i){e.transactionSync(()=>rz(e,t,n,r,i))===`new`&&mk(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`)}function az(e,t,n){return PR(()=>{iz(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function oz(e,t,n,r){let i=vF(e,t,n);if(i?.entry.workId!==r)throw MR(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function sz(e,t,n,r){let i=oz(e,t,n,r),a=SF(e,t,r).map(({entry:e})=>e),o=new Set(a.flatMap(e=>e.kind===`tool_intent`?[e.call.id]:[])).size,s=a.filter(e=>e.kind===`run_terminal`||e.kind===`work_terminal`).at(-1);return Object.freeze({terminal:s?.kind===`run_terminal`||s?.kind===`work_terminal`?s.outcome:`missing`,origin:i,toolCalls:o})}function cz(e,t){return PR(()=>{if(vF(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw MR(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};iz(e,{sessionId:t.sessionId,commandId:t.workId},t.diagnostic===void 0?n:{...n,diagnostic:t.diagnostic},({entry:e})=>e.kind===`work_terminal`||e.kind===`run_terminal`&&e.outcome===t.outcome,()=>{e.sql.exec(`DELETE FROM session_entries WHERE session_id = ? AND work_id = ? AND state = 'streaming' AND type = 'message_start'`,t.sessionId,t.workId)})})}function lz(e,t,n,r,i){return PR(()=>{let a=r.type===`run_start`?{kind:`run_started`,workId:t.commandId,run:r.run,contract:n}:r.type===`turn_start`?{kind:`turn_started`,workId:t.commandId,run:r.run,turn:r.turn}:{kind:`run_terminal`,workId:t.commandId,run:r.run,terminal:r.terminal,outcome:r.outcome};a.kind===`run_terminal`&&i!==void 0&&(a={...a,diagnostic:i}),iz(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?tz(e.run,a.run)&&nz(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?tz(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&tz(e.terminal,a.terminal):!1)})}function uz(e,t,n){return PR(()=>{let r={kind:`message_start`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,role:n.value.role};e.transactionSync(()=>{let i=SF(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&tz(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!tz(i.entry.run,r.run)||!tz(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw NR(`Mule message-start identity conflicts`);return`replay`}if(i.entry.kind!==`message_start`||!dj(uj(i.entry),r))throw NR(`Mule message-start identity conflicts`);return`replay`}return nI(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&mk(e,t.sessionId)})}function dz(e,t,n,r){return PR(()=>{iz(e,t,{kind:`model_prompt`,workId:t.commandId,run:r.run,turn:r.turn,attempt:r.attempt,contract:n,systemPrompt:r.systemPrompt},({entry:e})=>e.kind===`model_prompt`&&tz(e.turn,r.turn)&&e.attempt===r.attempt&&nz(e.contract,n))})}function fz(e,t,n,r){return PR(()=>{let i={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value},a=n.data===void 0?i:{...i,data:n.data};e.transactionSync(()=>{let i=SF(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&tz(e.message,n.message));if(i?.entry.kind===`message`){if(!dj(i.entry,a))throw NR(`Mule completed-message identity conflicts`)}else rI(e,{sessionId:t.sessionId,id:n.message.value,entry:a});let o=n.retry===void 0||n.value.role!==`assistant`?`replay`:gz(e,t,hz(n.retry,r),n.turn);return i?.entry.kind===`message`&&o===`replay`?`replay`:`new`})===`new`&&mk(e,t.sessionId)})}function pz(e,t,n,r){return PR(()=>{iz(e,t,{kind:`tool_intent`,replay:r.replay,contract:n,workId:t.commandId,run:r.run,turn:r.turn,toolCall:r.toolCall,call:r.call},({entry:e})=>e.kind===`tool_intent`&&tz(e.toolCall,r.toolCall)&&nz(e.contract,n))})}function mz(e,t,n){return PR(()=>{let{data:r,...i}=n.result,a={kind:`tool_outcome`,workId:t.commandId,run:n.run,turn:n.turn,toolCall:n.toolCall,call:n.call,result:i};iz(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&tz(e.toolCall,n.toolCall))})}function hz(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+QO({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,dueAt:e.dueAt,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function gz(e,t,n,r){let i=SF(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&tz(e.turn,r));if(i===void 0)throw NR(`Retry has no recorded turn`);return rz(e,t,{kind:`live_retry`,workId:t.commandId,event:n},({entry:e,sequence:t})=>t>i.sequence&&e.kind===`live_retry`&&e.event.type===n.type&&e.event.attempt===n.attempt&&tz(e.event.run,n.run))}function _z(e,t,n,r){return PR(()=>{e.transactionSync(()=>gz(e,t,n,r))===`new`&&mk(e,t.sessionId)}).pipe(ut(vz))}var vz=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function yz(e,t,n,r,i){return b(function*(){let a=yield*xR(e,t,n=>fz(e,t,n,r),i),o=yield*hR(e,t),s=(i,s)=>{switch(i.type){case`model_prompt`:return dz(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return lz(e,t,n,i,s);case`message_start`:return i.value.role===`user`?C:uz(e,t,i).pipe(g(i.value.role===`assistant`?a.started(i):C));case`message_update`:return a.update(i);case`message_end`:return i.value.role===`user`?C:i.value.role===`assistant`?a.terminal(i):fz(e,t,i,r);case`tool_execution_start`:return pz(e,t,n,i).pipe(g(o.started(i)));case`tool_execution_end`:return mz(e,t,i).pipe(g(o.terminal(i)));case`tool_execution_update`:return o.update(i);case`turn_end`:return C}};return(e,t)=>s(e,t).pipe(ut(vz))})}function bz(e,t,n){return PR(()=>eR(e,Sb(t),Sb(n)))}var xz=xP.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),Sz=P({requestId:k(M),meta:k(qO),data:k(WO),origin:k(xz),id:M,sequence:H.check(Zm(0)),commandId:R(M),value:$A}),Cz=L([`manual`,`threshold`,`overflow`]),wz=P({queue:I([P({state:j(`idle`)}),P({state:j(`queued`),commandId:Mh,runningWork:R(P({phase:L([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),P({state:j(`running`),commandId:Mh})]),cancellationRequested:cm,retry:R(P({attempt:H.check(Zm(0)),maxAttempts:H.check(Zm(0)),delayMs:H.check(V(0)),errorMessage:M,scheduledAt:H.check(V(0))})),activeTool:R(M),lastModelChoiceSequence:R(H.check(Zm(0))),compaction:R(P({trigger:Cz}))}),Tz=M,Ez=fm(M,I([P({status:j(`running`),revision:Tz,value:WO,catalog:k(WO)}),P({status:j(`stopped`),revision:Tz,reason:M})])),Dz=P({id:M,version:M,revision:Tz,status:L([`running`,`stopped`]),reason:R(M),stoppedAt:R(N)}),Oz=P({commandId:M,outcome:L([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:H.check(Zm(0)),diagnostic:R(M),meta:k(qO)}),kz=P({id:M,sequence:H.check(Zm(0)),at:H.check(V(0)),tokensBefore:N,tokensAfter:R(N),trigger:R(Cz)}),Az=P({id:M,sequence:H.check(Zm(0)),at:H.check(V(0)),trigger:Cz,result:L([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:R(M)}),jz=M.check(B(e=>new TextEncoder().encode(e).byteLength<=65536)),Mz=P({messageId:M,revision:H.check(V(0)),text:jz,thinking:jz,textOffset:H.check(V(0)),thinkingOffset:H.check(V(0)),textTruncated:cm,thinkingTruncated:cm}),Nz=P({commandId:M,requestId:M,meta:k(qO),origin:k(xz),text:M,images:k(F(Ky)),delivery:L([`steer`,`followUp`])}),Pz=F(P({toolCallId:M,revision:H.check(V(0)),tail:M.check(B(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
|
|
869
|
+
`).length<=200)),droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))})).check(yh(4)),Fz=P({total:H.check(V(0)),prompts:F(Nz),hasMore:cm}),Iz=P({tokens:H.check(V(0)),window:R(H.check(Zm(0)))}),Lz=P({parent:k(Ey),sessionId:M,cursor:R(M),hasMore:cm,oldestCursor:k(R(M)),messages:F(Sz),terminals:F(Oz),sandboxFailures:k(F(BO)),compactions:k(F(kz)),compactionNotices:k(F(Az)),pending:Fz,activity:wz,progress:R(Mz),toolOutput:Pz,extensions:Ez,attention:jy,context:k(Iz)}),Rz=I([P({kind:j(`heartbeat`)}),P({kind:j(`activity`),activity:wz}),P({kind:j(`tool_output`),toolOutput:Pz,activity:wz}),P({kind:j(`update`),delivery:L([`replay`,`live`]),cursor:R(M),messages:F(Sz),terminals:F(Oz),sandboxFailures:k(F(BO)),compactions:k(F(kz)),compactionNotices:k(F(Az)),pending:Fz,activity:wz,extensions:Ez,attention:jy,context:k(Iz)}),P({kind:j(`progress`),progress:P({messageId:M,revision:H.check(V(0)),text:P({offset:H.check(V(0)),append:jz}),thinking:P({offset:H.check(V(0)),append:jz})}),activity:wz}),P({kind:j(`reset`),reason:j(`history_unavailable`),cursor:R(M),baseline:Lz})]),zz=P({status:j(`accepted`),commandId:M,sessionId:k(M)});O(U(I([zz,P({status:j(`held`),reason:j(`recipient_offline`),message:j(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var Bz=P({status:j(`unknown`)}),Vz=O(U(I([zz,Bz])));function Hz(e){return Vz(e)}var Uz=I([zz,Bz,P({status:j(`too_late`),commandId:M})]),Wz=P({sessionId:M}),Gz=O(U(Lz),{onExcessProperty:`error`}),Kz=O(U(Rz),{onExcessProperty:`error`}),qz=O(U(zz)),Jz=O(U(Uz)),Yz=O(U(Wz)),Xz=O(U(By)),Zz=O(U(Dz)),Qz=O(U(F(Dz))),$z=O(U(WO));function eB(e){return Zz(e)}function tB(e){return Qz(e)}function nB(e){return $z(e)}function rB(e){return qz(e)}function iB(e){return Jz(e)}function aB(e){return O(U(R(Nz)))(e)}function oB(e){return Yz(e)}var sB=P({acceptedSender:R(M),delegator:R(M),terminal:Oz,content:M,usage:F(P({provider:M,model:M,usage:YA})),toolCalls:H.check(V(0)),waitingOnYou:F(P({itemId:M,kind:M,summary:M})).check(yh(8))});function cB(e){return O(U(R(sB)))(e)??void 0}function lB(e){return Gz(e)}function uB(e){return Kz(e)}function dB(e){let t=Xz(e);return new W(t.boundary,t.cause,t.message,t.requestId)}var fB=O(U(P({sessions:F(I([P({sessionId:Mh,createdAt:N,lastActivityAt:N,settledAt:k(N),title:M,state:L([`needs_you`,`running`,`errored`,`done`])}),P({sessionId:Mh,state:j(`unavailable`)})])),next:A(Mh)})));function pB(e){let t=fB(e);return{sessions:t.sessions,next:t.next}}var mB=O(U(P({sessionId:Mh}))),hB=O(U(P({deleted:cm})));function gB(e){return hB(e).deleted}function _B(e){return mB(e).sessionId}function vB(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:NO(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function yB(e,t){return Kn(e,t).then(e=>{if(ca(e))return e.value;let t=Gn(Xi(e.cause))??Ji(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function bB(e){let t=Pr(e);if(ca(t))return t.value;let n=Gn(Xi(t.cause))??Ji(t.cause);throw n instanceof Error?n:Error(String(n))}function xB(e){let t=xy(e);return Object.freeze({[Symbol.asyncIterator]:()=>{let e=t[Symbol.asyncIterator]();return{next:()=>e.next(),return:()=>e.return?.()??Promise.resolve({done:!0,value:void 0})}}})}function SB(e,t){function n(e){return yB(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>yB(t.withdraw(e)),abort:()=>yB(t.abort),send:(e,n)=>yB(t.send(e,n)),cancel:e=>yB(t.cancel(e)),latestPending:()=>yB(t.latestPending),modelPreference:Object.freeze({read:()=>yB(t.modelPreference.read),set:e=>yB(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>yB(n.call(e,t,r))})},read:e=>yB(t.read(e)),readSettlement:(e,n)=>yB(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>xB(t.subscribe(e)),watch:e=>yB(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:xB(e.changes),close:()=>yB(e.close)}))})}function CB(e,t){let n=t??`local:${ig()}`;return Object.freeze({createSession:t=>yB(e.createSession(t)),deleteSession:t=>yB(e.deleteSession(t)),listSessions:t=>yB(e.listSessions(t)),extensions:Object.freeze({list:()=>yB(e.extensions.list),resume:t=>yB(e.extensions.resume(t)),call:(t,n,r)=>yB(e.extensions.call(t,n,r))}),session:t=>SB(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>yB(e.close)})}function wB(e){let t=`local:${ig()}`;return Object.freeze({...CB(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:vB(t.tools)});let r=await yB(e.prepareConfiguration(n));return{commit:()=>{bB(r.commit)},discard:()=>yB(r.discard)}},grants:Object.freeze({deliver:(t,n)=>bB(e.grants.deliver(t,n)),read:t=>bB(e.grants.read(t))}),withMeta:n=>CB(e.withMeta(n),t)})}function TB(e=`Remote Shiitake operation is unavailable`){return new W(`runtime`,`unavailable`,e)}function EB(e){return new W(`runtime`,`invalid`,e)}function DB(){return new W(`runtime`,`closed`,`Shiitake client is closed`)}var OB=2,kB=O(M);function AB(e){if(!(e instanceof MessageEvent))throw EB(`Session stream event is invalid`);return kB(e.data)}function jB(e){return e.kind===`source-error`?v(TB(`Session stream is unavailable`)):e.kind===`snapshot`?oi({try:()=>({kind:`snapshot`,value:lB(AB(e.event))}),catch:()=>EB(`Session snapshot is invalid`)}):e.kind===`frame`?oi({try:()=>({kind:`frame`,value:uB(AB(e.event))}),catch:()=>EB(`Session frame is invalid`)}):oi({try:()=>dB(AB(e.event)),catch:()=>EB(`Session runtime error is invalid`)}).pipe(T(v))}function MB(e,t){return y(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function NB(e,t,n,r){return Wv(t=>Fr(oi({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Gg(t,{kind:e,event:r})||(Jg(t,Wi(TB(`Session stream client fell behind`))),_r(MB(i,n)))};return i.source.addEventListener(`snapshot`,e=>{a(`snapshot`,e)}),i.source.addEventListener(`frame`,e=>{a(`frame`,e)}),i.source.addEventListener(`runtime-error`,e=>{a(`runtime-error`,e)}),i.source.addEventListener(`error`,e=>{i.source.readyState===OB&&a(`source-error`,e)}),n.add(i),i},catch:()=>TB(`Session stream could not open`)}),e=>MB(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(ry(jB),oy({duration:Cy,orElse:()=>Jv(TB(`Session feed is connected but silent; the service may be busy`))}),_y(t.await))}function PB(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function FB(e,t,n=!1){let r=new URLSearchParams({mode:`subscribe`});return t!==void 0&&r.set(`after`,t),n&&r.set(`includeSandboxFailures`,`true`),`${e}?${r.toString()}`}function IB(e,t,n,r){return NB(e,t,n,r).pipe(ry(e=>e.kind===`frame`?x(e.value):v(EB(`Session subscription received a snapshot`))))}function LB(e,t,n,r,i,a){return b(function*(){yield*n;let o=yield*D_(!1),s=yield*Ca();yield*y(()=>t.add(s)),yield*Da(s,y(()=>{t.delete(s)}));let c=yield*Ln(NB(e,r,i,a).pipe(py(Pv()),Ta(s)));if(la(c))return yield*Aa(s,c),yield*Zt(c.cause);let[l,u]=c.value;if(on(l)||l.value.kind!==`snapshot`){let e=EB(`Session stream did not begin with a snapshot`);return yield*Aa(s,aa(e)),yield*v(e)}let d=u.pipe(ry(e=>e.kind===`frame`?x(e.value):x({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),_y(o.await),my(e=>o.isOpen()&&Ki(e)?Gv:Yv(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(g(Aa(s,sa)))})})}function RB(e,t,n){return pn({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>TB(`${n} request failed`)}).pipe(T(({response:e,body:r})=>e.ok?oi({try:()=>t(r),catch:()=>EB(`${n} response is invalid`)}):oi({try:()=>dB(r),catch:()=>EB(`${n} error response is invalid`)}).pipe(T(v))))}function zB(e){let t=e.baseUrl.replace(/\/+$/u,``),n=e.fetch??globalThis.fetch,r=new Set,i=new Set,a=E_(!1),o=!1,s=sr(()=>o?v(DB()):C),c=(e,t,n)=>Dn(RB(e,t,n),a.await.pipe(g(v(DB())))),l=(e,t)=>s.pipe(g(c(r=>n(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:r}),nB,`Extension command`)));return Object.freeze({createSession:e=>s.pipe(T(()=>{let r=wb({requestId:e});return c(e=>n(`${t}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:r}),signal:e}),_B,`Session creation`)})),deleteSession:e=>s.pipe(T(()=>{let r=Sb(e);return c(e=>n(`${t}/sessions/${encodeURIComponent(r)}`,{method:`DELETE`,signal:e}),gB,`Session deletion`)})),listSessions:e=>s.pipe(T(()=>{let r=new URLSearchParams;e!==void 0&&r.set(`after`,Cb(e));let i=r.size===0?``:`?${r.toString()}`;return c(e=>n(`${t}/sessions${i}`,{signal:e}),pB,`Session discovery`)})),extensions:Object.freeze({list:s.pipe(g(c(e=>n(`${t}/extensions`,{signal:e}),tB,`Extension list`))),resume:e=>s.pipe(g(c(r=>n(`${t}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:r}),eB,`Extension resume`))),call:(e,n,r)=>l(`${t}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(n)}`,r)}),session:o=>{let u=Sb(o),d=PB(t,u),f=`${d}/events`;function p(e){return s.pipe(g(c(t=>n(`${d}/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({command:e}),signal:t}),e.type===`prompt`||e.type===`compact`?rB:e.type===`cancel`?iB:e.type===`fork`?oB:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>s.pipe(g(c(t=>n(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),Hz,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>y(()=>t?.requestId??ig()).pipe(T(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return p(t?.images===void 0?r:{...r,images:t.images}).pipe(ut(e=>e.requestId===n?e:new W(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:s.pipe(g(c(e=>n(`${d}/pending/latest`,{signal:e}),aB,`Newest pending prompt`))),modelPreference:Object.freeze({read:s.pipe(g(c(e=>n(`${d}/model-preference`,{signal:e}),Iy,`Model preference read`))),set:e=>s.pipe(g(c(t=>n(`${d}/model-preference`,{signal:t,method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),()=>void 0,`Model preference set`)))}),extension:e=>Object.freeze({call:(t,n)=>l(`${d}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,n)}),read:e=>s.pipe(g(oi({try:()=>Tb(e),catch:e=>e instanceof W?e:EB(`Read options are invalid`)})),T(({limit:e,before:t,includeSandboxFailures:r})=>{let i=new URLSearchParams({limit:String(e)});return t!==void 0&&i.set(`before`,t),r===!0&&i.set(`includeSandboxFailures`,`true`),c(e=>n(`${d}?${i.toString()}`,{signal:e}),lB,`Session read`)})),readSettlement:(e,t=0)=>s.pipe(g(c(r=>n(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:r}),cB,`Command settlement`))),subscribe:t=>ty(s.pipe(g(oi({try:()=>Eb(t),catch:e=>e instanceof W?e:EB(`Subscribe options are invalid`)})),we(({after:t,includeSandboxFailures:n})=>IB(FB(f,t,n===!0),a,i,e.eventSource)))),watch:t=>LB(t?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,r,s,a,i,e.eventSource)})},close:sr(()=>o?C:(o=!0,a.open.pipe(g(Zr([...r],e=>Aa(e,sa),{discard:!0})),g(Zr([...i],e=>MB(e,i),{discard:!0})))))})}function BB(e){return CB(zB(e),e.baseUrl.replace(/\/+$/u,``))}D(WO);function VB(e,t){if(t===void 0)return{status:`unavailable`};if(t.status===`stopped`)return{status:`stopped`,reason:t.reason};if(t.value===null||e.projection===null)return{status:`running`,value:null};let n=D(e.projection.schema)(t.value);return n._tag===`Success`?{status:`running`,value:n.success}:{status:`stopped`,reason:`Extension projection does not match this client`}}function HB(e,t){let n=e?.messageId===t.messageId?e:null;if(n!==null&&n.revision>=t.revision)return e;let r=n===null?0:n.textOffset+n.text.length,i=n===null?0:n.thinkingOffset+n.thinking.length;return t.text.offset>r||t.thinking.offset>i?e:{messageId:t.messageId,revision:t.revision,text:(n?.text??``)+t.text.append.slice(Math.max(0,r-t.text.offset)),thinking:(n?.thinking??``)+t.thinking.append.slice(Math.max(0,i-t.thinking.offset)),textOffset:n?.textOffset??0,thinkingOffset:n?.thinkingOffset??0,textTruncated:n?.textTruncated??!1,thinkingTruncated:n?.thinkingTruncated??!1}}var UB=M.pipe(z(gh(1)),z(yh(128)),z(Fm(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),WB=M.pipe(z(gh(1)),z(yh(64)),z(Fm(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u))),GB=UB.pipe(xm(`ExtensionId`)),KB=M.pipe(z(Fm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionRevision`)),qB=M.pipe(z(Fm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionFingerprint`)),JB=class extends zi(`ExtensionHookError`){};function YB(e){return sr(()=>{let t=e();return Ke(t)?t:pn({try:()=>Promise.resolve(t),catch:e=>new JB({cause:e})})})}var XB=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function ZB(e,t){let n=e(t);if(n instanceof Promise||Ke(n)&&!gr(n))throw new XB;return n}export{yR as $,rd as $a,jm as $i,QO as $n,C_ as $r,aM as $t,oz as A,kh as Aa,mm as Ai,vA as An,ia as Ao,Ny as Ar,CL as At,VR as B,ym as Ba,Gp as Bi,Ak as Bn,Xi as Bo,Jv as Br,MM as Bt,QR as C,lh as Ca,R as Ci,bj as Cn,Ta as Co,Sb as Cr,QF as Ct,jR as D,Dh as Da,P as Di,hA as Dn,ha as Do,W as Dr,tL as Dt,yz as E,Ah as Ea,M as Ei,kA as En,ga as Eo,Db as Er,tI as Et,GR as F,Lm as Fa,am as Fi,oA as Fn,ra as Fo,Sy as Fr,BM as Ft,hz as G,zp as Ga,D as Gi,lk as Gn,zi as Go,ey as Gr,hM as Gt,cz as H,Zh as Ha,Hp as Hi,Ok as Hn,Ki as Ho,$v as Hr,pM as Ht,JR as I,B as Ia,xm as Ii,iA as In,sa as Io,Cy as Ir,HM as It,ER as J,cf as Ja,Qp as Ji,sk as Jn,xy as Jr,TM as Jt,OR as K,Dm as Ka,O as Ki,uk as Kn,yy as Kr,gM as Kt,qR as L,A as La,z as Li,Qk as Ln,Gi as Lo,Wv as Lr,OM as Lt,$R as M,th as Ma,sm as Mi,dA as Mn,ca as Mo,Oy as Mr,mN as Mt,ez as N,Fm as Na,vm as Ni,uA as Nn,da as No,Ey as Nr,pN as Nt,FR as O,xh as Oa,lm as Oi,bA as On,ba as Oo,Py as Or,pL as Ot,sz as P,Bm as Pa,I as Pi,eA as Pn,ua as Po,Ay as Pr,_N as Pt,dR as Q,Ec as Qa,U as Qi,$O as Qn,x_ as Qr,cM as Qt,KR as R,k as Ra,Mp as Ri,aA as Rn,Wi as Ro,cy as Rr,AM as Rt,ZR as S,mh as Sa,om as Si,_j as Sn,wa as So,wb as Sr,SI as St,UR as T,yh as Ta,fm as Ti,jA as Tn,va as To,Eb as Tr,eI as Tt,RR as U,Xh as Ua,Up as Ui,Pk as Un,$i as Uo,Bv as Ur,mM as Ut,az as V,Am as Va,Kp as Vi,Nk as Vn,Qi as Vo,sy as Vr,jM as Vt,LR as W,Yh as Wa,Wp as Wi,jk as Wn,Ji as Wo,ry as Wr,_M as Wt,bR as X,Nc as Xa,Jp as Xi,mk as Xn,O_ as Xr,DM as Xt,wR as Y,Ad as Ya,wm as Yi,hk as Yn,ty as Yr,EM as Yt,uR as Z,kc as Za,Yp as Zi,ek as Zn,E_ as Zr,NM as Zt,kR as _,nh as _a,L as _i,Kj as _n,Sa as _o,BT as _r,$F as _t,qB as a,bh as aa,Eg as ai,Yj as an,Sc as ao,$D as ar,dL as at,IR as b,ch as ba,hm as bi,HA as bn,Oa as bo,Tb as br,WI as bt,WB as c,Vm as ca,F as ci,iM as cn,$u as co,qE as cr,fL as ct,BB as d,dh as da,Ph as di,Gj as dn,pc as do,LE as dr,hF as dt,Vp as ea,S_ as ei,eM as en,Dc as eo,XO as er,pR as et,vB as f,oh as fa,Um as fi,qj as fn,Us as fo,RE as fr,sF as ft,zR as g,Hm as ga,j as gi,Vj as gn,Lo as go,MT as gr,lF as gt,rB as h,sh as ha,$h as hi,tM as hn,ps as ho,NT as hr,TF as ht,GB as i,uh as ia,Tg as ii,Qj as in,wc as io,ED as ir,GF as it,YR as j,Eh as ja,Bh as ji,_A as jn,la as jo,Dy as jr,nP as jt,bz as k,gh as ka,Rh as ki,yA as kn,fa as ko,Fy as kr,qI as kt,HB as l,Wm as la,um as li,zj as ln,Qu as lo,KE as lr,JI as lt,wB as m,fh as ma,Qh as mi,Xj as mn,Ks as mo,EE as mr,wF as mt,YB as n,hh as na,Kg as ni,nM as nn,Tc as no,UO as nr,KL as nt,UB as o,jh as oa,xg as oi,Lj as on,jc as oo,xD as or,eL as ot,yB as p,V as pa,H as pi,rM as pn,Ws as po,ME as pr,$P as pt,TR as q,km as qa,Xp as qi,gk as qn,oy as qr,vM as qt,ZB as r,Ch as ra,Gg as ri,Hj as rn,Ac as ro,PO as rr,SP as rt,KB as s,Oh as sa,ig as si,Uj as sn,Zu as so,HE as sr,uF as st,XB as t,eh as ta,Yg as ti,Wj as tn,xc as to,WO as tr,LL as tt,VB as u,Zm as ua,cm as ui,Bj as un,Ou as uo,UE as ur,QI as ut,AR as v,Qm as va,rh as vi,Jj as vn,Da as vo,oT as vr,CF as vt,HR as w,Sh as wa,N as wi,vj as wn,_a as wo,Xy as wr,qF as wt,XR as x,$m as xa,Mh as xi,xj as xn,Ca as xo,yb as xr,SL as xt,BR as y,ph as ya,im as yi,Zj as yn,Aa as yo,vb as yr,bF as yt,_z as z,bm as za,jp as zi,Mk as zn,Zi as zo,vy as zr,kM as zt};
|