@fungi.computer/grove 0.16.1 → 0.17.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/{Effect-DeiDqvoz.js → Effect-pxRavrBh.js} +11 -11
- package/dist/assets/{anthropic-messages-DQiQ4Cgh.js → anthropic-messages-CkLFXbme.js} +3 -3
- package/dist/assets/{azure-openai-responses-BdsogfXX.js → azure-openai-responses-BjItkyTn.js} +1 -1
- package/dist/assets/{base-face-BYExcFAP.js → base-face-CsIbc1by.js} +1 -1
- package/dist/assets/burger-BgftDtiM.js +1 -0
- package/dist/assets/cat-CfNEurUg.js +1 -0
- package/dist/assets/{classifier-shared-BCGGOIh6.js → classifier-shared-JiMD88Sh.js} +1 -1
- package/dist/assets/{cloudflare-workers-ai-system-one-BjlnhHlD.js → cloudflare-workers-ai-system-one-tEpgPfLW.js} +1 -1
- package/dist/assets/compat-CxZajpXB.js +2 -0
- package/dist/assets/conversation-toast-DUFOMoQ9.js +33 -0
- package/dist/assets/{document-EWUYmKg3.js → document-BBvRlLC3.js} +1 -1
- package/dist/assets/{document-BiiUDQ73.js → document-Bpcy9TTA.js} +1 -1
- package/dist/assets/extension-hook-Da3ATgkY.js +890 -0
- package/dist/assets/extensions-D2Z9guoO.js +1 -0
- package/dist/assets/{google-generative-ai-DZR_Ze6f.js → google-generative-ai-DJB3dC5c.js} +1 -1
- package/dist/assets/{google-shared-BpSgfzOZ.js → google-shared-DVq-_IDX.js} +1 -1
- package/dist/assets/{google-vertex-ghIH-83b.js → google-vertex-CYm5wNps.js} +1 -1
- package/dist/assets/index-BaCEAFz2.js +117 -0
- package/dist/assets/index-CIiuRnlU.css +1 -0
- package/dist/assets/{mistral-conversations-Dz3sIOsn.js → mistral-conversations-DDg7eeLe.js} +1 -1
- package/dist/assets/{mushroom-CjQXC8r7.js → mushroom-FKArpulr.js} +1 -1
- package/dist/assets/{node.browser-Bg-Udc28.js → node.browser-CdLsHXpS.js} +1 -1
- package/dist/assets/{openai-codex-responses-CsLh-FB3.js → openai-codex-responses-H7WhI66H.js} +1 -1
- package/dist/assets/{openai-completions-F-1Tomjo.js → openai-completions-CkqQ2fFp.js} +1 -1
- package/dist/assets/{openai-decisions-BMWT3gOP.js → openai-decisions-DMV8tZy4.js} +1 -1
- package/dist/assets/{openai-responses-CZ6dqUTL.js → openai-responses-Csql8sEY.js} +1 -1
- package/dist/assets/{openai-responses-shared-Btjx9mL_.js → openai-responses-shared-DAZ5Qapp.js} +1 -1
- package/dist/assets/{openrouter-images-D5Uqwk0h.js → openrouter-images-DFWtFOvI.js} +1 -1
- package/dist/assets/parakeet-BUkzxkvS.js +35 -0
- package/dist/assets/parakeet-conversation-D8vRtIjX.js +4 -0
- package/dist/assets/{pi-messages-1JTpG1Us.js → pi-messages-DoPiztqV.js} +1 -1
- package/dist/assets/{renderer-DOUDAFcS.js → renderer-BVZdPJB6.js} +1 -1
- package/dist/assets/runtime-core-U8lOfyYX.js +40 -0
- package/dist/assets/{system-one-shared-qsmpMW29.js → system-one-shared-D7AS4c2W.js} +1 -1
- package/dist/assets/{transform-messages-AGWoIDpj.js → transform-messages-CCZNew0k.js} +1 -1
- package/dist/assets/{typesafe-system-one-D8FWi62S.js → typesafe-system-one-Cl52u7Mq.js} +1 -1
- package/dist/assets/{website-conversation-kQbo5VTI.js → website-conversation-CpPJ8N_o.js} +1 -1
- package/dist/index.html +9 -8
- package/package.json +9 -9
- package/dist/assets/burger-Bn2ocNTG.js +0 -1
- package/dist/assets/cat-x9tMcsRE.js +0 -1
- package/dist/assets/compat-CAkhM7lX.js +0 -2
- package/dist/assets/conversation-toast-BLAWHMmE.js +0 -32
- package/dist/assets/extension-hook-BEwrceUI.js +0 -869
- package/dist/assets/index-BaZH2cO3.js +0 -117
- package/dist/assets/index-ODpmGtEN.css +0 -1
- package/dist/assets/parakeet-Cq96KyZe.js +0 -36
- package/dist/assets/parakeet-conversation-m2Bl3XXj.js +0 -4
- package/dist/assets/runtime-core-DDK2YKwN.js +0 -40
|
@@ -0,0 +1,890 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-CxZajpXB.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-U8lOfyYX.js","assets/Effect-pxRavrBh.js","assets/extensions-D2Z9guoO.js","assets/index-BaCEAFz2.js","assets/conversation-toast-DUFOMoQ9.js","assets/document-BBvRlLC3.js","assets/document-Bpcy9TTA.js","assets/base-face-CsIbc1by.js","assets/index-CIiuRnlU.css","assets/estimate-DElUjJag.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{$i as e,$n as t,$r as n,$t as r,A as i,Ai as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as ee,Ct as te,D as ne,Da as re,Di as ie,Dn as ae,Dr as oe,Dt as se,E as ce,Ea as le,Ei as ue,En as de,Er as fe,Et as pe,Fi as me,Fn as he,Fr as ge,Ft as _e,G as ve,Gn as ye,Gr as be,Gt as xe,H as Se,Hr as Ce,Ht as we,I as Te,Ii as Ee,In as De,Ir as Oe,It as ke,J as Ae,Jn as je,Jr as Me,Jt as Ne,K as Pe,Kr as Fe,Kt as Ie,L as Le,Li as Re,Ln as ze,Lr as Be,Lt as Ve,M as He,Mi as Ue,Mn as We,Mr as Ge,Mt as Ke,N as qe,Ni as Je,Nn as Ye,Nr as Xe,Nt as Ze,O as Qe,Oi as $e,On as et,Or as tt,Ot as nt,P as rt,Pi as it,Pn as at,Pr as ot,Pt as st,Q as ct,Qi as lt,Qr as h,Qt as ut,R as dt,Rn as ft,Rr as pt,Rt as mt,S as ht,Sa as gt,Si as _t,Sn as vt,Sr as yt,St as bt,T as xt,Ta as St,Ti as Ct,Tn as wt,Tt,U as Et,Un as Dt,Ur as Ot,Ut as kt,V as At,Vn as jt,Vr as Mt,Vt as Nt,W as Pt,Wn as Ft,Wr as It,Wt as Lt,X 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 g,_i as Qt,_n as $t,_r as en,a as _,aa as tn,ai as nn,an as rn,ar as an,at as on,b as sn,ba as cn,bi as ln,bn as un,br as dn,bt as fn,c as pn,ca as mn,ci as hn,cn as gn,cr as _n,d as vn,da as yn,di as bn,dn as xn,dr as Sn,ea as Cn,en as wn,er as Tn,et as En,f as Dn,fa as v,fi as On,fn as kn,ft as An,g as y,ga as jn,gi as Mn,gn as Nn,gr as Pn,gt as Fn,h as In,ha as Ln,hi as Rn,hn as zn,hr as Bn,ht as Vn,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,la as er,li as tr,ln as nr,lo as rr,lt as ir,m as ar,ma as or,mi as sr,mn as cr,mt as lr,ni as ur,nn as dr,nt as fr,o as pr,oa as mr,oi as hr,on as gr,oo as _r,or as vr,ot as yr,p as br,pa as x,pi as xr,pn as Sr,pr as Cr,pt as S,q as wr,qr as C,qt as Tr,r as Er,ra as Dr,ri as Or,rn as kr,ro as Ar,rt as jr,s as Mr,sa as Nr,sn as Pr,sr as Fr,st as Ir,t as Lr,ta as Rr,ti as zr,tn as Br,tt as Vr,u as Hr,ua as Ur,ui as Wr,un as Gr,ur as Kr,ut as qr,v as Jr,vi as Yr,vn as Xr,vr as Zr,vt as Qr,w as $r,wa as ei,wi as ti,wn as ni,wr as ri,wt as ii,x as ai,xa as w,xi as oi,xn as si,xr as ci,xt as li,y as T,ya as ui,yi as di,yn as fi,yr as pi,yt as mi,z as hi,zr as gi,zt as _i}from"./Effect-pxRavrBh.js";import{c as vi,t as yi}from"./preload-helper-CfILh1TC.js";var bi=yn(),xi=v(()=>mn(`status`,[g({status:x(`available`)}).strict(),g({status:x(`unavailable`),reason:w()}).strict()])),Si=bi,Ci=v(()=>ui(w(),Si)),wi=e=>Si.parse(e),Ti=e=>Ci.parse(e),Ei=v(()=>g({code:w().min(1).max(160),message:w().min(1).max(512),details:Si.optional()}).strict()),Di=e=>Ei.parse(e),Oi=Ci,ki=v(()=>w().refine(e=>e.trim().length>0)),Ai=xi,ji=v(()=>ei([g({type:x(`action`)}).strict(),g({type:x(`custom`),data:Ci}).strict(),g({type:x(`choice`),options:Dr(g({value:Si,label:ki,description:ki.optional()}))}).strict(),g({type:x(`form`),submitLabel:ki.optional()}).strict(),g({type:x(`confirmation`),message:ki,confirmLabel:ki.optional(),cancelLabel:ki.optional()}).strict()])),Mi=v(()=>g({inputSchema:Oi.optional(),outputSchema:Oi.optional(),presentation:ji.optional()}).strict()),Ni=v(()=>jn().int().refine(e=>Number.isSafeInteger(e))),Pi=v(()=>g({hint:ki.pipe(w().max(120)),words:Dr(g({word:w().regex(/^\S{1,64}$/u),description:ki.pipe(w().max(512)).optional(),arguments:Ci}).strict()).max(32).optional(),text:g({field:ki.pipe(w().max(120)),arguments:Ci,requestIdField:ki.pipe(w().max(120)).optional()}).strict().optional()}).strict().refine(e=>e.words!==void 0||e.text!==void 0,`slash arguments need words or text`)),Fi=v(()=>g({order:Ni.optional()}).strict()),Ii=v(()=>g({bindings:g({order:Ni.optional(),values:Dr(ki).max(16)}).strict().optional(),agent:g({keybind:ki.optional(),order:Ni.optional()}).strict().optional(),help:Fi.optional(),menu:Fi.optional(),palette:Fi.optional(),slash:g({aliases:Dr(ki).max(16),consumesDraft:mr().optional(),order:Ni.optional(),arguments:Pi.optional()}).strict().optional()}).strict()),Li=v(()=>g({id:ki.refine(e=>!e.includes(`:`)),title:ki,category:ki,description:ki.optional(),projections:Ii.optional(),action:Mi.optional(),availability:Ai.optional()}).strict()),Ri=e=>Li.parse(e),zi=v(()=>g({inputSchema:Oi.optional(),outputSchema:Oi.optional()}).strict()),Bi=w().min(1).brand(),Vi=v(()=>g({commandId:Bi,command:g({namespace:w(),id:w()}).strict(),sourceId:w(),scope:w().optional(),title:w(),category:w(),description:w().optional(),order:jn(),availability:xi,action:zi.optional(),keybind:w().optional()}).strict());Dr(Vi);var Hi=8192,Ui=ki.pipe(w().max(Hi)),Wi=ki.pipe(w().max(60)),Gi=le({protocol:/^https?$/u}),Ki=g({label:Ui,value:Ui}).strict(),qi={summary:Ui.optional(),facts:Dr(Ki).max(4).optional(),body:Ui.optional(),bodyLabel:Ui.optional(),details:Dr(Ki).max(24).optional()},Ji=mn(`type`,[g({type:x(`choice`),message:Wi,...qi,current:Ui.optional(),collapsedGroup:Ui.optional(),options:Dr(g({value:Ui,label:Ui,description:Ui.optional(),group:Ui.optional(),destructive:x(!0).optional()}).strict()).min(1).max(256)}).strict(),g({type:x(`text`),message:Wi,...qi,placeholder:Ui.optional(),secret:mr().optional()}).strict(),g({type:x(`confirmation`),message:Wi,...qi,confirmLabel:Ui.optional(),cancelLabel:Ui.optional(),destructive:x(!0).optional()}).strict(),g({type:x(`decision`),message:Wi,...qi,options:Dr(g({value:Ui,label:Ui,description:Ui.optional(),destructive:x(!0).optional()}).strict()).min(1).max(8).refine(e=>new Set(e.map(e=>e.value)).size===e.length,`Decision option values must be unique`),multiple:mr().optional(),other:g({label:Ui,placeholder:Ui.optional(),maxLength:jn().int().min(1).max(Hi),blank:Ui.optional()}).strict().optional(),escape:Ui.optional()}).strict().refine(e=>[e.escape,e.other?.blank].every(t=>t===void 0||e.options.some(e=>e.value===t)),`A decision's escape and blank answers must be offered options`)]),Yi=v(()=>mn(`type`,[g({type:x(`info`),message:Ui,links:Dr(g({url:Gi,label:Ui.optional()}).strict()).max(16).optional()}).strict(),g({type:x(`progress`),message:Ui}).strict(),g({type:x(`handoff`),url:Gi,code:Ui.optional(),message:Ui.optional()}).strict(),g({type:x(`success`),message:Ui}).strict()])),Xi=e=>Ji.parse(e),Zi=e=>Yi.parse(e),Qi={decision:e=>{let t=Ji.options[3].parse(e),n=new Set(t.options.map(e=>e.value));return g({selected:Dr(w()).max(t.options.length),text:er(ki.pipe(w().max(t.other?.maxLength??1)))}).strict().superRefine((e,r)=>{let i=e=>{r.addIssue({code:`custom`,message:e})};(e.selected.some(e=>!n.has(e))||new Set(e.selected).size!==e.selected.length)&&i(`Pick each offered option at most once`),t.multiple!==!0&&e.selected.length>1&&i(`Pick one option`),e.selected.length===0&&e.text===void 0&&i(`Pick an option or write an answer`),t.other===void 0&&e.text!==void 0&&i(`This decision takes no written answer`),t.multiple!==!0&&e.selected.length>0&&e.text!==void 0&&i(`Pick an option or write an answer, not both`)})},confirmation:e=>(Ji.options[2].parse(e),mr()),text:e=>(Ji.options[1].parse(e),w().max(Hi)),choice:e=>{let t=Ji.options[0].parse(e);return w().refine(e=>t.options.some(t=>t.value===e))}};function $i(e){let t=Qi[e.type](e);return e=>{let n=t.safeParse(e);return n.success?{kind:`accepted`,value:n.data}:{kind:`invalid`,cause:n.error}}}var ea=e=>e>0?Math.floor(e):0,ta=e=>Math.max(1,ea(e)),na=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},ra=`~effect/BigDecimal`,ia={[ra]:ra,[On](){let e=fa(this);return hn(bn(String(e.value)),Wr(e.scale))},[hr](e){return aa(e)&&_a(this,e)===0},toString(){return`BigDecimal(${ya(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Fe](){return this.toJSON()},pipe(){return Re(this,arguments)}},aa=e=>xr(e,ra),oa=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(ia);return n.value=e,n.scale=t,n},sa=(e,t)=>{let n=oa(e,t);return n.normalized=n,n},ca=BigInt(0),la=BigInt(1),ua=BigInt(10),da=sa(ca,0),fa=e=>{if(e.normalized===void 0){if(e.value===ca)e.normalized=da;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=sa(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},pa=100,ma=[la],ha=(e,t)=>e===t?0:e<t?-1:1,ga=(e,t)=>{let n=`${e.value<ca?-e.value:e.value}`,r=`${t.value<ca?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==ca)return i<ca?-1:1;let a=Math.max(n.length,r.length);return Zr(n.padEnd(a,`0`),r.padEnd(a,`0`))},_a=(e,t)=>{if(e.scale===t.scale)return ha(e.value,t.value);let n=va(e),r=va(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>pa)return n===-1?ga(t,e):ga(e,t);let o=ma[a]??=ua**BigInt(a);return i>0?ha(e.value,t.value*o):ha(e.value*o,t.value)},va=e=>e.value===ca?0:e.value<ca?-1:1,ya=e=>{let t=fa(e);if(Math.abs(t.scale)>=16)return ba(t);let n=t.value<ca,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},ba=e=>{if(xa(e))return`0e+0`;let t=fa(e),n=`${t.value}`,r=t.value<ca?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},xa=e=>e.value===ca,Sa=oe,Ca=`~effect/encoding/EncodingError`,wa=class extends Sa(`EncodingError`){[Ca]=Ca},Ta=d,Ea=qn,Da=s,Oa=Zn,ka=kr,Aa=Ze,ja=_e,Ma=ut,Na=r,Pa=Xt,Fa=dr,Ia=st,La=pt,Ra=Ge,za=nt;Ye()(`effect/Cause/StackTrace`),Ye()(`effect/Cause/InterruptorStackTrace`);var Ba=Be,Va=Oe,Ha=ge,Ua=ot,Wa=xe,Ga=we,Ka=Nt,qa=Lt,Ja=kt,Ya=_i,Xa={"~effect/Deferred":{_A:Ue,_E:Ue},pipe(){return Re(this,arguments)}},Za=function(){this.resumes=void 0,this.effect=void 0};Za.prototype=Xa;var Qa=()=>new Za,$a=()=>vt(()=>Qa()),eo=e=>Jn(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),vt(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),to=a(2,(e,t)=>vt(()=>io(e,t))),no=a(2,(e,t)=>to(e,ge(t))),ro=a(2,(e,t)=>to(e,Be(t))),io=(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},ao=Xr,oo=Nn,so=$t,co=nr,lo=kn,uo=xn,fo=cr,po=zn,mo=Sr,ho=se,go=Ve,_o=`~effect/DateTime`,vo=`~effect/DateTime/TimeZone`,yo={[_o]:_o,pipe(){return Re(this,arguments)},[Fe](){return this.toString()},toJSON(){return Ao(this).toJSON()}},bo={...yo,_tag:`Utc`,[On](){return Wr(this.epochMilliseconds)},[hr](e){return So(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ao(this).toJSON()})`}};({...yo});var xo={[vo]:vo,[Fe](){return this.toString()}};({...xo}),{...xo};var So=e=>xr(e,_o),Co=e=>e._tag===`Utc`,wo=e=>{let t=Object.create(bo);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},To=e=>{let t=e.getTime();if(Number.isNaN(t))throw new za(`Invalid date`);return wo(t)},Eo=e=>{if(So(e))return e;if(e instanceof Date)return To(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return To(new Date(e.epochMilliseconds));let t=new Date(0);return jo(t,e),To(t)}return typeof e==`string`&&!Do(e)?To(new Date(e+`Z`)):To(new Date(e))},Do=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Oo=_n(Eo),ko=e=>wo(e.epochMilliseconds),Ao=e=>new Date(e.epochMilliseconds),jo=(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)},Mo=e=>Ao(e).toISOString();globalThis.Number;var No=a(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]=Po(e),[i,a]=Po(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 Po(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 Fo=e=>e.trim(),Io=a(2,(e,t)=>Ke(e,Bo,e=>t(e))),Lo=e=>e.reasons.some(Ro),Ro=e=>e._tag===`Fail`&&La(e.error),zo=e=>{let n,r=!1;for(let t of e.reasons)Ro(t)?n??=t.error:t._tag!==`Interrupt`&&(r=!0);return n===void 0?ye(e):r?ye(Ea(e.reasons.filter(e=>!Ro(e)))):t(n)},Bo=e=>{let n=zo(e);return je(n)?n:t(n.success.value)},Vo=e=>{let t=zo(e);return je(t)?Va(t.failure):Ba(t.success.value)},Ho=We(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),Uo=We(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),Wo=`~effect/Metric`,Go=class{[Wo]=Wo;#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=De(e,Ho);t!==this.#e&&(this.#e=t,this.#t=Qo(this,es(this.attributes,t)));let n=De(e,Uo),r=n.get(this.#t);return ue(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?es(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return Re(this,arguments)}},Ko=BigInt(0),qo=class extends Go{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,ts(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?Ko:0,t=this.#t?this.#e?e=>e>=Ko:e=>e>=0:e=>!0;return $o(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},Jo=class extends Go{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()}},Yo=(e,t)=>new qo(e,t),Xo=a(2,(e,t)=>ke(n=>vt(()=>e.updateUnsafe(t,n)))),Zo=a(2,(e,t)=>{let n=ns(t);return new Jo(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function Qo(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 $o(e,t,n){return{get:e,update:t,modify:n??t}}function es(e,t){return{...ts(e),...ts(t)}}function ts(e){return di(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(h(e,t,n),e),{}):e}function ns(e){let t,n={};return r=>{let i=De(r,Ho);return i!==t&&(t=i,n=es(i,e)),at(r,Ho,n)}}var rs=So,is=Co,as=Eo,os=Oo,ss=ko;Ye()(`effect/DateTime/CurrentTimeZone`);var cs=Mo,ls=e=>ds(typeof e==`string`?fs.encode(e):e),us=e=>{let n=ps(e),r=n.length;if(r%4!=0)return ye(new wa({kind:`Decode`,module:`Base64`,input:n,message:`Length must be a multiple of 4, but is ${r}`}));let i=n.indexOf(`=`);if(i!==-1&&(i<r-2||i===r-2&&n[r-1]!==`=`))return ye(new wa({kind:`Decode`,module:`Base64`,input:n,message:`Found a '=' character, but it is not at the end`}));try{let e=n.endsWith(`==`)?2:+!!n.endsWith(`=`),i=new Uint8Array(r/4*3-e);for(let e=0,t=0;e<r;e+=4,t+=3){let r=gs(n.charCodeAt(e))<<18|gs(n.charCodeAt(e+1))<<12|gs(n.charCodeAt(e+2))<<6|gs(n.charCodeAt(e+3));i[t]=r>>16,i[t+1]=r>>8&255,i[t+2]=r&255}return t(i)}catch(e){return ye(new wa({kind:`Decode`,module:`Base64`,input:n,message:e instanceof Error?e.message:`Invalid input`}))}},ds=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=ms[e[r-2]>>2],n+=ms[(e[r-2]&3)<<4|e[r-1]>>4],n+=ms[(e[r-1]&15)<<2|e[r]>>6],n+=ms[e[r]&63];return r===t+1&&(n+=ms[e[r-2]>>2],n+=ms[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=ms[e[r-2]>>2],n+=ms[(e[r-2]&3)<<4|e[r-1]>>4],n+=ms[(e[r-1]&15)<<2],n+=`=`),n},fs=new TextEncoder,ps=e=>e.replace(/[\n\r]/g,``),ms=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,hs=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)hs[ms.charCodeAt(e)]=e;hs[61]=0;var gs=e=>{if(e>=hs.length||hs[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return hs[e]};Sa(`CookiesError`),{...be},{...be};var _s=new WeakMap,vs=`~effect/Redacted`,ys=e=>xr(e,vs),bs=(e,t)=>{let n=Object.create(xs);return t?.label&&(n.label=t.label),_s.set(n,e),n},xs={[vs]:{_A:e=>e},label:void 0,...fe,toJSON(){return this.toString()},toString(){return`<redacted${ti(this.label)?`:`+this.label:``}>`},[On](){return tr(_s.get(this))},[hr](e){return ys(e)&&Or(_s.get(this),_s.get(e))}};({...fe});function Ss(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Cs(e){return t=>Ss(t)?.[e]}var ws=`~structural`,Ts=`~identifier`,Es=`~sentinels`,Ds=`~constructor`,Os=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],ks=Cs(`identifier`),As=Cs(Ts),js=Cs(`title`),Ms=Cs(`description`),Ns=Je(e=>{let t=Ss(e)?.identifier;return typeof t==`string`?t:e.getExpected(Ns)}),Ps=new Set([Es,ws,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),E=Symbol(),Fs=Ba,Is=Fs(E),Ls=Fs(E),Rs=e=>e===E?Sn():Cr(e),zs=e=>e._tag===`None`?Is:Fs(e.value),Bs=`~effect/SchemaIssue/Issue`;function Vs(e){return xr(e,Bs)&&e[Bs]===Bs}function Hs(e){return Object.hasOwn(e,`input`)}var Us=class{[Bs]=Bs;constructor(e,t){t?.reportInput===!0&&e!==E&&(this.input=e)}},Ws=class extends Us{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},Gs=class extends Us{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},Ks=class extends Us{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},qs=class extends Us{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},Js=class extends Us{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Ys=class extends Us{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Xs=class extends Us{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Zs=class extends Us{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},Qs=class extends Us{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},$s=class extends Us{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ec=class extends Us{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function tc(e,t,n){if(Vs(e))return e;if(typeof e==`string`)return new Zs({message:e},t,n);let r=typeof e.issue==`string`?new Zs({message:e.issue},t,n):e.issue;return new Ks(e.path,r)}function nc(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new Zs(void 0,t,n):tc(e,t,n)}function rc(e,t,n,r){return Array.isArray(t)?jt(t)?t.length===1?tc(t[0],n,r):new Ys(e,Dt(t,e=>tc(e,n,r)),n,r):void 0:nc(t,n,r)}var ic=e=>{let t=hc(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return lc(Ns(e.ast),e);case`InvalidValue`:{let t=cc(e);if(t!==void 0)return lc(t,e);let n=sc(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=sc(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=sc(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},ac=e=>hc(e.issue)??hc(e);function oc(e){return t=>({issues:uc(t,[],e?.leafHook??ic,e?.checkHook??ac)})}function sc(e){return Hs(e)?C(e.input):void 0}function cc(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function lc(e,t){let n=sc(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function uc(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 uc(e.issue,t,n,r);let a=cc(e.issue);return[{path:t,message:a===void 0?lc(dc(e.filter),e):lc(a,e.issue)}]}case`Encoding`:return uc(e.issue,t,n,r);case`Pointer`:return uc(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>uc(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:hc(e)??lc(Ns(e.ast),e)}]:e.issues.flatMap(e=>uc(e,t,n,r));default:return[{path:t,message:n(e)}]}}function dc(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=>dc(e)).join(` & `)}}function fc(){return e=>mc(e,``)}var pc=fc();function mc(e,t){let n;switch(e._tag){case`Filter`:{let r=ac(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return mc(e.issue,t);let r=cc(e.issue);n=r===void 0?lc(dc(e.filter),e):lc(r,e.issue)}break}case`Encoding`:return mc(e.issue,t);case`Pointer`:return mc(e.issue,t+Gt(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>mc(e,t)).join(`
|
|
3
|
+
`);n=hc(e)??lc(Ns(e.ast),e);break;default:n=ic(e)}return t?`${n}\n at ${t}`:n}function hc(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return hc(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 gc(e){let t;for(let n of e.reasons){if(!Ta(n)||!Vs(n.error))return;t??=n.error}return t}function _c(e,t){let n=gc(e);if(n===void 0)throw Error(t,{cause:e});return n}var vc=e=>ls(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),yc=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return ye(new wa({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 ye(new wa({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,`/`),us(r)},bc=e=>Object.assign(Object.create(Ee),e);function xc(e){return Ac((t,n)=>y(e(t,n)))}function Sc(e){return xc((t,n)=>{let r={message:e(t)};return Fr(t)?new Qs(r,t.value,n):new Qs(r)})}var Cc=Sc(()=>`Encoding is not supported`),wc=bc({_tag:`Passthrough`});function Tc(){return wc}function Ec(){return wc}function Dc(e){return bc({_tag:`Transform`,transform:e})}function Oc(e){return bc({_tag:`TransformEffect`,transform:e})}function kc(e){return bc({_tag:`TransformOptional`,transform:e})}function Ac(e){return bc({_tag:`TransformOptionalEffect`,transform:e})}function jc(){return kc(()=>Sn())}function Mc(e){return Ac(t=>{let n=Tn(t,di);return Fr(n)?S(n):Le(e,Cr)})}function Nc(){return Dc(globalThis.String)}function Pc(){return Dc(globalThis.Number)}function Fc(){return Dc(globalThis.BigInt)}function Ic(){return Dc(e=>new globalThis.Date(e))}function Lc(){return Dc(Fo)}function Rc(e){return Oc((t,n)=>li({try:()=>JSON.parse(t,e?.reviver),catch:()=>new Zs({expected:`a valid JSON string`},t,n)}))}function zc(e){return Oc((t,n)=>li({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 Zs({expected:`a JSON-serializable value`},t,n)}))}function Bc(){return Dc(ls)}function Vc(){return Oc((e,t)=>hi(i(us(e)),()=>new Zs({expected:`a valid Base64 string`},e,t)))}var Hc=class extends me{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Hc(this.encode,this.decode)}},Uc=`~effect/SchemaTransformation/Transformation`,Wc=class extends me{[Uc]=Uc;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new Wc(this.encode,this.decode)}};function Gc(e){return xr(e,Uc)&&e[Uc]===Uc}var Kc=e=>Gc(e)?e:new Wc(e.decode,e.encode);function qc(e){return new Wc(Oc(e.decode),Oc(e.encode))}function Jc(){return new Wc(Lc(),Tc())}var Yc=new Wc(Tc(),Tc());function Xc(){return Yc}var Zc=new Wc(Pc(),Nc()),Qc=new Wc(Fc(),Nc()),$c=new Wc(Ic(),Dc(Me)),el=new Wc(Vc(),Bc());function tl(e){return new Wc(Rc(e??{}),zc(e))}function nl(e){return t=>t._tag===e}var rl=nl(`Declaration`),il=nl(`Null`),al=nl(`Undefined`),ol=nl(`Never`),sl=nl(`String`),cl=nl(`Number`),ll=nl(`Boolean`),ul=nl(`Literal`),dl=nl(`UniqueSymbol`),fl=nl(`Arrays`),pl=nl(`Objects`),ml=nl(`Union`),hl=nl(`Suspend`),gl=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},_l={},vl=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}},yl=`~effect/Schema`,bl=class{[yl]=yl;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}>`}},xl=class extends bl{_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?Is:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=Ju(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new xl(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>`}},Sl=new class extends bl{_tag=`Null`;getParser(){return hd(this,null)}getExpected(){return`null`}},Cl=class extends bl{_tag=`Undefined`;getParser(){return hd(this,void 0)}toCodecJson(){return Iu(this,[wl])}getExpected(){return`undefined`}},wl=new gl(Sl,new Wc(Dc(()=>void 0),Dc(()=>null))),Tl=new Cl,El=new class extends bl{_tag=`Never`;getParser(){return gd(this,Qt)}getExpected(){return`never`}},Dl=new class extends bl{_tag=`Unknown`;getParser(){return gd(this,ie)}getExpected(){return`unknown`}},Ol=class extends bl{_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 ${C(e)}`);this.literal=e}getParser(){return hd(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?kl(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:kl(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function kl(e){let t=globalThis.String(e.literal);return Iu(e,[new gl(new Ol(t),new Wc(Dc(()=>e.literal),Dc(()=>t)))])}var Al=new class extends bl{_tag=`String`;getParser(){return gd(this,ti)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Md(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},jl=class extends bl{_tag=`Number`;getParser(){return gd(this,ln)}matchKey(e,t){return this._match(xd,e,t)}matchPart(e,t){return this._match(bd,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Md(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Ml(this.checks,`effect/schema/isFinite`)||Ml(this.checks,`effect/schema/isInt`))?this:Iu(this,[ju])}toCodecStringTree(){return this.toCodecJson()===this?Iu(this,[wd]):Iu(this,[Td])}getExpected(){return`number`}};function Ml(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Ml(e.checks,t))}var Nl=new jl,Pl=new class extends bl{_tag=`Boolean`;getParser(){return gd(this,Rn)}getExpected(){return`boolean`}},Fl=new class extends bl{_tag=`Symbol`;getParser(){return gd(this,Ct)}matchKey(e,t){return t.disableChecks||!this.checks?e:Md(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return Iu(this,[Ad])}getExpected(){return`symbol`}},Il=new class extends bl{_tag=`BigInt`;getParser(){return gd(this,sr)}matchPart(e,t){if(!Ed.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Md(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return Iu(this,[Od])}getExpected(){return`bigint`}},Ll=class extends bl{_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(ad(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(ad(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 Js(n,t[o],i),a=new Ks([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return y(new Ys(n,[a],t,i))}return e.issues?y(new Ys(n,e.issues,t,i)):Fs(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:Gr(t.concurrency),f=d===1?Bl(i,e,0,u):Vl(i,e,{concurrency:d,end:u});if(!f)return c(i);if(mt(f))return sn(f,()=>c(i));let p=!0;return lr(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===E)return Is;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)):y(new Xs(n,e,a))}catch(e){return br(e)}}}_rebuild(e,t,n){let r=Ju(this.elements,e),i=Ju(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Ll(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 Rl(e,t,n,r){if(n._tag===`Failure`)return Hl(e,e.ast,r,n);let i=n===Ls?t:n[tt];if(i!==E)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(ad(t.ast))return;let n=new Ks([r],new qs(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Ha(new Ys(e.ast,[n],e.input,e.options))}}var zl={onItem(e,t,n){let r=n<e.len?t:E;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Rl},Bl=rn()(zl),Vl=Wn()(zl),Hl=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=gc(r.cause);if(i===void 0)return Va(Aa(r.cause,r=>new Ys(t,[new Ks([n],r)],e.input,e.options)));let a=new Ks([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Ha(new Ys(t,[a],e.input,e.options))},Ul=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function Wl(e,t,n=_l){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(_d(dd(t)))}var Gl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function Kl(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(Kl);default:return!1}}function ql(e){let t=Ru(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ql);default:return!1}}function Jl(e){return Kl(e)&&ql(e)}var Yl=class{parameter;type;constructor(e,t){if(!Jl(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,ad(t)&&!md(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Xl=class extends bl{_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 gd(n,Yr);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(_d(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 Hl(t,n,i,s)??Wa;let c=s===Ls?o:s[tt];if(a!==E&&c!==E){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Wa;h(t.out,a,c)}return Wa},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!mt(t))return T(In(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return Hl(e,n,r,a)??Wa;let o=a===Ls?r:a[tt],s=e.input[r],l=i.parserValue(s,e.options);return mt(l)?t(e,r,o,s,l):T(In(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return mt(a)?t(e,n,n,i,a):T(In(a),r=>t(e,n,n,i,r))},u=i?Wn()({onItem:(e,[t,n])=>n.is.parameter===Al?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return p(function*(t,d){if(t===E)return E;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*y(new Xs(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:Gr(d.concurrency),re=i&&te?n.indexSignatures.map(e=>Wl(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 Js(n,f[a],d),r=new Ks([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*y(new Ys(n,[r],t,d))}}}if(r){let e=ne===1?$l(m,a):eu(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===Al?l:c,r=re?.[e]??(t.is.parameter===Al?Object.keys(f):Wl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!mt(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=ft();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===Al?Object.keys(f):Wl(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*y(new Ys(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(In(n),n=>{let i=Zl(e,r,n);if(i)return i;let o=()=>Fs(e.out),s=$l(e,a.slice(t+1));return s?sn(s,o):o()})};return(e,t)=>{if(e===E)return Is;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Gr(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return y(new Xs(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=pu(i,s),l=c?i[s]:E,d=n.parser(l,t);if(!mt(d))return u(o,e,d);if(d===Ls){c&&h(a,s,l);continue}let f=Zl(o,n,d);if(f)return f}}catch(e){return br(e)}return Fs(a)}}_rebuild(e,t,n,r){let i=Ju(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new Gl(t.name,n)}),a=Ju(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Yl(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Xl(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 Zl(e,t,n){if(n._tag===`Failure`)return Hl(e,e.ast,t.name,n);if(n===Ls)return;let r=n[tt];if(r!==E){h(e.out,t.name,r);return}if(delete e.out[t.name],!ad(t.type)){let n=new Ks([t.name],new qs(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Ha(new Ys(e.ast,[n],e.input,e.options))}}var Ql={onItem(e,t){if(!pu(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:Zl},$l=rn()(Ql),eu=Wn()(Ql);function tu(e,t){return e?t?[...e,...t]:e:t}function nu(e,t,n){return new Xl(Reflect.ownKeys(e).map(t=>new Gl(t,e[t].ast)),[],n,t)}function ru(e){return e.ast}function iu(e,t=void 0){return new Ll(!1,e.map(e=>e.ast),[],void 0,t)}function au(e,t,n){return new hu(e.map(ru),t,void 0,n)}function ou(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new Ll(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var su=it(e=>{for(;;){if(hl(e))return Dl;let t=e.encoding;if(!t)return e.recur?.(su,Ue)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==Ue))return Dl;e=t[t.length-1].to}});function cu(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(cu)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function lu(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Es];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!ad(t)){if(ul(t))return[{key:e.name,literal:t.literal}];if(dl(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!ad(e)){if(ul(e))return[{key:t,literal:e.literal}];if(dl(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>lu(su(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return lu(e.thunk())}}var uu=new WeakMap,du=Object.freeze([]),fu=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,pu=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function mu(e){let t=uu.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=su(c);if(ol(l))continue;if(ul(l)||dl(l)){a??=new Map;let e=ul(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=lu(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=cu(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??du);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??du;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(_t(e)){let n=pu(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??du;if(t)return o}return du}}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=fu(t);if(!_t(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=pu(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=pu(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=pu(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(fu(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return uu.set(e,t),t}var hu=class extends bl{_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 Is;let i=(o??=mu(n.types))(e,r);if(i.length===0)return y(new $s(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:mt(r)?gu(n,r.cause,e,t):_u(n,r,e,t)}return vu(n,a,i,e,t)}}_rebuild(e,t,n){let r=Ju(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new hu(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=dd(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(ul);if(t.length>0)return`${Su(n.isMutable)}[ ${t.map(t=>e(t)+Cu(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>ul(e.type));if(t.length>0)return`{ ${t.map(t=>`${Su(t.type.context?.isMutable)}${Bt(t.name)}${Cu(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function gu(e,t,n,r){let i=gc(t);return i?Ha(new $s(e,[i],n,r)):Va(t)}function _u(e,t,n,r){return Hr(t,t=>gu(e,t,n,r))}function vu(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=bu(a,n);if(!o)return a.out?a.out:y(new $s(e,a.issues??[],r,i));if(mt(o))return yu(o,a);let s=!0;return lr(()=>s?(s=!1,yu(o,a)):vu(e,t,n,r,i))}function yu(e,t){return sn(e,e=>t.out===Ls?S(t.input):t.out?t.out:y(new $s(t.ast,t.issues??[],t.input,t.options)))}var bu=rn()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=gc(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]),Ha(new ec(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Wa}}}),xu=new hu([new Ol(`Infinity`),new Ol(`-Infinity`),new Ol(`NaN`)]);function Su(e){return e?``:`readonly `}function Cu(e){return e?`?`:``}var wu=class extends bl{_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 wu(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Tu=class extends me{_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 Tu(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Tu(this.run,this.annotations,!0)}and(e,t){return new Eu([this,e],t)}},Eu=class extends me{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Eu(this.checks,{...this.annotations,...e})}and(e,t){return new Eu([this,e],t)}};function Du(e,t,n=!1){return new Tu((t,n,r)=>rc(n,e(t,n,r),t,r),t,n)}function Ou(e,t){return new Tu((t,n,r)=>e(t)?void 0:new Zs(void 0,t,r),t,!0)}function ku(e){return Du(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 Au=Vu(Nl,[ku()]),ju=new gl(new hu([Au,xu]),new Wc(Pc(),Dc(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Mu(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Du(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 Nu=new WeakMap;function Pu(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Nu.set(n,Fu(e)),n}function Fu(e){let t=Nu.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 Nu.set(e,n),n}function Iu(e,t){return e.encoding===t?e:Pu(e,{encoding:t})}function Lu(e,t){if(e.context===t)return e;let n=Fu(e);return n.context===t&&n.encoding===e.encoding?n:Pu(e,{context:t})}function Ru(e){return e.encoding?Ru(e.encoding[e.encoding.length-1].to):e}function zu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Bu(e,ze(e.checks.slice(0,-1),n.annotate(t)))}return Pu(e,{annotations:{...e.annotations,...t}})}function Bu(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Pu(e,{checks:t})}function Vu(e,t){return Bu(e,tu(e.checks,t))}function Hu(e,t){let n=t(e.to);return n===e.to?e:new gl(n,e.transformation)}function Uu(e,t){let n=e,r=n[n.length-1],i=Hu(r,t);return i===r?e:ze(e.slice(0,e.length-1),i)}function Wu(e){return t=>t.encoding?Iu(t,Uu(t.encoding,e)):t}function Gu(e,t){return Wu(e=>Lu(e,t))(e)}function Ku(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:Iu(r,Uu(r.encoding,n))}return e(r)}return it(n)}function qu(e,t,n){let r=new gl(e,t);return Iu(n,n.encoding?[...n.encoding,r]:[r])}function Ju(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 Yu(e,t){return Lu(e,e.context?new vl(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new vl(!1,!1,void 0,t))}var Xu=it(e=>Zu(Lu(e,e.context?e.context.isOptional===!1?new vl(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new vl(!0,!1)))),Zu=Wu(Xu),Qu=Je(e=>Xu(new hu([e,Tl]))),$u=it(e=>ed(Lu(e,e.context?e.context.isMutable===!1?new vl(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new vl(!1,!0)))),ed=Wu($u);function td(e,t){return Lu(e,e.context?new vl(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new vl(!1,!1,t))}function nd(e,t,n){return qu(e,n,t)}function rd(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:m(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 id(e,t){let{literals:n,parameters:r}=rd(e);return new Xl(n.map(e=>new Gl(e,t)),r.map(e=>new Yl(e,t)))}function ad(e){return e.context?.isOptional??!1}function od(e){return e.context?.isMutable??!1}function sd(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(sd)}function cd(e){function t(e){return sd(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return u(n)?n:void 0}function ld(e){let t=!0;function n(e){return t=t&&!e.encoding&&!hl(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var ud=it(e=>{let t=Fu(e);if(t!==e){let n=ud(t);return n===t&&e.encoding===void 0?e:Lu(n,e.context)}let n=`recur`in e?e.recur(ud):e;if(`encodingChecks`in n&&n.encodingChecks){let t=ld(e)?n.encodingChecks:fl(n)||pl(n)||rl(n)&&n.typeParameters.length>0?cd(n.encodingChecks):void 0;return Pu(n,{encodingChecks:void 0,checks:tu(n.checks,t)})}return n}),dd=it(e=>ud(pd(e)));function fd(e,t){let n=t,r=n.length,i=n[r-1],a=[new gl(pd(Iu(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new gl(pd(n[e-1].to),n[e].transformation.flip()));let o=pd(i.to);return o.encoding?Iu(o,[...o.encoding,...a]):Iu(o,a)}var pd=Je(e=>{if(e.encoding)return fd(e,e.encoding);let t=Fu(e);if(t!==e){let n=pd(t);return n===t?e:Lu(n,e.context)}return`flip`in e?e.flip(pd):`recur`in e?e.recur(pd):e});function md(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(md);default:return!1}}function hd(e,t){let n=t===0?Ls:Fs(t);return(r,i)=>r===E?Is:r===t?n:y(new Xs(e,r,i))}function gd(e,t){return(n,r)=>n===E?Is:t(n)?Ls:y(new Xs(e,n,r))}var _d=Ku(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(_d)}}),vd=Ku(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(vd)}}),yd=`[\\s\\S]*?`,bd=new globalThis.RegExp(`^${Ul}$`),xd=new globalThis.RegExp(`^(?:${Ul}|Infinity|-Infinity|NaN)$`);function Sd(e){return Mu(bd,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:bd.source}),...e})}var Cd=Vu(Al,[Sd()]),wd=new gl(Cd,Zc),Td=new gl(new hu([Cd,xu]),Zc),Ed=new globalThis.RegExp(`^-?\\d+$`);function Dd(e){return Mu(Ed,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Ed.source}),...e})}var Od=new gl(Vu(Al,[Dd({expected:`a string representing a bigint`})]),Qc),kd=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),Ad=new gl(Vu(Al,[jd()]),new Wc(Dc(e=>globalThis.Symbol.for(kd.exec(e)[1])),Oc((e,t)=>globalThis.Symbol.keyFor(e)===void 0?y(new Qs({message:`cannot serialize to string, Symbol is not registered`},e,t)):S(globalThis.String(e)))));function jd(e){return Mu(kd,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:kd.source}),...e})}function Md(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Md(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 Ws(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Nd(e){if(!rl(e))return;let t=e.annotations?.[Ds];return Mn(t)?t(e.typeParameters):void 0}var Pd=Ss,Fd=js,Id=Ms;function Ld(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function Rd(e){return e===void 0||typeof e==`string`}function zd(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 Bd(e){return zd(e,Ld)}var Vd=new xl([],()=>(e,t,n)=>Bd(e)?Ls:y(new Xs(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>Gd}),Hd=new gl(Vd,Xc()),Ud=new gl(new hu([new Ll(!1,[],[Vd]),new Xl([],[new Yl(Al,Vd)])]),Xc());function Wd(e){return zd(e,Rd)}var Gd=new gl(new xl([],()=>(e,t,n)=>Wd(e)?Ls:y(new Xs(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),Xc()),Kd=(e,t,n)=>e===Ls?n(t):sn(e,n);function qd(e){if(e._tag===`Middleware`)return(t,n,r)=>Jd(t===Ls?e.decode(Fs(Rs(n)),r):e.decode(Le(t,Rs),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===Ls?Fs(t):e;case`Transform`:{let e=e=>e===E?Is:Fs(t.transform(e));return(t,n)=>Kd(t,n,e)}case`TransformOptional`:{let e=e=>zs(t.transform(Rs(e)));return(t,n)=>Kd(t,n,e)}case`TransformEffect`:return(e,n,r)=>Kd(e,n,e=>e===E?Is:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>Kd(e,n,e=>Jd(t.transform(Rs(e),r)))}}var Jd=e=>sn(e,zs),Yd=(e,t,n,r)=>Hr(r,r=>Jr(()=>Aa(r,r=>new Gs(e,r,t,n))));function Xd(e,t){let n=qd(e.link.transformation),r;return(i,a)=>{if(i===E)return Is;if(e.isConstructed(i))return Ls;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function Zd(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==E&&r!==void 0)return t(r,i);let a=n;if(mt(a)&&a._tag===`Success`){let e=t(a[tt],i);return e===Ls?a:e}return sn(Yd(e,r,i,a),e=>{let n=t(e,i);return n===Ls?Fs(e):n})}}function Qd(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:Zd(e,n)}function $d(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Nd(e):void 0,o=a?Xd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>qd(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(mt(r)){if(r._tag===`Success`){let i=r===Ls?t:r[tt];if(t!==E&&i!==E){let i=Md(u,t,void 0,e,n);i&&(r=y(new Ys(e,i,t,n)))}}}else r=T(r,r=>{if(t!==E&&r!==E){let r=Md(u,t,void 0,e,n);if(r)return y(new Ys(e,r,t,n))}return S(r)})}if(s&&!n.disableChecks){if(mt(r)){if(r._tag===`Success`){let i=r===Ls?t:r[tt];if(i===E)return r;let a=Md(s,i,void 0,e,n);a&&(r=y(new Ys(e,a,i,n)))}}else r=T(r,t=>{if(t!==E){let r=Md(s,t,void 0,e,n);if(r)return y(new Ys(e,r,t,n))}return S(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[tt],o=t(a,r)):o=sn(o,e=>{let n=t(e,r);return n===Ls?Fs(e):n})}if(o._tag===`Success`){let e=o[tt],t=p(e,r);return t===Ls?o:t}return o=Yd(e,n,r,o),sn(o,e=>{let t=p(e,r);return t===Ls?Fs(e):t})}:p}var ef=Symbol(),tf=new WeakMap,nf=e=>sf(e).parser,rf=e=>sf(e).makeEffect,af=e=>Qd(e,rf),of=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=$d(this.ast,nf)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=$d(this.ast,rf,af)}};function sf(e){let t=tf.get(e);if(t!==void 0)return t;let n=new of(e);return tf.set(e,n),n}function cf(e){let t=e.ast,n;return(e,r)=>(n??=Tf(Mf,ud(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function lf(e){let t=cf(e);return(e,n)=>{let r=Ir(t(e,n));return Ga(r)?Cr(r.value):(_c(r.cause,`Option adapter can only return none for schema issues`),Sn())}}function uf(e){return Af(ud(e.ast))}function df(e){return pf(e.ast)}function ff(e){{let t=Ef(Cf(e));return e=>{let n=t(e,_l);return Ga(n)?!0:(_c(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function pf(e){let t=ud(e),n=e=>(n=ff(t),n(e));return e=>n(e)}function mf(e,t){let n=Cf(e.ast);return t===void 0?n:(e,r)=>n(e,xf(t,r))}function hf(e,t){return Ef(mf(e,t))}function gf(e,t){return Df(mf(e,t))}function _f(e,t){return Of(mf(e,t))}function vf(e,t){let n=Cf(pd(e.ast));return t===void 0?n:(e,r)=>n(e,xf(t,r))}function yf(e,t){return Ef(vf(e,t))}function bf(e,t){return Of(vf(e,t))}var xf=(e,t)=>t?{...e,...t}:e,Sf=e=>e===E?y(new Zs):S(e);function Cf(e){return Tf(jf,e)}function wf(e,t){return e===Ls?S(t):mt(e)?e[tt]===E?Sf(E):e:sn(e,Sf)}function Tf(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??_l);return a===Ls?S(r):mt(a)?a[tt]===E?Sf(E):a:sn(a,Sf)}}function Ef(e){return(t,n)=>Ir(e(t,n))}function Df(e){let t=Ef(e);return(e,n)=>{let r=t(e,n);return Ga(r)?Cr(r.value):(_c(r.cause,`Option adapter can only return none for schema issues`),Sn())}}function Of(e){let n=Ef(e);return(e,r)=>{let i=n(e,r);return Ga(i)?t(i.value):ye(_c(i.cause,`Result adapter can only return schema issues`))}}function kf(e,t){let n=Ir(e);if(Ga(n))return n.value;let r=_c(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Af(e){let t,n;return(r,i)=>{t??=sf(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??_l,o=t.make;if(o!==void 0&&r!==E){let e;try{e=o(r,a)}catch(e){throw _c(Oa(e),`Constructor adapter can only throw schema issues`),e}if(e!==ef&&e!==E)return e}return kf(wf((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var jf=e=>sf(e).parser,Mf=e=>sf(e).makeEffect,Nf=`~effect/Schema/Schema`,Pf=Symbol(),Ff={[Nf]:Nf,get make(){let e=uf(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=cf(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=lf(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Re(this,arguments)},annotate(e){return this.rebuild(zu(this.ast,e))},annotateKey(e){return this.rebuild(Yu(this.ast,e))},check(...e){return this.rebuild(Vu(this.ast,e))},rebuild(e){return If(e,this[Pf])}};function If(e,t){function n(){}let r=Object.setPrototypeOf(n,Ff);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[Pf]=t,r.ast=e,r}function Lf(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Rf(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function zf(e){return encodeURI(Lf(e)).replace(/#/g,`%23`)}function Bf(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 Vf(e){let t=Bf(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(Rf)}function Hf(e){return e.reduce((e,t)=>`${e}/${zf(t)}`,`#`)}var Uf=`http://json-schema.org/draft-07/schema#`;function Wf(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function Gf(e){return{dialect:`draft-07`,...rp(e,hp)}}function Kf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!oi(e))return e;let a=r||!i&&np(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=Yf(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 qf(e,t){return Kf(e,e=>{Jf(e,t)})}function Jf(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 Yf(e,t){if(!oi(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function Xf(e,t,n){let r=new Map,i=[],a=Zf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=$f(oi(e)?u(e):void 0,Zf)??Zf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=Qf(t,n);if(a!==void 0){let e=Vf(a.hash);if(a.hash=``,e!==void 0){let n=r.get(tp(a.href,e));n!==void 0&&(i=ep(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(!oi(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&np(c)){let e=$f(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 oi(e)?Yf(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(tp(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var Zf=`https://effect.invalid/.json-schema/`;function Qf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function $f(e,t){if(typeof e!=`string`)return;let n=Qf(e,t);if(n!==void 0)return n.hash=``,n.href}function ep(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${Hf(t)}`}function tp(e,t){return`${e}\u0000${JSON.stringify(t)}`}function np(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function rp(e,t,n){return Xf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:Yf(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var ip=new Set([`properties`,`patternProperties`]),ap=new Set([`allOf`,`anyOf`,`oneOf`]),op=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function sp(e,t,n,r,i,a=ip){let o;if(a.has(t))o=r.schemaMap(n,t);else if(ap.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 cp=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...cp],[...cp];var lp=/^[A-Za-z_][-A-Za-z0-9._]*$/,up=/^[A-Za-z][-A-Za-z0-9._:]*$/;function dp(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function fp(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&dp(i,n,`it is not active in ${r} but would become active in the target`)}var pp=[`additionalItems`,`definitions`,`dependencies`];function mp(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,Wf(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):Wf(t,`https://json-schema.org/draft/2020-12/schema`)||dp(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function hp(e,t){fp(e,pp,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!sp(n,o,s,t,op))switch(o){case`$ref`:r=s;break;case`$schema`:mp(n,s,t,Uf,`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`:dp(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(gp(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&dp(`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 vp(e,n,t,`draft-07`),bp(e,n,`$id`,`Draft-07`),_p(n,r,t),n}function gp(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 _p(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),yp(e,r)}else n.reference(e,t)}}function vp(e,t,n,r){let i=oi(e.dependentRequired)?e.dependentRequired:void 0,a=oi(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 yp(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function bp(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`||!lp.test(a))&&dp(`$anchor`,r,`the anchor is not valid`),up.test(a)||dp(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):dp(`$anchor`,r,`it cannot be combined with the schema $id`)}function xp(e){return If(Sp(e.ast),{schema:e})}var Sp=Ku(e=>{let t=Dp(e,Sp),n=e.context;return t===e||n===void 0?t:Gu(t,Cp(n))});function Cp(e){return e.constructorDefault===void 0?e:new vl(e.isOptional,e.isMutable,void 0,e.annotations)}function wp(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Tp(e){return t=>{let n=[...t].sort((t,n)=>e(dd(t))-e(dd(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Ep=Tp(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Dp(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Mn(n))return Iu(e,[Hd]);let r=n(e.typeParameters.map(e=>If(dd(e))));return r===void 0?e:Iu(e,[Hu(r,t)])}case`Unknown`:return Iu(e,[Hd]);case`ObjectKeyword`:return Iu(e,[Ud]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return wp(e),e.recur(t,vd);case`Union`:{let n=Ep(e.types);return n===e.types?e.recur(t):new hu(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 Op=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function kp(e,t){return t.length>0&&(e+=`\n at ${Gt(t)}`),Error(e)}function Ap(e){return`#/$defs/${zf(e)}`}var jp=new Set([...Ps,Ts,...Os]);function Mp(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;Bd(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&Bd(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(Bd(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))jp.has(r)||!t.includeAnnotationKey(r)||Bd(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function Np(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=Np(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 Pp(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 Fp=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function Ip(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function Lp(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var Rp=`|title|description|default|examples|readOnly|writeOnly|`,zp=Fp+Rp;function Bp(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=Pp(e);if(i!==void 0||a){let r=Np(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:Ip(r.schema,Rp)&&Lp(o,s)?{...o,...r.schema}:Bp(o,r.schema,n)}}if(n&&Lp(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 Vp(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>Vp(e,t)))}function Hp(e){return Array.isArray(e)}function Up(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=Dt(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!Vp(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=>Or(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Dt(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 kp(`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 qf(e,e=>{let t=Bf(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(Rf(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,Ap(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[Ts]: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=Hp(s);c&&i.push(!1);let l=c?s[0]:s,u=Mp(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Fp:zp;return[d,e._tag===`Filter`&&Ip(d,f)&&(u===void 0||Ip(u,Rp))?!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=Mp(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:Ap(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=Mp(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&Wp(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=Bp(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 kp(`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(Kp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw kp(`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=Mp(e.annotations,r);return s===void 0?o:p(Bp(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 kp(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=Mp(s.annotations,r);h(a,c,u===void 0?l:p(Bp(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);Or(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(Bp(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=Gp(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 kp(`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 Vp(n)&&r.type===`string`&&typeof r.pattern==`string`&&Ip(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(Kp).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 kp(`Invalid schema representation document`,t)}}}function Wp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function Gp(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 Kp(e){switch(e._tag){case`Literal`:return Op(globalThis.String(e.literal));case`String`:return yd;case`Number`:return Ul;case`TemplateLiteral`:return e.parts.map(Kp).join(``);case`Union`:return`(?:${e.types.map(Kp).join(`|`)})`;default:throw kp(`Invalid schema representation document`,[])}}function qp(e,t){let n=Up([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var Jp=({identifier:e})=>e;function Yp(e){return e===void 0?void 0:{annotations:e}}function Xp(e,t){let{references:n,representations:r}=Zp([e],t);return{representation:r[0],references:n}}function Zp(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??Jp;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:Dt(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:zu(e,{identifier:n}):As(e)===r?e:zu(e,{[Ts]: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=Ru(e),n=Fu(t),r=ks(t),i=r===void 0?(t===e?void 0:ks(e))??As(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(ud(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,...Yp(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...Yp(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...Yp(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...Yp(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...Yp(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=Ru(e),n=t.context?.annotations;return{isOptional:ad(t),type:m(e),...Yp(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...Yp(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=Ru(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:ad(t),isMutable:od(t),...Yp(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...Yp(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...Yp(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...Yp(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:Dt(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(ud(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function Qp(e){return Ga(e)?e.value:{issues:[{message:Ia(e.cause)}]}}function $p(e,t){let n=mf(e),r={errors:`all`,...t?.parseOptions},i=oc(t),a=e=>{let t=new wt(`sync`),a=fr(l(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?Qp(o):new Promise(e=>{a.addObserver(t=>{e(Qp(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 em(e){return qp(Xp(Sp(e)))}function tm(e,t){let n=em(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=Gf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function nm(e){let t={input(t){return tm(e.ast,t.target)},output(t){return tm(ud(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 rm=Je(e=>im(e));function im(e){let t=Ss(e)?.toEquivalence;if(t)return t(rl(e)?e.typeParameters.map(im):[]);switch(e._tag){case`Never`:return ur();case`Declaration`:return am(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 Or;case`Arrays`:{let t=e.elements.map(im),n=e.rest.map(im),[r,...i]=n,a=i.length;return zr((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 Or;let t=e.propertySignatures.map(e=>im(e.type)),n=e.indexSignatures.map(e=>im(e.type));return zr((r,i)=>{if(!oi(r)||!oi(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(ad(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=Wl(r,a.parameter),s=Wl(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=ud(e).types,n=mu(t),r=t.map((t,n)=>[pf(t),im(e.types[n])]);return zr((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 zr((n,r)=>(t??=rm(e.thunk()))(n,r))}}}function am(e){let t=e.annotations?.representation;if(t===void 0)return Or;switch(t.id){case`effect/schema/Option`:{let[t]=om(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=om(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]=om(e);return sm(t,n)}case`effect/schema/Cause`:{let[t,n]=om(e);return cm(t,n)}case`effect/schema/Exit`:{let[t,n,r]=om(e),i=cm(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]=om(e);return Un(t,n)}case`effect/schema/ReadonlySet`:return nn(om(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 Or}}function om(e){return e.typeParameters.map(im)}function sm(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 cm(e,t){let r=n(sm(e,t));return(e,t)=>r(e.reasons,t.reasons)}var lm=a(2,(e,t)=>({...e,...t})),um=e=>e,dm=`~effect/Schema/SchemaError`;function fm(e){return xr(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var pm=Nf;function mm(){return(e,t,n)=>Im(new xl(e.map(ru),e=>t(e.map(e=>Im(e))),n))}function hm(e,t){return mm()([],()=>(t,n,r)=>e(t)?S(t):y(new Xs(n,t,r)),t)}var gm=class extends Sa(`SchemaError`){[dm]=dm;constructor(e){let t=Ot();It(0);try{super({issue:e})}finally{It(t)}}get message(){return pc(this.issue)}toString(){return`SchemaError(${this.message})`}};function _m(e){return fm(e)}function vm(e){return mt(e)?ym(e):Hr(e,e=>Jr(()=>Aa(e,e=>new gm(e))))}function ym(e){return Ga(e)?e:Va(Aa(e.cause,e=>new gm(e)))}function bm(e,t){let n;for(let r of e.reasons){if(!Ta(r)||!_m(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 xm(e){let t=Ir(e);if(Ga(t))return t.value;throw bm(t.cause,`Sync adapter can only throw schema errors`)}function Sm(e,t){return $p(e,t)}function Cm(e){return nm(e)}var wm=df;function Tm(e,t){let n=mf(e,t);return(e,t)=>vm(n(e,t))}function Em(e,t){let n=hf(e,t);return(e,t)=>ym(n(e,t))}var Dm=gf;function D(e,t){let n=_f(e,t);return(e,t)=>Yt(n(e,t),e=>new gm(e))}var Om=D;function O(e,t){let n=Tm(e,t);return(e,t)=>xm(n(e,t))}var km=O;function Am(e,t){let n=vf(e,t);return(e,t)=>vm(n(e,t))}function jm(e,t){let n=yf(e,t);return(e,t)=>ym(n(e,t))}function Mm(e,t){let n=bf(e,t);return(e,t)=>Yt(n(e,t),e=>new gm(e))}var Nm=Mm;function Pm(e,t){let n=Am(e,t);return(e,t)=>xm(n(e,t))}var Fm=Pm,Im=If;function Lm(e){return xr(e,pm)&&e[pm]===pm}var k=um(e=>Im(Xu(e.ast),{schema:e})),A=um(e=>{let t=th(e);return Im(Qu(e.ast),{schema:t})}),Rm=um(e=>Im($u(e.ast),{schema:e})),zm=um(e=>Im(ud(e.ast),{schema:e})),Bm=um(e=>Im(dd(e.ast),{schema:e}));function j(e){let t=Im(new Ol(e),{literal:e,transform(n){return t.pipe(ah(j(n),{decode:Dc(()=>n),encode:Dc(()=>e)}))}});return t}var Vm=Im(El),Hm=Im(Dl),Um=Im(Sl),Wm=Im(Tl),M=Im(Al),N=Im(Nl),Gm=Im(Pl),Km=Im(Fl),qm=Im(Il);function Jm(e,t){return Im(e,{fields:t,mapFields(e,t){let n=e(this.fields);return Jm(nu(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e){return Jm(nu(e,void 0),e)}function Ym(e,t){return Im(id(e.ast,t.ast),{key:e,value:t})}function Xm(e,t){return Im(e,{elements:t,mapElements(e,t){let n=e(this.elements);return Xm(iu(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function Zm(e){return Xm(iu(e),e)}var F=um(e=>Im(new Ll(!1,[],[e.ast]),{value:e})),Qm=um(e=>Im(new Ll(!1,[e.ast],[e.ast]),{value:e})),$m=um(e=>Im(ou(e.ast),{schema:e}));function eh(e,t){return Im(e,{members:t,mapMembers(e,t){let n=e(this.members);return eh(au(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function I(e,t){return eh(au(e,t,void 0),e)}function L(e){let t=e.map(j);return Im(au(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=um(e=>I([e,Um])),th=um(e=>I([e,Wm]));function nh(e){return Im(new wu(()=>e().ast))}function z(...e){return t=>t.check(...e)}function rh(e,t){return n=>Im(Vu(n.ast,[Ou(e,t)]),{schema:n})}function ih(e){return t=>Im(t.ast,{schema:t,identifier:e})}function ah(e,t){return n=>Im(nd(n.ast,e.ast,t?Kc(t):Xc()),{from:n,to:e})}function oh(){return(e,t)=>hh()(e,{decode:t,encode:Cc})}function sh(e,t){return n=>t?ah(n,t)(e):ah(n)(e)}function ch(e){return t=>Im(td(t.ast,e),{schema:t})}function lh(e){return Hr(e,e=>Jr(()=>Aa(e,e=>e.issue)))}function uh(e,t){let n=t?.encodingStrategy===`omit`?jc():Tc();return t=>k(Bm(t)).pipe(ah(t,{decode:Mc(lh(e)),encode:n}))}function dh(e,t){let n=t?.encodingStrategy===`omit`?jc():Tc();return t=>A(Bm(t)).pipe(ah(t,{decode:Mc(lh(e)),encode:n}))}function fh(e,t){return n=>zm(n).pipe(dh(e,t),sh(A(n)))}function ph(e){return j(e).pipe(ch(S(e)))}function mh(e,t){return hm(t=>t instanceof e,t)}function hh(){return(e,t)=>new gl(e.ast,Kc(t))}var B=Du,gh=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function _h(e){let t=new globalThis.RegExp(gh);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:gh,flags:``}]},...e})}function vh(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${C(n)})`:`new RegExp(${C(n)}, ${C(r)})`;return Mu(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var yh=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 bh(e,t){let n=yh(e);return vh(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 xh(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return vh(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Sh(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 Ch(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${Op(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:()=>Sh(i,e,`^${Op(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${C(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function wh(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${Op(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:()=>Sh(i,e,`${Op(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${C(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Th(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(Op(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:()=>Sh(i,e,Op(i)),toCode:()=>({runtime:`Schema.isIncluding(${C(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Eh=Im(Au),Dh=ku;function Oh(e){let t=pi(e.order),n=e.formatter??C;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 kh(e){let t=dn(e.order),n=e.formatter??C;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 Ah(e){let t=ci(e.order),n=e.formatter??C;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 jh(e){let t=yt(e.order),n=e.formatter??C;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 Mh(e){let t=dn(e.order),n=pi(e.order),r=yt(e.order),i=ci(e.order),a=e.formatter??C;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 Nh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${C(e)}`);return e}var Ph=Oh({order:en,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Nh(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${C(e)})`})})}),V=kh({order:en,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Nh(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${C(e)})`})})}),Fh=Ah({order:en,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Nh(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${C(e)})`})})}),Ih=jh({order:en,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Nh(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${C(e)})`})})}),Lh=Mh({order:en,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Nh(e.minimum),maximum:Nh(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${C(e.minimum)}, maximum: ${C(e.maximum)}, exclusiveMinimum: ${C(t)}, exclusiveMaximum: ${C(n)} })`})}}});function Rh(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=>No(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(${C(e)})`}),...t})}function zh(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(zh()),Bh=H.check(V(0));function Vh(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${C(e)}`);return e.toISOString()}function Hh(e){return`new Date(${C(e.getTime())})`}var Uh=Oh({order:Pn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:Vh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${Hh(e)})`})})}),Wh=kh({order:Pn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:Vh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${Hh(e)})`})})}),Gh=Ah({order:Pn,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:Vh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${Hh(e)})`})})}),Kh=jh({order:Pn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:Vh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${Hh(e)})`})})}),qh=Mh({order:Pn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:Vh(e.minimum),maximum:Vh(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${Hh(e.minimum)}, maximum: ${Hh(e.maximum)}, exclusiveMinimum: ${C(t)}, exclusiveMaximum: ${C(n)} })`})}}}),Jh=Oh({order:Bn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${C(e)})`})})}),Yh=kh({order:Bn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${C(e)})`})})}),Xh=Ah({order:Bn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${C(e)})`})})}),Zh=jh({order:Bn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${C(e)})`})})}),Qh=Mh({order:Bn,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: ${C(e.minimum)}, maximum: ${C(e.maximum)}, exclusiveMinimum: ${C(t)}, exclusiveMaximum: ${C(n)} })`})}}});function $h(e,t){return e=cg(e),eg(e,Math.ceil(e/2),t)}function eg(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})`}),[ws]:!0,arbitraryConstraint:{minLength:e},...n})}function tg(e){return eg(1,1,e)}function ng(e,t){return e=cg(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})`}),[ws]:!0,arbitraryConstraint:{maxLength:e},...t})}function rg(e,t,n){return e=cg(e),t=cg(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})`}),[ws]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function ig(e,t){return e=cg(e),B(t=>sg(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 ag(e,t){return e=cg(e),B(t=>sg(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 og(e,t,n){return e=cg(e),t=cg(t),B(n=>{let r=sg(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 sg(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function cg(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function lg(e,t){return e=cg(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})`}),[ws]:!0,arbitraryConstraint:{minSize:e},...t})}function ug(e,t){return e=cg(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})`}),[ws]:!0,arbitraryConstraint:{maxSize:e},...t})}function dg(e,t,n){return e=cg(e),t=cg(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})`}),[ws]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function fg(e,t){return e=cg(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})`}),[ws]:!0,arbitraryConstraint:{minProperties:e},...t})}function pg(e,t){return e=cg(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})`}),[ws]:!0,arbitraryConstraint:{maxProperties:e},...t})}function mg(e,t,n){return e=cg(e),t=cg(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})`}),[ws]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var hg=M.check(tg());globalThis.RegExp,globalThis.URL;var gg=M.annotate({expected:`a string that will be decoded as a Date`}),_g=hm(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:()=>hh()(gg,$c)}),vg=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function U(e,t){return vg.pipe(ah(e,tl(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var yg=M.annotate({expected:`a string that will be decoded as a number`}).pipe(ah(N,Zc)),bg=M.check(_h()),xg=M.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(ah(bg,Jc())),Sg=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),Cg=mh(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>hh()(Sg,el)}),wg=qc({decode:(e,t)=>Kr(os(e),{onNone:()=>y(new Zs({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>S(ss(e))}),encode:e=>S(cs(e))}),Tg=-864e13,Eg=864e13;function Dg(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 Og(e,t){return H.check(Lh({minimum:e,maximum:t}))}var kg=hm(e=>rs(e)&&is(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]=Dg(e,Tg,Eg);return oh()(Og(t,n),Dc(as))},toCodecJson:()=>hh()(M,wg),toFormatter:()=>e=>e.toString()}),Ag=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(ah(kg,wg));function jg(e){return rm(e.ast)}function Mg(e,t){return Xp(e.ast,t)}function Ng(e,t){return qp(Xp(Sp(e.ast),t),t)}var Pg=xp,Fg=Im(zu(Vd,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),Ig=Ym(M,Fg),Lg=e=>crypto.getRandomValues(new Uint8Array(e)),Rg=(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}}},zg=(e,t=21)=>Rg(e,t|0,Lg),Bg=`abcdefghijklmnopqrstuvwxyz0123456789`;function Vg(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return zg(Bg,e)()}var Hg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,Ug=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,Wg=w().min(1).max(64).regex(Hg),Gg=w().min(1).max(64).regex(Hg),Kg=w().min(1).max(32).regex(Ug),qg=g({prefix:Kg}),Jg=g({family:Wg,version:x(1),kinds:ui(Gg,qg)}).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)}}),Yg=w(),Xg=/^[a-z0-9]+$/,Zg=new TextEncoder;function Qg(e){return e===32||e>=9&&e<=13}function $g(e){let t=0,n=e.length;for(;t<n&&Qg(e.charCodeAt(t));)t+=1;for(;n>t&&Qg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function e_(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&Xg.test(n)}let r=v(()=>Nr(e=>{let t=Yg.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=Zg.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($g(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=v(()=>Yg.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),rr)}));function o(){let n;try{n=Vg(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 t_=ui(w(),g({family:w(),kind:w(),version:x(1),generate:lt(),schema:e(Ut),parse:lt(),is:lt()})),n_=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},r_=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 i_(e){let t;try{t=Jg.safeParse(e)}catch{throw new n_}if(!t.success)throw new n_;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=e_({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new r_({family:n.family,kind:t})})}let i=Nr(e=>{let t=t_.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 n_;return i.data}var a_=[];for(let e=0;e<256;++e)a_.push((e+256).toString(16).slice(1));function o_(e,t=0){return(a_[e[t+0]]+a_[e[t+1]]+a_[e[t+2]]+a_[e[t+3]]+`-`+a_[e[t+4]]+a_[e[t+5]]+`-`+a_[e[t+6]]+a_[e[t+7]]+`-`+a_[e[t+8]]+a_[e[t+9]]+`-`+a_[e[t+10]]+a_[e[t+11]]+a_[e[t+12]]+a_[e[t+13]]+a_[e[t+14]]+a_[e[t+15]]).toLowerCase()}var s_,c_=new Uint8Array(16);function l_(){if(!s_){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);s_=crypto.getRandomValues.bind(crypto)}return s_(c_)}var u_={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function d_(e,t,n){if(u_.randomUUID&&!t&&!e)return u_.randomUUID();e||={};let r=e.random??e.rng?.()??l_();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return o_(r)}var f_=re({version:`v7`}),p_=w().regex(/^replay_[a-f0-9]{64}$/);Nr(e=>p_.safeParse(e).success);var m_=re({version:`v4`});Nr(e=>f_.safeParse(e).success);var h_=Nr(e=>m_.safeParse(e).success);function g_(){return h_.parse(d_())}var __=v(()=>cn({id:w().min(1).max(256),name:w().min(1).max(128),kind:x(`agent`).optional()})),v_=v(()=>w().min(1).max(256)),y_=v(()=>cn({agentId:v_,sessionId:v_,commandId:v_,outcome:Jt([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:w().min(1).max(200).optional(),waitingOnYou:Dr(cn({itemId:v_,kind:w().min(1).max(64),summary:w().min(1).max(200)})).min(1).max(8).optional()})),b_=cn({author:__.optional(),sourceRequestId:v_.optional(),delegation:cn({ancestors:Dr(v_).max(8),maxDepth:jn().int().min(1).max(8),steer:x(!0).optional(),goal:ei([w().min(1).max(4e3),x(!1)]).optional(),reply:y_.optional()}).optional()});function x_(e){let t=b_.safeParse(e);return t.success?t.data.author:void 0}var S_=Jt([`plain`,`pencil`,`manga`,`riso`,`halftone`,`blueprint`,`crt`,`watercolor`]),C_={ink:`var(--sprite-ink, var(--color-base-content, #1c1c1a))`,paper:`var(--sprite-paper, var(--color-base-100, #fbfaf6))`,accent:`var(--sprite-accent, var(--color-accent, #d20f39))`,risoFirst:`var(--sprite-riso-first, var(--color-info, #1e66f5))`,risoSecond:`var(--sprite-riso-second, var(--color-accent, #ea76cb))`,blueprint:`var(--sprite-blueprint, color-mix(in oklab, var(--color-info, #1e66f5) 55%, #0b2350))`,blueprintLine:`var(--sprite-blueprint-line, color-mix(in oklab, var(--color-info-content, #ffffff) 25%, #ffffff))`,screen:`var(--sprite-screen, color-mix(in oklab, var(--color-base-content, #111111) 12%, #050805))`,phosphor:`var(--sprite-phosphor, var(--color-success, #40a02b))`},W=(e,t={},...n)=>({tag:e,attributes:t,children:n}),w_=(e,t,n=1)=>W(`feFlood`,{style:`flood-color: ${e}`,"flood-opacity":n,result:t}),T_=(e,t,n)=>[W(`feImage`,{href:`data:image/svg+xml,${encodeURIComponent(`<svg xmlns='http://www.w3.org/2000/svg' width='${String(t)}' height='${String(t)}'>${e}</svg>`)}`,width:t,height:t,result:`${n}Cell`}),W(`feTile`,{in:`${n}Cell`,result:n})],E_=(e,t,n)=>W(`feColorMatrix`,{in:t,type:`matrix`,values:`0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ${e}`,result:n}),D_=(e,t)=>E_(`-0.333 -0.333 -0.333 1 0`,e,t),O_=(e,t,n,r=1.1)=>[W(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,result:`${t}In`}),W(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,result:`${t}Out`}),W(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),E_(`${String(n)} ${String(n)} ${String(n)} ${String(r)} 0`,`${t}Edges`,t)],k_=(e,t,n,r)=>[W(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 1 0 1 -4 1 0 1 0`,preserveAlpha:`true`,result:`${t}In`}),W(`feConvolveMatrix`,{in:e,order:3,kernelMatrix:`0 -1 0 -1 4 -1 0 -1 0`,preserveAlpha:`true`,result:`${t}Out`}),W(`feComposite`,{in:`${t}In`,in2:`${t}Out`,operator:`arithmetic`,k2:1,k3:1,result:`${t}Edges`}),E_(`${String(n)} ${String(n)} ${String(n)} 0 -0.15`,`${t}Edges`,`${t}Inner`),W(`feMorphology`,{in:e,operator:`dilate`,radius:r,result:`${t}Grown`}),W(`feComposite`,{in:`${t}Grown`,in2:e,operator:`out`,result:`${t}Ring`}),E_(`0 0 0 1 0`,`${t}Ring`,`${t}Outline`),j_(t,`${t}Inner`,`${t}Outline`)],A_=(e,t,n)=>W(`feComponentTransfer`,{in:e,result:n},W(`feFuncA`,{type:`discrete`,tableValues:t})),j_=(e,...t)=>W(`feMerge`,{result:e},...t.map(e=>W(`feMergeNode`,{in:e}))),M_=(e,t,n,r=1)=>[w_(e,`${n}Flood`,r),W(`feComposite`,{in:`${n}Flood`,in2:t,operator:`in`,result:n})],N_={x:`0%`,y:`0%`,width:`100%`,height:`100%`},P_={x:`-8%`,y:`-8%`,width:`116%`,height:`116%`},F_={value:1.6,line:6,outline:2.4,midHatch:[3.2,-.05],darkHatch:[3.4,-.4],tooth:`0 0 0 -0.7 1.45`,opacity:1},I_=e=>({region:P_,primitives:[W(`feComponentTransfer`,{in:`SourceGraphic`,result:`valued`},...[`feFuncR`,`feFuncG`,`feFuncB`].map(t=>W(t,{type:`gamma`,amplitude:1,exponent:e.value,offset:0}))),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:2,seed:1,result:`wobble`,"data-sprite-boil":`wobble`}),W(`feDisplacementMap`,{in:`valued`,in2:`wobble`,scale:2.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...O_(`drawn`,`line`,e.line,e.outline),D_(`drawn`,`dark`),...T_(`<path d='M-1 1l2-2M0 6l6-6M5 7l2-2' stroke='black' stroke-width='1.1'/>`,6,`hatch45`),W(`feOffset`,{in:`hatch45`,dx:0,dy:0,result:`hatchOffset`,"data-sprite-boil":`hatch`}),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.07,numOctaves:2,seed:5,result:`strokeBend`}),W(`feDisplacementMap`,{in:`hatchOffset`,in2:`strokeBend`,scale:4,xChannelSelector:`R`,yChannelSelector:`B`,result:`hatchA`}),...T_(`<path d='M-1 4l2 2M0 0l5 5M4 -1l2 2' stroke='black' stroke-width='0.9'/>`,5,`hatch135`),W(`feDisplacementMap`,{in:`hatch135`,in2:`strokeBend`,scale:3,xChannelSelector:`G`,yChannelSelector:`R`,result:`hatchB`}),W(`feComposite`,{in:`dark`,in2:`hatchA`,operator:`arithmetic`,k1:e.midHatch[0],k4:e.midHatch[1],result:`shadeA`}),W(`feComposite`,{in:`dark`,in2:`hatchB`,operator:`arithmetic`,k1:e.darkHatch[0],k4:e.darkHatch[1],result:`shadeB`}),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.9,numOctaves:1,seed:3,result:`tooth`}),E_(e.tooth,`tooth`,`toothMask`),E_(`0 0 0 6 -4.6`,`dark`,`solid`),j_(`graphiteRaw`,`solid`,`shadeA`,`shadeB`,`line`),W(`feComposite`,{in:`graphiteRaw`,in2:`toothMask`,operator:`in`,result:`graphite`}),...M_(C_.ink,`graphite`,`pencil`,e.opacity)],boil:{intervalMs:160,tracks:[{name:`wobble`,attribute:`seed`,frames:[1,2,3]},{name:`hatch`,attribute:`dx`,frames:[0,1,2]}]}}),L_={region:P_,primitives:[W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.04,numOctaves:2,seed:2,result:`brush`,"data-sprite-boil":`brush`}),W(`feDisplacementMap`,{in:`SourceGraphic`,in2:`brush`,scale:2,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...M_(C_.paper,`SourceAlpha`,`paperFill`),D_(`drawn`,`dark`),...T_(`<circle cx='2.5' cy='2.5' r='1.15' fill='black'/>`,5,`dots`),A_(`dark`,`0 1 1 0`,`midTone`),W(`feComposite`,{in:`dots`,in2:`midTone`,operator:`in`,result:`tone`}),A_(`dark`,`0 0 0 1`,`solid`),E_(`3 -3 0 0 -0.35`,`drawn`,`satRG`),E_(`-3 3 0 0 -0.35`,`drawn`,`satGR`),E_(`0 3 -3 0 -0.35`,`drawn`,`satGB`),E_(`0 -3 3 0 -0.35`,`drawn`,`satBG`),j_(`saturation`,`satRG`,`satGR`,`satGB`,`satBG`),A_(`saturation`,`0 1`,`accentMask`),...M_(C_.accent,`accentMask`,`accentFill`),...k_(`drawn`,`edge`,2,2.2),W(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.25,result:`stroke`}),j_(`inkRaw`,`tone`,`solid`,`stroke`),...M_(C_.ink,`inkRaw`,`ink`),j_(`manga`,`paperFill`,`accentFill`,`ink`)],boil:{intervalMs:180,tracks:[{name:`brush`,attribute:`seed`,frames:[2,4,6]}]}},R_={region:P_,primitives:[E_(`-0.55 -0.55 -0.55 1.65 0`,`SourceGraphic`,`dark`),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.85,numOctaves:1,seed:7,result:`grain`}),E_(`0 0 0 -0.9 1.35`,`grain`,`grainMask`),W(`feComposite`,{in:`dark`,in2:`grainMask`,operator:`in`,result:`firstMask`}),...M_(C_.risoFirst,`firstMask`,`firstInk`,.92),E_(`0 -1.9 0 1.9 0`,`SourceGraphic`,`secondMask`),...M_(C_.risoSecond,`secondMask`,`secondInk`,.9),W(`feOffset`,{in:`firstInk`,dx:-1.5,dy:1,result:`firstPlate`,"data-sprite-boil":`register`}),W(`feOffset`,{in:`secondInk`,dx:1.5,dy:-.5,result:`secondPlate`}),W(`feBlend`,{in:`firstPlate`,in2:`secondPlate`,mode:`multiply`})],boil:{intervalMs:240,tracks:[{name:`register`,attribute:`dx`,frames:[-1.5,-1,-2]}]}},z_={region:P_,primitives:[E_(`-0.5 -0.5 -0.5 1.65 0`,`SourceGraphic`,`value`),E_(`0 0 0 0.16 0`,`SourceGraphic`,`floor`),j_(`dark`,`floor`,`value`),...T_(`<defs><radialGradient id='d'><stop offset='0' stop-opacity='1'/><stop offset='1' stop-opacity='0'/></radialGradient></defs><rect width='6' height='6' fill='url(#d)'/>`,6,`screen`),W(`feComposite`,{in:`dark`,in2:`screen`,operator:`arithmetic`,k2:1,k3:1,k4:-.92,result:`dotField`}),W(`feComponentTransfer`,{in:`dotField`,result:`dotsRaw`},W(`feFuncA`,{type:`linear`,slope:12,intercept:0})),W(`feComposite`,{in:`dotsRaw`,in2:`SourceAlpha`,operator:`in`,result:`dots`}),...M_(C_.ink,`dots`,`halftone`)]},B_={region:N_,primitives:[w_(C_.blueprint,`ground`),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.05,numOctaves:1,seed:4,result:`hand`,"data-sprite-boil":`hand`}),W(`feDisplacementMap`,{in:`SourceGraphic`,in2:`hand`,scale:1.6,xChannelSelector:`R`,yChannelSelector:`G`,result:`drawn`}),...T_(`<path d='M0 0.5h16M0.5 0v16' stroke='black' stroke-width='1' stroke-opacity='0.22'/>`,16,`grid`),...M_(C_.blueprintLine,`grid`,`gridLines`),...M_(C_.blueprintLine,`SourceAlpha`,`wash`,.12),...k_(`drawn`,`edge`,3,1.2),W(`feMorphology`,{in:`edge`,operator:`dilate`,radius:.3,result:`stroke`}),...M_(C_.blueprintLine,`stroke`,`lines`),j_(`blueprint`,`ground`,`gridLines`,`wash`,`lines`)],boil:{intervalMs:200,tracks:[{name:`hand`,attribute:`seed`,frames:[4,5,6]}]}},V_={region:N_,primitives:[w_(C_.screen,`ground`),W(`feColorMatrix`,{in:`SourceGraphic`,type:`luminanceToAlpha`,result:`lumRaw`}),W(`feComposite`,{in:`lumRaw`,in2:`SourceAlpha`,operator:`in`,result:`lum`}),W(`feComponentTransfer`,{in:`lum`,result:`beam`},W(`feFuncA`,{type:`linear`,slope:1.5,intercept:-.35})),W(`feComposite`,{in:`beam`,in2:`SourceAlpha`,operator:`in`,result:`trace`}),...M_(C_.phosphor,`trace`,`glow`),W(`feGaussianBlur`,{in:`glow`,stdDeviation:2.5,result:`bloom`}),...T_(`<rect y='2' width='3' height='1' fill='black'/>`,3,`scan`),W(`feOffset`,{in:`scan`,dx:0,dy:0,result:`scanRoll`,"data-sprite-boil":`roll`}),...M_(C_.screen,`scanRoll`,`scanlines`,.6),j_(`crt`,`ground`,`bloom`,`glow`,`scanlines`)],boil:{intervalMs:120,tracks:[{name:`roll`,attribute:`dy`,frames:[0,1,2]}]}},H_={region:P_,primitives:[W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.03,numOctaves:3,seed:9,result:`flow`}),W(`feDisplacementMap`,{in:`SourceGraphic`,in2:`flow`,scale:7,xChannelSelector:`R`,yChannelSelector:`G`,result:`bled`}),W(`feGaussianBlur`,{in:`bled`,stdDeviation:1.4,result:`wash`}),W(`feComponentTransfer`,{in:`wash`,result:`thin`},W(`feFuncR`,{type:`linear`,slope:.78,intercept:.2}),W(`feFuncG`,{type:`linear`,slope:.78,intercept:.2}),W(`feFuncB`,{type:`linear`,slope:.78,intercept:.2}),W(`feFuncA`,{type:`linear`,slope:.9,intercept:0})),W(`feGaussianBlur`,{in:`wash`,stdDeviation:3,result:`spread`}),W(`feComposite`,{in:`wash`,in2:`spread`,operator:`arithmetic`,k2:1.6,k3:-1.4,result:`rimMask`}),W(`feComponentTransfer`,{in:`wash`,result:`deep`},W(`feFuncR`,{type:`linear`,slope:.6,intercept:0}),W(`feFuncG`,{type:`linear`,slope:.6,intercept:0}),W(`feFuncB`,{type:`linear`,slope:.6,intercept:0})),W(`feComposite`,{in:`deep`,in2:`rimMask`,operator:`in`,result:`rim`}),W(`feTurbulence`,{type:`fractalNoise`,baseFrequency:.7,numOctaves:2,seed:11,result:`tooth`}),E_(`0 0 0 -0.8 1.5`,`tooth`,`toothMask`),D_(`SourceGraphic`,`dark`),E_(`0 0 0 5 -3.8`,`dark`,`keyMask`),...M_(C_.ink,`keyMask`,`key`,.9),j_(`paint`,`thin`,`rim`,`key`),W(`feComposite`,{in:`paint`,in2:`toothMask`,operator:`in`})]},U_=I_(F_),W_={manga:L_,riso:R_,halftone:z_,blueprint:B_,crt:V_,watercolor:H_},G_=e=>e===`pencil`?U_:W_[e],K_=`http://www.w3.org/2000/svg`,q_=(e,t)=>{let n=e.createElementNS(K_,t.tag);for(let[e,r]of Object.entries(t.attributes))n.setAttribute(e,String(r));for(let r of t.children)n.append(q_(e,r));return n};function J_(e){let t=`sprite-style-${g_()}`,n=e.ownerDocument,r=n.defaultView,i=`plain`,a,o,s=!1,c=!0,l,u=0,d=()=>{l!==void 0&&clearInterval(l),l=void 0},f=()=>{if(d(),i===`plain`||!o||s||!c||n.hidden)return;let e=G_(i).boil;if(!e)return;let t=o;l=setInterval(()=>{if(!n.hidden){u+=1;for(let n of e.tracks){let e=n.frames[u%n.frames.length];t.querySelector(`[data-sprite-boil="${n.name}"]`)?.setAttribute(n.attribute,String(e))}}},e.intervalMs)},p=r?.IntersectionObserver,m=p?new p(e=>{c=e.some(e=>e.isIntersecting),f()}):void 0;m?.observe(e);let ee=()=>{d(),o?.remove(),o=void 0,a&&(a.style.filter=``)};return{set(r,s){if(r===i&&s===a||(ee(),i=r,a=s,r===`plain`))return;let c=G_(r),l=`${t}-${r}`,u=n.createElementNS(K_,`svg`);u.setAttribute(`aria-hidden`,`true`),u.setAttribute(`focusable`,`false`),u.setAttribute(`width`,`0`),u.setAttribute(`height`,`0`),u.style.cssText=`position:absolute;width:0;height:0;overflow:hidden`,u.append(q_(n,W(`filter`,{id:l,...c.region,"color-interpolation-filters":`sRGB`},...c.primitives))),e.append(u),o=u,s.style.filter=`url(#${l})`,f()},still(e){e!==s&&(s=e,f())},dispose(){ee(),a=void 0,m?.disconnect()}}}var Y_=[`mushroom`,`cat`,`burger`];Jt([`shift`,`keep`]);var X_=w().regex(/^#[0-9a-f]{6}$/i),Z_=ei([X_,jn(),mr()]),Q_=16,$_=cn({v:x(1),character:Jt(Y_),appearance:ui(w().min(1),Z_).refine(e=>Object.keys(e).length<=Q_,{message:`Avatar appearance cannot exceed ${String(Q_)} keys`}),expression:w().min(1),renderStyle:S_});function ev(e,t,n){let r=t/100,i=n/100,a=r*Math.min(i,1-i),o=t=>{let n=(t+e/30)%12,r=i-a*Math.max(-1,Math.min(n-3,9-n,1));return Math.round(255*r).toString(16).padStart(2,`0`)};return`#${o(0)}${o(8)}${o(4)}`}function tv(e){let t=2166136261;for(let n of e)t^=n.codePointAt(0)??0,t=Math.imul(t,16777619)>>>0;return t}function nv(e){let t=tv(e)%360;return{cap:ev(t,68,72),capSpot:ev(t,70,92)}}function rv(e){return{v:1,character:`mushroom`,appearance:nv(e),expression:`normal`,renderStyle:`plain`}}var iv=Symbol.for(`effect/MutableList/Empty`),av=()=>({head:void 0,tail:void 0,length:0}),ov=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})},sv=()=>({array:[],mutable:!0,offset:0,next:void 0}),cv=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=sv(),e.tail=e.tail.next):e.head=e.tail=sv(),e.tail.array.push(t),e.length++},lv=e=>{e.head=e.tail=void 0,e.length=0},uv=(e,t)=>{if(t=ea(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 lv(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?lv(e):ov(e),n;i=i.next}return lv(e),n},dv=e=>uv(e,e.length),fv=e=>{if(!e.head)return iv;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:lv(e):ov(e),t},pv=`~effect/Queue`,mv=`~effect/Queue/Enqueue`,hv=`~effect/Queue/Dequeue`,gv={_A:Ue,_E:Ue},_v={[pv]:gv,[mv]:gv,[hv]:gv,...fe,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:Pv(this)}}},vv=e=>Ce(t=>{let n=Object.create(_v);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=av(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},fi(n)}),yv=e=>vv({capacity:e}),bv=e=>vv({capacity:e,strategy:`dropping`}),xv=a(2,(e,t)=>si(()=>Sv(e,t)?Iv:e.state._tag===`Open`&&e.strategy===`suspend`?Gv(e,t):Fv)),Sv=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(fv(e.messages),cv(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(cv(e.messages,t),zv(e),!0):(cv(e.messages,t),Bv(e),!0):!1,Cv=a(2,(e,t)=>wv(e,s(t))),wv=a(2,(e,t)=>vt(()=>Tv(e,t))),Tv=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Oe(t),r=Ie(n,Lv);return e.state.offers.size===0&&e.messages.length===0?(Zv(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},Bv(e),!0)},Ev=e=>Tv(e,s(ri())),Dv=e=>vt(()=>Ov(e)),Ov=e=>{if(e.state._tag===`Done`)return!1;lv(e.messages);let t=e.state.offers;Zv(e,e.state._tag===`Open`?Rv:e.state.exit);for(let e of t)qv(e);return!0},kv=e=>Hv(()=>{if(e.state._tag===`Done`)return Io(e.state.exit,()=>fi([]));let t=Xv(e);return Yv(e),fi(t)}),Av=e=>jv(e,1,1/0),jv=a(3,(e,t,n)=>(t=ea(t),n=ea(n),Hv(()=>Vv(e,t,n)??Qn(Wv(e,()=>Uv(e,t)),jv(e,t,n))))),Mv=e=>Hv(()=>Nv(e)??Qn(Wv(e,()=>Uv(e,1)),Mv(e))),Nv=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=fv(e.messages);return Yv(e),Be(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=Jv(e.state.offers);return Yv(e),Be(t)}},Pv=e=>e.state._tag===`Done`?0:e.messages.length,Fv=Be(!1),Iv=Be(!0),Lv=ge(ri()),Rv=f(),zv=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(xe),e.messages.length===0))break}},Bv=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,zv(e)},0))},Vv=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Be([]);if(!Uv(e,t))return;let r=e.messages.length>0?uv(e.messages,n):[Jv(e.state.offers)];return Yv(e),Be(r)},Hv=Mt({op:`QueueTake`,[Xe](e){let t=this[tt]();return gi(t)?t[Xe](e):t}}),Uv=(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,Wv=(e,t)=>Jn(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(xe);let r={ready:t,resume:n};return e.state.takers.add(r),vt(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),Gv=(e,t)=>Jn(n=>Sv(e,t)?n(Iv):Kv(e,{_tag:`Single`,message:t,resume:n})),Kv=(e,t)=>{if(e.state._tag!==`Open`)return qv(t);let n=e.state.offers;return n.add(t),vt(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&Zv(e,e.state.exit))})},qv=e=>e._tag===`Single`?e.resume(Fv):e.resume(Be(e.remaining.slice(e.offset))),Jv=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(Iv),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Be([]))),n},Yv=e=>{if(e.state._tag===`Done`)return Lo(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(Zv(e,e.state.exit),Lo(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`)cv(e.messages,t.message),e.state.offers.delete(t),t.resume(Iv);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;cv(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Be([]))}let r=e.state;if(r._tag===`Done`)return Lo(r.exit.cause)}return!1},Xv=e=>{if(e.messages.length>0){let t=dv(e.messages);return Yv(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[Jv(e.state.offers)];return Yv(e),t}return[]},Zv=(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()},Qv=Tr,$v=Kt,ey=Ne,ty=Br,ny=Vt,ry=Pr,iy=gr,ay=e=>new sy(e),oy=(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),vt(()=>{e.waiters.delete(i)})}),sy=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=si(()=>this.free<e?oy(this,e,t):(this.taken+=e,fi(e)));return t}takeIfAvailable(e){return si(()=>this.free<e?fi(!1):(this.taken+=e,fi(!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 Ce(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ni))}release(e){return Ce(t=>fi(this.releaseUnsafe(t,e)))}get releaseAll(){return Ce(e=>fi(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>ee(n=>{let r=si(()=>{if(this.free<e){let t=oy(this,e,ni);return wn(n(t),()=>r)}return this.taken+=e,gn(n(t),()=>{this.releaseUnsafe(Br(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>ee(n=>this.free<e?un:(this.taken+=e,gn(n(c(t)),()=>{this.releaseUnsafe(Br(),e)},!0)))}},cy=e=>vt(()=>new sy(e)),ly=`~effect/Channel`,uy=e=>xr(e,ly),dy={[ly]:{_Env:Ue,_InErr:Ue,_InElem:Ue,_OutErr:Ue,_OutElem:Ue},pipe(){return Re(this,arguments)}},fy=e=>{let t=Object.create(dy);return t.transform=(t,n)=>Hr(e(t,n),e=>S(Zt(e))),t},py=(e,t)=>fy((n,r)=>T(gy(e)(n,r),e=>t(e,r))),my=e=>fy((t,n)=>e),hy=e=>fy(ht(function*(t,n){let r=po(n),i=e=>mo(r,Vo(e)),a=yield*ve(e(t,n,r),i);return ve(a,i)})),gy=e=>e.transform,_y=4096,vy=(e,t,n)=>vv({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(Fn(t=>uo(e,Dv(t))),Fn(n=>co(t(n),e).pipe(Hr(e=>wv(n,e)),Qe(e)))),yy=(e,t)=>fy((n,r)=>Te(vy(r,e,t),Av)),by=e=>fy((t,n)=>lr(()=>gy(e())(t,n))),xy=e=>my(Vn(()=>{let t=e();return lr(()=>{let e=t.next();return e.done?Ra(e.value):S(e.value)})})),Sy=(e,t=_y)=>{let n=ta(t);return my(Vn(()=>{let t=e(),r=Sn();return lr(()=>{if(r._tag===`Some`)return Ra(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return Ra(n.value);r=Cr(n.value);break}e.push(n.value)}return S(e)})}))},Cy=(e,t=_y)=>Sy(()=>e[Symbol.iterator](),t),wy=e=>Oy(S(e)),Ty=my(S(Ra())),Ey=e=>my(S(y(e))),Dy=e=>my(Zt(e)),Oy=e=>my(Vn(()=>{let t=!1;return lr(()=>t?Ra():(t=!0,e))})),ky=e=>my(S(Av(e))),Ay=(e,t)=>fy(ht(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*uo(r,qt(()=>i.return()))),T(fn({try:()=>i.next(),catch:t}),e=>e.done?Ra(e.value):S(e.value))})),jy=(e,t)=>My(Ay(e,t),Ft),My=a(2,(e,t)=>py(e,e=>Vn(()=>{let n=0;return Te(e,e=>t(e,n++))}))),Ny=e=>e===void 0||e!==`unbounded`&&e<=1,Py=a(e=>uy(e[0]),(e,t,n)=>Ny(n?.concurrency)?Fy(e,t):Iy(e,t,n)),Fy=(e,t)=>fy((n,r)=>{let i=0;return Te(gy(e)(n,r),T(e=>t(e,i++)))}),Iy=(e,t,n)=>hy(ht(function*(r,i,a){let o=0,s=yield*gy(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*yv(0);yield*uo(a,Dv(l));let u=jr(yield*Dn()),d=ny(a);if(n.unordered){let e=ay(c),n=Xn(e.release(1)),r=At({onFailure:e=>T(wv(l,e),n),onSuccess:e=>T(xv(l,e),n)});yield*e.take(1).pipe(T(()=>s),T(e=>{let n=o++;return d(u(r(lr(()=>t(e,n))))),ii}),xt({disableYield:!0}),Hr(t=>e.withPermits(c-1)(wv(l,t))),Qe(a))}else{let e=yield*yv(c-2);yield*uo(a,Dv(e)),yield*Mv(e).pipe(ai,T(e=>xv(l,e)),xt({disableYield:!0}),Hr(e=>wv(l,e)),Qe(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,Tv(l,e.cause))};yield*s.pipe(T(i=>{if(n)return Zt(n);let a=o++,s=u(lr(()=>t(i,a)));return d(s),s.addObserver(r),xv(e,$v(s))}),xt({disableYield:!0}),Hr(t=>xv(e,Va(t)).pipe(_(wv(e,t)))),Qe(a))}return Mv(l)})),Ly=a(e=>uy(e[0]),(e,t,n)=>Ny(n?.concurrency)?Ry(e,t):zy(e,t,n)),Ry=(e,t)=>fy((n,r)=>Te(gy(e)(n,r),e=>{let i,a,o=T(e,e=>(a??=po(r),sn(gy(t(e))(n,a),e=>(i=s(e),i)))),s=Io(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=mo(a,Wa);return a=void 0,T(t,()=>o)});return lr(()=>i??o)})),zy=(e,t,n)=>e.pipe(My(t),Ky(n)),By=e=>Ly(e,Ue),Vy=e=>py(e,e=>{let t,n=0,r=lr(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return S(e[0]);default:return t=e,S(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),S(i)});return S(r)}),Hy=a(2,(e,t)=>py(e,e=>S(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return jt(i)?S(i):T(e,n)})))),Uy=a(2,(e,t)=>fy((n,r)=>{let i=po(r);return Te(gy(e)(n,i),e=>{let a=e.pipe(Hr(e=>{if(Lo(e))return Zt(e);let o=i;return i=po(r),mo(o,Va(e)).pipe(_(gy(t(e))(n,i)),T(e=>(a=e,e)))}));return lr(()=>a)})})),Wy=a(3,(e,t,n)=>Uy(e,e=>{let r=t(e);return je(r)?Dy(r.failure):n(r.success,e)})),Gy=a(2,(e,t)=>Wy(e,Ma,e=>t(e))),Ky=a(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>hy(ht(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:ay(s),l=yield*iy(!0),u=new Set,d=yield*yv(t);yield*uo(o,Dv(d));let f=yield*gy(e)(i,a);return yield*b(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*ce(f),yield*En(c.take(1),_($v(e),Pt))));let t=e===void 0?yield*f:yield*$v(e),n=po(o),r=yield*gy(t)(i,n);for(;u.size>=s;){let e=na(u);u.delete(e),u.size===0&&(yield*l.open),yield*ey(e)}let a=yield*r.pipe(Fn(()=>pe),T(e=>xv(d,e)),xt({disableYield:!0}),ve(ht(function*(e){let t=Vo(e),r=yield*In(mo(n,t));if(!u.has(a))return;let i=Ya([t,r]);Ka(i)&&(yield*wv(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),ce);l.closeUnsafe(),u.add(a)}}).pipe(Hr(e=>{let t=zo(e);return Wt(t)?l.whenOpen(wv(d,e)):wv(d,e)}),Qe(o)),Mv(d)}))),qy=a(e=>uy(e[0])&&uy(e[1]),(e,t,n)=>hy(ht(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*yv(0);yield*uo(a,Dv(s));let c=0;function l(e,t){if(c++,!Lo(t))return wv(s,t);switch(o){case`both`:return c===2?wv(s,t):ii;case`left`:case`right`:return e===o?wv(s,t):ii;case`either`:return wv(s,t)}}let u=(e,t,n)=>gy(t)(r,n).pipe(T(e=>e.pipe(T(e=>xv(s,e)),xt)),ve(t=>wr(Vo(t),e=>mo(n,e)).pipe(At({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Qe(a));return yield*u(`left`,e,po(a)),yield*u(`right`,t,po(a)),Mv(s)}))),Jy=e=>fy((t,n)=>{let r;return S(lr(()=>r||e.pipe(co(n),T(e=>gy(e)(t,n)),T(e=>r=e))))}),Yy=a(2,(e,t)=>qy(e,my(S(T(t,Ra))),{haltStrategy:`either`})),Xy=a(2,(e,t)=>hy((n,r,i)=>lo(i,t).pipe(_(gy(e)(n,r))))),Zy=a(2,(e,t)=>Xy(e,e=>t)),Qy=(e,t,n)=>lr(()=>{let r=so(),i=gy(e)(Ra(),r);return Io(T(i,t),n||S).pipe(Pe(e=>mo(r,e)))}),$y=a(2,(e,t)=>Qy(e,e=>xt(T(e,t),{disableYield:!0}))),eb=ht(function*(e){let t=ay(1),n=yield*Dn(),r=De(n,ao);return(yield*gy(e)(Ra(),r)).pipe(ct(n),t.withPermits(1))},Hr(e=>S(Zt(e)))),tb=(e,t)=>gy(e)(Ra(),t),nb=`~effect/Stream`,rb={_R:Ue,_E:Ue,_A:Ue},ib=function(e){this.channel=e};ib.prototype={[nb]:rb,pipe(){return Re(this,arguments)}};var ab=e=>new ib(e),ob=`~effect/Sink`,sb={_A:Ue,_In:Ue,_L:Ue,_E:Ue,_R:Ue},cb={[ob]:sb,pipe(){return Re(this,arguments)}},lb=e=>{let t=Object.create(cb);return t.transform=e,t},ub=((e,t,n)=>lb(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)),Ra();return ii}),xt({disableYield:!0}),Io(()=>S([i,a]))):S([i])}))(Sn,an,(e,t)=>Cr(t)),db=()=>ub,fb=`~effect/Stream`,pb=e=>xr(e,fb),mb=ab,hb=e=>mb(Oy(Te(e,Ft))),gb=e=>vb(S(T(e,()=>Ra()))),_b=e=>vb(S(Te(e,Ft))),vb=e=>mb(my(e)),yb=(e,t)=>mb(fy((n,r)=>T(tb(e.channel,r),e=>t(e,r)))),bb=e=>e.channel,xb=(e,t)=>mb(yy(e,t)),Sb=mb(Ty),Cb=e=>mb(wy(Ft(e))),wb=e=>mb(by(()=>e().channel)),Tb=e=>mb(Ey(e)),Eb=e=>mb(Dy(e)),Db=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Ob(e):mb(Cy(e,t?.chunkSize)),Ob=e=>jt(e)?mb(wy(e)):Sb,kb=e=>mb(ky(e)),Ab=(e,t)=>mb(jy(e,t)),jb=(e,t)=>vb(Vn(()=>{let n=e,r=!1;return lr(function e(){return r?Ra():T(t(n),([t,i])=>(an(i)?r=!0:n=i.value,jt(t)?S(t):e()))})})),Mb=e=>mb(Jy(Te(e,bb))),Nb=a(2,(e,t)=>wb(()=>{let n=0;return mb(My(e.channel,Dt(e=>t(e,n++))))})),Pb=a(e=>pb(e[0]),(e,t,n)=>e.channel.pipe(Vy,Py(t,n),My(Ft),mb)),Fb=e=>e.pipe(Nb(t),Kb(e=>Cb(ye(e)))),Ib=a(e=>pb(e[0]),(e,t,n)=>e.channel.pipe(Vy,Ly(e=>t(e).channel,n),mb)),Lb=a(2,(e,t)=>{let n=de(t.duration);if(!ae(n))return e;if(et(n))return wb(t.orElse);let r=Symbol();return Gb(wb(()=>{let t=ty().getRef(ho),i=o(n),a,s=ry(!1);return Hb(yb(e,(e,n)=>lr(()=>(a=t.currentTimeMillisUnsafe()+i,s.openUnsafe(),e)).pipe(Te(e=>(s.closeUnsafe(),a=void 0,e)),S)),gb(b(function*(){for(;;)if(yield*s.await,a!==void 0&&(yield*An(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*br(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Eb(e))}),Rb=e=>Ib(e,Db),zb=a(2,(e,t)=>{let n=mb(By(xy(()=>Vb(e,t))));return Bb.set(n,[e,t]),n}),Bb=new WeakMap;function*Vb(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=Bb.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var Hb=a(e=>pb(e[0])&&pb(e[1]),(e,t,n)=>mb(qy(bb(e),bb(t),n))),Ub=a(2,(e,t)=>mb(Hy(bb(e),t))),Wb=a(2,ht(function*(e,t){let n,r=yield*eb(e.channel),i=Hr(r,e=>(n=e,Zt(e))),[a,o]=yield*qr(e=>t.transform(i,e)),s=n?Sb:vb(S(r));return o&&(s=zb(Ob(o),s)),[a,s]})),Gb=a(2,(e,t)=>e.channel.pipe(Uy(e=>t(e).channel),mb)),Kb=a(2,(e,t)=>mb(Gy(e.channel,e=>t(e).channel))),qb=a(e=>pb(e[0]),(e,t,n)=>yb(e,(e,r)=>Vn(()=>{let r=0,i=!1;return T(lr(()=>i?Ra():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 jt(t)?S(t):Ra()}return S(e)})}))),Jb=a(2,(e,t)=>mb(Yy(e.channel,t))),Yb=a(2,(e,t)=>mb(Zy(e.channel,t))),Xb=a(2,(e,t)=>$y(e.channel,e=>{let n=0;return Tt({while:()=>n<e.length,body:()=>t(e[n++]),step:$e})})),Zb=a(2,(e,t)=>({[Symbol.asyncIterator](){let n=on(t),r=jr(t),i=so(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Mr(_(t?ey(t):ii,mo(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(rt(`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(tb(e.channel,i),e=>(a=e,e)));s=t;let d=await n(Qv(t));if(s===t&&(s=void 0),Ga(d))return o=d.value[Symbol.iterator](),o.next();if(Lo(d.cause))return l(Wa);if(c&&ka(d.cause))return c;throw await u(d),ja(d.cause)},return(){return l(Wa)},async throw(e){throw await u(Ua(e)),e}}}})),Qb=e=>Zb(e,he()),$b=15e3,ex=45e3,tx=hg.check(ng(256)),nx=H.check(V(0)),rx=P({agentId:tx,sessionId:tx,name:tx}),ix=P({by:rx,reason:L([`escalated`,`sender_archived`,`sender_absent`]),note:k(M.check(ng(1e3)))}),ax=P({id:tx,kind:hg.check(ng(64)),summary:hg.check(ng(200)),since:nx,expiresAt:A(nx),inbox:A(j(!1)),waitingOn:A(rx),escalated:A(ix)}),ox=ax.mapFields(e=>({...e,extensionId:tx})),sx=4096,cx=F(ox).check(ng(64)),lx=M.pipe(z($h(1)),z(ng(256))),ux=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],dx=P({providerId:lx,modelId:lx,reasoning:A(L(ux))}),fx=O(R(dx)),px=O(U(R(dx))),mx=L([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),hx=L([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),gx=M.pipe(z($h(1)),z(ng(256))),_x=P({_tag:j(`ShiitakeError`),boundary:mx,cause:hx,message:M,requestId:k(gx)}),G=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}},vx=new TextEncoder;function yx(e){return M.check($h(1),ng(e),B(t=>vx.encode(t).byteLength<=e))}var bx=/\p{Cs}/u,xx=yx(256).check(B(e=>!bx.test(e))),Sx=yx(262144),Cx=P({type:j(`image`),data:M.check($h(1),ng(1048576),xh()),mimeType:M.check(B(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),wx=F(Cx).check($h(1),ng(8)),Tx=L([`steer`,`followUp`]),Ex=xx,Dx=D(P({commandId:xx,timeoutMs:H.check(V(0),Ih(3e4))}),{onExcessProperty:`error`});D(P({commandId:xx,timeoutMs:yg.check(zh(),Lh({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Ox=D(yx(512)),kx=P({requestId:xx}),Ax=P({delivery:Tx,requestId:xx,type:j(`prompt`),text:M.check(ng(262144),B(e=>vx.encode(e).byteLength<=262144)),images:k(wx)}).check(B(e=>(e.text.length>0||(e.images?.length??0)>0)&&vx.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),jx=P({type:j(`abort`)}),Mx=P({commandId:xx,onlyIfPending:A(Gm),type:j(`cancel`)}),Nx=P({type:j(`operator`),requestId:xx,author:L([`operator`,`party`]),text:Sx}),Px=P({type:j(`branch`),entryId:xx}),Fx=P({type:j(`fork`),entryId:xx}),Ix=M.check($h(1),ng(4096)),Lx=P({type:j(`compact`),requestId:xx,instructions:k(Ix)}),Rx=I([Ax,Lx]),zx=M.check(B(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),Bx=I([Ax,jx,Mx,Px,Fx,Nx,Lx,P({type:j(`title`),title:R(zx)})]),Vx=P({command:Bx}),Hx=P({includeSandboxFailures:A(Gm),limit:A(H.check(Lh({minimum:1,maximum:200}))),before:A(yx(512))}),Ux=P({includeSandboxFailures:A(j(`true`)),limit:A(yg.check(zh(),Lh({minimum:1,maximum:200}))),before:A(yx(512))}),Wx=P({includeSandboxFailures:A(Gm),after:A(M)}),Gx=P({includeSandboxFailures:A(j(`true`)),mode:A(j(`subscribe`)),after:A(M),limit:A(yg.check(zh(),Lh({minimum:1,maximum:200})))}),Kx={onExcessProperty:`error`},qx=D(Ex,Kx),Jx=D(kx,Kx),Yx=D(Rx,Kx);D(xx);var Xx=D(Bx,Kx);D(Vx,Kx);var Zx=D(I([Hx,Wm]),Kx);D(Ux,Kx);var Qx=D(Wx,Kx);D(Gx,Kx);function $x(e){let t=qx(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session id is invalid`);return t.success}function eS(e){let t=Ox(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function tS(e){let t=Jx(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function nS(e){let t=Zx(e);if(t._tag===`Failure`)throw new G(`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 rS(e){let t=Qx(e);if(t._tag===`Failure`)throw new G(`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 iS(e,t){if(je(e))throw new G(`contract`,`invalid`,t);return e.success}var aS=yn();function oS(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function sS(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 cS(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 lS(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var uS=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function dS(e){return uS.has(e)}function fS(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 pS(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 mS(e){return e.slice(e.indexOf(`.`)+1)}function hS(e){return e.slice(0,e.indexOf(`.`))}var gS=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,_S=1e3,vS=221;function yS(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,yS(r,t+1));return n}if(!oS(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,yS(r,t+1));return n}var bS=v(()=>ui(w(),yn()).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`}),yS(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),xS=v(()=>g({query:w().max(200),maxResults:jn().int().min(1).max(50).default(50)})),SS=v(()=>g({path:w().max(160),detail:Jt([`index`,`full`]).default(`full`),methods:Dr(w().max(80)).max(50).optional()})),CS=g({cursor:w().max(400).optional(),limit:jn().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()}),wS=v(()=>g({path:w().max(160),capabilityNotes:w().max(500).optional()})),TS=g({path:w().max(160),description:w().max(1e3).optional(),score:jn().min(0).max(vS),matchReason:w().max(500).optional(),sample:bS.optional(),capabilityNotes:w().max(500).optional(),peers:Dr(wS).max(1e3).optional()}),ES=v(()=>g({results:Dr(TS).max(50),total:jn().int().min(0).max(_S),truncated:mr(),topScore:jn().min(0).max(vS),margin:jn().min(0).max(vS),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)})),DS=g({results:Dr(TS).max(50),total:jn().int().min(0).max(_S),nextCursor:w().max(400).nullable(),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)}),OS=v(()=>g({path:w().max(160),description:w().max(1e3).optional(),types:w().max(2e4),inputSchema:yn().refine(e=>JSON.stringify(e).length<=2e4&&yS(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:Jt([`module`,`operation`]),usage:w().max(300).optional()}));v(()=>g({code:Jt([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:w().max(1e3)}));var kS=v(()=>g({"~standard":g({jsonSchema:g({input:e(Function),output:e(Function)})})})),AS=v(()=>Nr(e=>kS.safeParse(e).success,`Expected a Standard JSON Schema`)),jS=v(()=>g({path:w().min(3).max(160).regex(gS),description:w().max(1e3).optional(),input:AS,output:AS.optional(),capabilityNotes:w().max(500).optional(),instructions:w().max(1e3).optional()})),MS=v(()=>g({revision:w().min(1).max(160),operations:Dr(jS).max(_S)})),NS=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}}},PS=ei([or({$ref:w().optional(),$defs:ui(w(),St()).optional(),definitions:ui(w(),St()).optional(),const:St().optional(),enum:Dr(St()).optional(),oneOf:Dr(St()).optional(),anyOf:Dr(St()).optional(),allOf:Dr(St()).optional(),type:ei([w(),Dr(w())]).optional(),properties:ui(w(),St()).optional(),additionalProperties:St().optional(),required:Dr(w()).optional(),prefixItems:Dr(St()).optional(),items:St().optional(),examples:Dr(St()).optional(),default:St().optional()}),mr()]),FS=new WeakMap;function IS(e,t){let n=FS.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 NS(`invalid_input`,`Schema cannot be projected to JSON Schema`)}zS(i);let a={raw:i};return n===void 0&&(n={},FS.set(e,n)),n[t]=a,a}function LS(e,t){return IS(e,t).raw}function RS(e,t){let n=IS(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new NS(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function zS(e){let t=PS.safeParse(e);if(!t.success)throw new NS(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var BS=256,VS=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function HS(e,t,n){let r=VS.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>BS)throw new NS(`invalid_input`,`Schema references expand more than ${String(BS)} times; flatten its shared definitions`);return WS(zS(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function US(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=VS.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&US(zS(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 WS(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 HS(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=>WS(zS(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>WS(zS(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=zS(e),i=WS(n,t+1,r);return US(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>sS(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${WS(zS(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
4
|
+
${n.map(([e,n])=>{let a=WS(zS(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
|
+
`)}
|
|
6
|
+
${` `.repeat(t)}}`}if(e.type===`array`){let n=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>WS(zS(e),t+1,r));return n!==void 0&&n!==!0&&!Array.isArray(n)&&i.push(`...${WS(zS(n),t+1,r)}[]`),`[${i.join(`, `)}]`}if(n!==void 0&&Array.isArray(n))return`[${n.map(e=>WS(zS(e),t+1,r)).join(`, `)}][]`;let i=n===void 0||zS(n),a=WS(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 GS(e,t=`input`){return WS(zS(LS(e,t)),0)}function KS(e){return e.replace(/[^A-Za-z0-9_$]/g,`_`)}function qS(e,t,n){let r=`(input: ${t}) => Promise<${n}>`;for(let t of e.split(`.`).reverse())r=`{ [${JSON.stringify(t)}]: ${r} }`;return r}function JS(e){return e.length===0?``:`export declare const env: ${e.map(e=>e.indexEnvironment).join(` & `)};`}function YS(e){let t=e.map(e=>e.types).join(`
|
|
7
|
+
|
|
8
|
+
`);return e.length===0?t:`${t}\nexport declare const env: ${e.map(e=>e.environment).join(` & `)};`}var XS=new WeakMap;function ZS(e){let t=XS.get(e);if(t!==void 0)return t;let n=KS(e.path.replace(/\./g,`$`)),r=GS(e.input,`input`),i=e.output?GS(e.output,`output`):`unknown`,a=Object.freeze({indexEnvironment:qS(e.path,r,i),environment:qS(e.path,`${n}_Input`,`${n}_Output`),types:`export type ${n}_Input = ${r};\nexport type ${n}_Output = ${i};`});return XS.set(e,a),a}function QS(e){let t=zS(LS(e,`input`));if(t===!0||t===!1||!t.properties)return;let n={},r=!1,i=Object.entries(t.properties).sort(([e],[t])=>sS(e,t));for(let[e,t]of i){let i=zS(t);if(i===!0||i===!1)continue;let a=i.examples;if(a&&a.length>0){let t=aS.safeParse(a[0]);t.success&&(n[e]=t.data,r=!0)}else if(i.default!==void 0){let t=aS.safeParse(i.default);t.success&&(n[e]=t.data,r=!0)}}return r?n:void 0}function $S(e){return e&&e.length>0?e:void 0}function eC(e){let t=OS.safeParse(e);if(!t.success)throw new NS(`invalid_input`,`Description output exceeded its bounds`);return t.data}function tC(e,t){let n=e.find(e=>e.path===t.path);if(n){let e=`env.${n.path}`,t=aS.safeParse(LS(n.input,`input`));if(!t.success)throw new NS(`invalid_input`,`Schema cannot be projected to JSON Schema`);let r={path:n.path,description:$S(n.description),types:YS([ZS(n)]),kind:`operation`,inputSchema:t.data,usage:`await ${e}({ ... })`};if(r.types.length>2e4)throw new NS(`invalid_input`,`Operation description exceeds the bounded output`);return eC(r)}let r=`${t.path}.`,i=e.filter(e=>e.path.startsWith(r)).sort((e,t)=>sS(e.path,t.path));if(i.length===0)throw new NS(`unknown_target`,`Unknown target: ${t.path}`);let a=i[0];if(!a)throw new NS(`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?JS(i.map(ZS)):YS((o.length>0?o:i).map(ZS)),s.length>2e4)throw new NS(`invalid_input`,`Description types exceed the bounded output`);return eC({path:t.path,description:$S(a.instructions),types:s,kind:`module`})}function nC(e){let t=RS(e.input,`input`),n=e.output?RS(e.output,`output`):``;return Object.freeze({...e,fingerprint:pS(t+`
|
|
9
|
+
`+n),inputBytes:t.length,outputBytes:n.length,sample:QS(e.input)})}var rC={exact:14,startsWith:9,phrase:6,token:4,prefix:2,substring:2,includes:1},iC={path:12,namespace:8,method:10,description:5},aC=25,oC=10,sC=8,cC=20,lC=Math.max(aC,oC)+sC+cC,uC=1+Math.max(...Object.values(rC))*Math.max(...Object.values(iC))+lC;function dC(e){return pS([...e].sort((e,t)=>sS(e.path,t.path)).map(e=>JSON.stringify([e.path,e.description??null,e.capabilityNotes??null,e.instructions??null,e.fingerprint])).join(`
|
|
10
|
+
`))}function fC(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=lS(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 pC(e,t,n){let r=cS(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...fS(e)],s=`none`;for(let e of n){let t=fC(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=rC[s]*iC[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function mC(e,t){let n=cS(e);return[t,...fS(t)].some(e=>n.includes(e))}function hC(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 gC(e){let t=ES.safeParse(e);if(!t.success)throw new NS(`invalid_input`,`Search output exceeded its bounds`);return t.data}function _C(e){return[mS(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function vC(e){return gC({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function yC(e,t,n){let r=hS(e.path),i=mS(e.path),a=e.description??``,o=[e.path,r,i,a],s=pC(e.path,`path`,t),c=pC(r,`namespace`,t),l=pC(i,`method`,t),u=pC(a,`description`,t),d=n.filter(e=>o.some(t=>mC(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?aC:f*oC,ee=n[0];ee&&o.some(e=>mC(e,ee))&&(m+=sC),(s.level===`exact`||l.level===`exact`)&&(m+=cC);let te={path:e.path,score:d+(p+m)/uC};a&&(te.description=a);let ne=hC([[`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:_C(e),pathScore:s.score}}function bC(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||sS(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>sS(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||sS(e.path,t.path))}function xC(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return gC({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function SC(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=lS(cS(t)),o=a.filter(e=>!dS(e));if(o.length===0)return vC(r);let s=[];for(let t of e){let e=yC(t,a,o);e&&s.push(e)}return xC(bC(s),i,r)}var CC=cn({catalogStamp:DS.shape.catalogStamp,namespace:CS.shape.namespace.unwrap().nullable(),after:TS.shape.path});function wC(e,t,n){let r=CS.safeParse(n);if(!r.success)throw new NS(`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)=>sS(hS(e.path),hS(t.path))||sS(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=CC.parse(JSON.parse(i.cursor))}catch(e){throw new NS(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new NS(`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 NS(`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 DS.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 TC=1e6;function EC(e,t=0){if(t>=16)return e.length===0?t:t+1;let n=t;for(let r=e.length-1;r>=0;--r){let i=e[r],a=t+1;if(Array.isArray(i)?a=EC(i,a):_r(i)&&(a=EC(Object.values(i),a)),n=Math.max(n,a),n>16)return n}return n}function DC(e){let t=MS.safeParse(e);if(!t.success)throw new NS(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new NS(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>sS(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new NS(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),RS(e.input,`input`).length>2e4||EC(Object.values(LS(e.input,`input`)))>16)throw new NS(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?RS(e.output,`output`).length:0)>2e4||e.output!==void 0&&EC(Object.values(LS(e.output,`output`)))>16)throw new NS(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=nC(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||yS(n,0)>16))throw new NS(`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>TC)throw new NS(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function OC(e){let t=DC(e),n=Object.freeze(t.operations),r=dC(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=xS.safeParse(e);if(!t.success)throw new NS(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new NS(`empty_query`,`Search query must not be empty`);return SC(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=SS.safeParse(e);if(!t.success)throw new NS(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new NS(`empty_query`,`Description target must not be empty`);return tC(n,t.data)},list:e=>wC(i,r,e),stamp:()=>r})}var kC=v(()=>w().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),AC=v(()=>ui(w(),yn()));v(()=>ei([AC,mr()]));var jC=v(()=>g({tool:kC,title:w().max(120),description:w().max(1e3),input:ui(w(),yn()),output:ui(w(),yn()),call:ui(w(),yn())}).catchall(yn()));v(()=>mn(`kind`,[cn({kind:x(`unindexed`)}),cn({kind:x(`ready`),tools:Dr(jC).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var MC=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:xS,output:ES}),NC=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:SS,output:OS}),PC=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:CS,output:DS});Object.freeze({createCatalog:OC,forageSearchDefinition:MC,forageDescribeDefinition:NC,forageListDefinition:PC});var FC=`invalid_definition`,IC=`runtime_closed`,LC=`source_failure`,K=class extends Error{code=FC;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},RC=class extends Error{code=IC;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},zC=class extends Error{sourceId;phase;code=LC;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`}},BC=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},VC=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},HC=class extends Sa(`SourceInvalid`){},UC=class extends Sa(`GuestThrew`){},WC=class extends Sa(`DeadlineExceeded`){},GC=class extends Sa(`SandboxBusy`){code=`sandbox-busy`},KC=class extends Sa(`Cancelled`){},qC=class extends Sa(`DispatchLost`){},JC=class extends Sa(`SandboxCrashed`){},YC=class extends Sa(`BadResponse`){},XC=class extends Sa(`ResultTooLarge`){},ZC=class extends Sa(`ResultNotJson`){},QC=class extends Sa(`CapabilityFailed`){constructor(e){super(e),this.message=tw(this)}},$C=class extends Sa(`Unknown`){};function ew(e,t){switch(e._tag){case`SourceInvalid`:return new HC({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new UC({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new WC({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new GC({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new KC({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new qC({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new JC({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new YC({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new XC({size:e.size,ref:t});case`ResultNotJson`:return new ZC({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new QC({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new $C({rawCause:e.rawCause,ref:t})}}function tw(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 nw=v(()=>ei([e(HC),e(UC),e(WC),e(GC),e(KC),e(qC),e(JC),e(YC),e(XC),e(ZC),e(QC),e($C)])),rw=v(()=>St().pipe(ei([e(Error).transform(e=>({kind:`error`,value:e})),Cn().transform(e=>({kind:`null`,value:e})),Rr().transform(e=>({kind:`undefined`,value:e})),w().transform(e=>({kind:`string`,value:e})),mr().transform(e=>({kind:`boolean`,value:e})),ei([jn(),Ln(),x(1/0),x(-1/0)]).transform(e=>({kind:`number`,value:e})),tn().transform(e=>({kind:`bigint`,value:e})),gt().transform(e=>({kind:`symbol`,value:e})),e(Function).transform(e=>({kind:`function`,value:e})),Dr(St()).transform(e=>({kind:`array`,value:e})),ei([e(Object),ui(w(),St())]).transform(e=>({kind:`object`,value:e})),St().transform(()=>({kind:`opaque`}))])));function iw(e){return nw.safeParse(e).success}function aw(e){let t=nw.safeParse(e);return t.success?t.data:new $C({rawCause:e})}function ow(e){let t=rw.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}v(()=>yn().optional());function sw(e){return cw(e,new Set)}function cw(e,t){let n=rw.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=>cw(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,cw(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=cw(r.cause,t)),r instanceof AggregateError&&(e.errors=cw(r.errors,t))}return e}finally{t.delete(e)}}}}var lw=v(()=>g({name:x(`ReferenceError`),message:w().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));v(()=>ei([lw,g({name:w(),message:w()})]).and(g({transportMessage:w().max(512).optional()})));var uw=v(()=>cn({v:x(1),kind:x(`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)})),dw=D(U(Hm)),fw=v(()=>w().transform((e,t)=>{let n=dw(e);return je(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),rr):n.success})).pipe(uw);cn({error:fw}),v(()=>St().pipe(ei([x(`Execution timed out`).transform(()=>({kind:`deadline`})),St().transform(e=>({kind:`bad_response`,rawCause:e}))])));var pw=cn({sandboxCapacity:Ur().positive().optional(),admissionWaitMs:Ur().min(1).max(9e5).optional()});function mw(e,t){let n=pw.safeParse(e??{}),r=Ur().positive().safeParse(t??2);if(!n.success||!r.success)throw new K(`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 hw=[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],gw=[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],_w=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,vw=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,yw={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`},bw=`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`,xw={5:bw,"5module":bw+` export import`,6:bw+` const class extends export import super`},Sw=/^in(stanceof)?$/,Cw=RegExp(`[`+vw+`]`),ww=RegExp(`[`+vw+_w+`]`);function Tw(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 Ew(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&Cw.test(String.fromCharCode(e)):t!==!1&&Tw(e,gw)}function Dw(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&&ww.test(String.fromCharCode(e)):t===!1?!1:Tw(e,gw)||Tw(e,hw)}var Ow=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 kw(e,t){return new Ow(e,{beforeExpr:!0,binop:t})}var Aw={beforeExpr:!0},jw={startsExpr:!0},Mw={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,Mw[e]=new Ow(e,t)}var J={num:new Ow(`num`,jw),regexp:new Ow(`regexp`,jw),string:new Ow(`string`,jw),name:new Ow(`name`,jw),privateId:new Ow(`privateId`,jw),eof:new Ow(`eof`),bracketL:new Ow(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new Ow(`]`),braceL:new Ow(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new Ow(`}`),parenL:new Ow(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new Ow(`)`),comma:new Ow(`,`,Aw),semi:new Ow(`;`,Aw),colon:new Ow(`:`,Aw),dot:new Ow(`.`),question:new Ow(`?`,Aw),questionDot:new Ow(`?.`),arrow:new Ow(`=>`,Aw),template:new Ow(`template`),invalidTemplate:new Ow(`invalidTemplate`),ellipsis:new Ow(`...`,Aw),backQuote:new Ow("`",jw),dollarBraceL:new Ow("${",{beforeExpr:!0,startsExpr:!0}),eq:new Ow(`=`,{beforeExpr:!0,isAssign:!0}),assign:new Ow(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new Ow(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new Ow(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:kw(`||`,1),logicalAND:kw(`&&`,2),bitwiseOR:kw(`|`,3),bitwiseXOR:kw(`^`,4),bitwiseAND:kw(`&`,5),equality:kw(`==/!=/===/!==`,6),relational:kw(`</>/<=/>=`,7),bitShift:kw(`<</>>/>>>`,8),plusMin:new Ow(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:kw(`%`,10),star:kw(`*`,10),slash:kw(`/`,10),starstar:new Ow(`**`,{beforeExpr:!0}),coalesce:kw(`??`,1),_break:q(`break`),_case:q(`case`,Aw),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,Aw),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,Aw),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,jw),_if:q(`if`),_return:q(`return`,Aw),_switch:q(`switch`),_throw:q(`throw`,Aw),_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`,jw),_super:q(`super`,jw),_class:q(`class`,jw),_extends:q(`extends`,Aw),_export:q(`export`),_import:q(`import`,jw),_null:q(`null`,jw),_true:q(`true`,jw),_false:q(`false`,jw),_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})},Nw=/\r\n?|\n|\u2028|\u2029/,Pw=new RegExp(Nw.source,`g`);function Fw(e){return e===10||e===13||e===8232||e===8233}function Iw(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(Fw(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var Lw=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,Rw=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,zw=Object.prototype,Bw=zw.hasOwnProperty,Vw=zw.toString,Hw=Object.hasOwn||(function(e,t){return Bw.call(e,t)}),Uw=Array.isArray||(function(e){return Vw.call(e)===`[object Array]`}),Ww=Object.create(null);function Gw(e){return Ww[e]||(Ww[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function Kw(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var qw=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,Jw=function(e,t){this.line=e,this.column=t};Jw.prototype.offset=function(e){return new Jw(this.line,this.column+e)};var Yw=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function Xw(e,t){for(var n=1,r=0;;){var i=Iw(e,r,t);if(i<0)return new Jw(n,t-r);++n,r=i}}var Zw={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},Qw=!1;function $w(e){var t={};for(var n in Zw)t[n]=e&&Hw(e,n)?e[n]:Zw[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!Qw&&typeof console==`object`&&console.warn&&(Qw=!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),Uw(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}if(Uw(t.onComment)&&(t.onComment=eT(t,t.onComment)),t.sourceType===`commonjs`&&t.allowAwaitOutsideFunction)throw Error(`Cannot use allowAwaitOutsideFunction with sourceType: commonjs`);return t}function eT(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 Yw(this,o,s)),e.ranges&&(c.range=[i,a]),t.push(c)}}var tT=1,nT=2,rT=4,iT=8,aT=16,oT=32,sT=64,cT=128,lT=256,uT=512,dT=1024,fT=tT|nT|lT;function pT(e,t){return nT|(e?rT:0)|(t?iT:0)}var mT=0,hT=1,gT=2,_T=3,vT=4,yT=5,bT=function(e,t,n){this.options=e=$w(e),this.sourceFile=e.sourceFile,this.keywords=Gw(xw[e.ecmaVersion>=6?6:e.sourceType===`module`?`5module`:5]);var r=``;e.allowReserved!==!0&&(r=yw[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType===`module`&&(r+=` await`)),this.reservedWords=Gw(r);var i=(r?r+` `:``)+yw.strict;this.reservedWordsStrict=Gw(i),this.reservedWordsStrictBind=Gw(i+` `+yw.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(Nw).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`?nT:tT),this.regexpState=null,this.privateNameStack=[]},xT={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}};bT.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},xT.inFunction.get=function(){return(this.currentVarScope().flags&nT)>0},xT.inGenerator.get=function(){return(this.currentVarScope().flags&iT)>0},xT.inAsync.get=function(){return(this.currentVarScope().flags&rT)>0},xT.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(lT|uT))return!1;if(t&nT)return(t&rT)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},xT.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&tT)},xT.allowSuper.get=function(){return(this.currentThisScope().flags&sT)>0||this.options.allowSuperOutsideMethod},xT.allowDirectSuper.get=function(){return(this.currentThisScope().flags&cT)>0},xT.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},xT.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(lT|uT)||t&nT&&!(t&aT))return!0}return!1},xT.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&dT||!this.inModule&&e&tT)},xT.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&lT)>0},bT.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},bT.parse=function(e,t){return new this(t,e).parse()},bT.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},bT.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(bT.prototype,xT);var ST=bT.prototype,CT=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;ST.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){Rw.lastIndex=e,e+=Rw.exec(this.input)[0].length;var t=CT.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){Rw.lastIndex=e+t[0].length;var n=Rw.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||Nw.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,Rw.lastIndex=e,e+=Rw.exec(this.input)[0].length,this.input[e]===`;`&&e++}},ST.eat=function(e){return this.type===e&&(this.next(),!0)},ST.isContextual=function(e){return this.type===J.name&&this.value===e&&!this.containsEsc},ST.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},ST.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}},ST.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},ST.canInsertSemicolon=function(){return this.type===J.eof||this.type===J.braceR||Nw.test(this.input.slice(this.lastTokEnd,this.start))},ST.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},ST.semicolon=function(){!this.eat(J.semi)&&!this.insertSemicolon()&&this.unexpected()},ST.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},ST.expect=function(e){this.eat(e)||this.unexpected()},ST.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var wT=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};ST.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`)}},ST.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`)},ST.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`)},ST.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var Y=bT.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 TT={kind:`loop`},ET={kind:`switch`};Y.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;Rw.lastIndex=this.pos;var t=Rw.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(Ew(r)){var i=n;do n+=r<=65535?1:2;while(Dw(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!Sw.test(a))return!0}return!1},Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;Rw.lastIndex=this.pos;var e=Rw.exec(this.input),t=this.pos+e[0].length,n;return!Nw.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(Dw(n=this.fullCharCodeAt(t+8))||n===92))},Y.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;Rw.lastIndex=this.pos;var n=Rw.exec(this.input),r=this.pos+n[0].length;if(Nw.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||Dw(a=this.fullCharCodeAt(i))||a===92)return!1;Rw.lastIndex=i;var o=Rw.exec(this.input);if(r=i+o[0].length,o&&Nw.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!Ew(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(Dw(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(Sw.test(l))return!1;if(t&&!e&&l===`of`){Rw.lastIndex=r;var u=Rw.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){Rw.lastIndex=this.pos;var o=Rw.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(TT),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(TT),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 wT,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,OT|(n?0:kT),!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(ET),this.enterScope(dT);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(),Nw.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 DT=[];Y.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?oT:0),this.checkLValPattern(e,t?vT:gT),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(TT),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`?hT:gT,!1)};var OT=1,kT=2,AT=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&kT&&this.unexpected(),e.generator=this.eat(J.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&OT&&(e.id=t&AT&&this.type!==J.name?null:this.parseIdent(),e.id&&!(t&kT)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?hT:gT:_T));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(pT(e.async,e.generator)),t&OT||(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&OT?`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`&&jT(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&&MT(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&&MT(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 MT(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&MT(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(J.eq)?(this.enterScope(uT|sT),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(lT|sT);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,gT,!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];Hw(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function jT(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 MT(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,OT|AT,!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),Hw(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=DT,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,gT),this.finishNode(e,`ImportSpecifier`)},Y.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,gT),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,gT),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;Hw(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 qw.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 NT=bT.prototype;NT.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},NT.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},NT.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},NT.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`)},NT.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()},NT.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},NT.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},NT.parseBindingListItem=function(e){return e},NT.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`)},NT.checkLValSimple=function(e,t,n){t===void 0&&(t=mT);var r=t!==mT;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===gT&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(Hw(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==yT&&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`)}},NT.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=mT),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)}},NT.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=mT),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 PT=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},FT={b_stat:new PT(`{`,!1),b_expr:new PT(`{`,!0),b_tmpl:new PT("${",!1),p_stat:new PT(`(`,!1),p_expr:new PT(`(`,!0),q_tmpl:new PT("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new PT(`function`,!1),f_expr:new PT(`function`,!0),f_expr_gen:new PT(`function`,!0,!1,null,!0),f_gen:new PT(`function`,!1,!1,null,!0)},IT=bT.prototype;IT.initialContext=function(){return[FT.b_stat]},IT.curContext=function(){return this.context[this.context.length-1]},IT.braceIsBlock=function(e){var t=this.curContext();return t===FT.f_expr||t===FT.f_stat?!0:e===J.colon&&(t===FT.b_stat||t===FT.b_expr)?!t.isExpr:e===J._return||e===J.name&&this.exprAllowed?Nw.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===FT.b_stat:e===J._var||e===J._const||e===J.name?!1:!this.exprAllowed},IT.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},IT.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},IT.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===FT.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)?FT.b_stat:FT.b_expr),this.exprAllowed=!0},J.dollarBraceL.updateContext=function(){this.context.push(FT.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?FT.p_stat:FT.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()===FT.p_stat)&&!(e===J._return&&Nw.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==J.colon&&e!==J.braceL||this.curContext()!==FT.b_stat)?this.context.push(FT.f_expr):this.context.push(FT.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()===FT.q_tmpl?this.context.pop():this.context.push(FT.q_tmpl),this.exprAllowed=!1},J.star.updateContext=function(e){if(e===J._function){var t=this.context.length-1;this.context[t]===FT.f_expr?this.context[t]=FT.f_expr_gen:this.context[t]=FT.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=bT.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 wT,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`&<(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&RT(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 LT(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&<(e.expression)}function RT(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&RT(e.expression)||e.type===`ParenthesizedExpression`&&RT(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 wT,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(FT.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(FT.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 wT,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 zT=[];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):zT,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
|
+
`),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)&&!Nw.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(pT(t,r.generator)|sT|(n?cT: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(pT(n,!1)|aT),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,yT),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,hT,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&fT)&&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 BT=bT.prototype;BT.raise=function(e,t){var n=Xw(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},BT.raiseRecoverable=BT.raise,BT.curPosition=function(){if(this.options.locations)return new Jw(this.curLine,this.pos-this.lineStart)};var VT=bT.prototype,HT=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};VT.enterScope=function(e){this.scopeStack.push(new HT(e))},VT.exitScope=function(){this.scopeStack.pop()},VT.treatFunctionsAsVarInScope=function(e){return e.flags&nT||!this.inModule&&e.flags&tT},VT.declareName=function(e,t,n){var r=!1;if(t===gT){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&tT&&delete this.undefinedExports[e]}else if(t===vT)this.currentScope().lexical.push(e);else if(t===_T){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&oT&&s.lexical[0]===e)||!this.treatFunctionsAsVarInScope(s)&&s.functions.indexOf(e)>-1){r=!0;break}if(s.var.push(e),this.inModule&&s.flags&tT&&delete this.undefinedExports[e],s.flags&fT)break}r&&this.raiseRecoverable(n,`Identifier '`+e+`' has already been declared`)},VT.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)},VT.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},VT.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(fT|uT|lT))return t}},VT.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(fT|uT|lT)&&!(t.flags&aT))return t}};var UT=function(e,t,n){this.type=``,this.start=t,this.end=0,e.options.locations&&(this.loc=new Yw(e,n)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},WT=bT.prototype;WT.startNode=function(){return new UT(this,this.start,this.startLoc)},WT.startNodeAt=function(e,t){return new UT(this,e,t)};function GT(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}WT.finishNode=function(e,t){return GT.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},WT.finishNodeAt=function(e,t,n,r){return GT.call(this,e,t,n,r)},WT.copyNode=function(e){var t=new UT(this,e.start,this.startLoc);for(var n in e)t[n]=e[n];return t};var KT=`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`,qT=`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`,JT=qT+` Extended_Pictographic`,YT=JT,XT=YT+` EBase EComp EMod EPres ExtPict`,ZT=XT,QT={9:qT,10:JT,11:YT,12:XT,13:ZT,14:ZT},$T={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`},eE=`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`,tE=`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`,nE=tE+` Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd`,rE=nE+` Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho`,iE=rE+` Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi`,aE=iE+` Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith`,oE={9:tE,10:nE,11:rE,12:iE,13:aE,14:aE+` `+KT},sE={};function cE(e){var t=sE[e]={binary:Gw(QT[e]+` `+eE),binaryOfStrings:Gw($T[e]),nonBinary:{General_Category:Gw(eE),Script:Gw(oE[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 lE=0,uE=[9,10,11,12,13,14];lE<uE.length;lE+=1){var dE=uE[lE];cE(dE)}var Z=bT.prototype,fE=function(e,t){this.parent=e,this.base=t||this};fE.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},fE.prototype.sibling=function(){return new fE(this.parent,this.base)};var pE=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=sE[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};pE.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)},pE.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,`Invalid regular expression: /`+this.source+`/: `+e)},pE.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},pE.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},pE.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)},pE.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},pE.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)},pE.prototype.eat=function(e,t){return t===void 0&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},pE.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 mE(e){for(var t in e)return!0;return!1}Z.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&mE(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 fE(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&&hE(n);)t+=Kw(n),e.advance();return t};function hE(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 gE(t)?(e.lastIntValue=t,e.advance(),!0):!1};function gE(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&&!gE(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+=Kw(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=Kw(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),_E(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function _E(e){return Ew(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),vE(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function vE(e){return Dw(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&&!AE(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 yE(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function yE(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)&&bE(e.lastIntValue))return!0;r&&e.raise(`Invalid unicode escape`),e.pos=n}return!1};function bE(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 xE=0,SE=1,CE=2;Z.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(wE(t))return e.lastIntValue=-1,e.advance(),SE;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===CE&&e.raise(`Invalid property name`),r;e.raise(`Invalid property name`)}return xE};function wE(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),SE}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return xE},Z.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){Hw(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 SE;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return CE;e.raise(`Invalid property name`)},Z.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue=``;TE(t=e.current());)e.lastStringValue+=Kw(t),e.advance();return e.lastStringValue!==``};function TE(e){return yE(e)||e===95}Z.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue=``;EE(t=e.current());)e.lastStringValue+=Kw(t),e.advance();return e.lastStringValue!==``};function EE(e){return TE(e)||AE(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===CE&&e.raise(`Negated character class may contain strings`),!0}return!1},Z.regexp_classContents=function(e){return e.current()===93?SE:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),SE)},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||NE(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=SE,n;if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e)){n===CE&&(t=CE);for(var r=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(n=this.regexp_eatClassSetOperand(e))){n!==CE&&(t=SE);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===CE&&(t=CE)}},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)?SE: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===CE&&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)===CE&&(t=CE);return t},Z.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?SE:CE},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()&&DE(n)||OE(n)?!1:(e.advance(),e.lastIntValue=n,!0)};function DE(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 OE(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 kE(t)?(e.lastIntValue=t,e.advance(),!0):!1};function kE(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 AE(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;AE(n=e.current());)e.lastIntValue=10*e.lastIntValue+(n-48),e.advance();return e.pos!==t};function AE(e){return e>=48&&e<=57}Z.regexp_eatHexDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;jE(n=e.current());)e.lastIntValue=16*e.lastIntValue+ME(n),e.advance();return e.pos!==t};function jE(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function ME(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 NE(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function NE(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(!jE(i))return e.pos=n,!1;e.lastIntValue=16*e.lastIntValue+ME(i),e.advance()}return!0};var PE=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new Yw(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},Q=bT.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 PE(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 PE(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 Ew(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=Iw(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&&!Fw(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&&Lw.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||Nw.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(),Ew(t,!0)||t===92))return this.finishToken(J.privateId,this.readWord1());this.raise(this.pos,`Unexpected character '`+Kw(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 '`+Kw(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(Nw.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 pE(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 FE(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,``))}function IE(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=IE(this.input.slice(t,this.pos)),++this.pos):Ew(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=IE(this.input.slice(t,this.pos));return++this.pos,Ew(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`)),Ew(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`);var a=FE(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)):(Fw(r)&&this.raise(this.start,`Unterminated string constant`),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(J.string,t)};var LE={};Q.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===LE)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},Q.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw LE;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(Fw(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
|
+
`;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
|
+
`&&++this.pos;case`
|
|
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 Kw(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 Fw(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(Dw(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?Ew:Dw)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=Kw(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=Mw[e]),this.finishToken(t,e)},bT.acorn={Parser:bT,version:`8.18.0`,defaultOptions:Zw,Position:Jw,SourceLocation:Yw,getLineInfo:Xw,Node:UT,TokenType:Ow,tokTypes:J,keywordTypes:Mw,TokContext:PT,tokContexts:FT,isIdentifierChar:Dw,isIdentifierStart:Ew,Token:PE,isNewLine:Fw,lineBreak:Nw,lineBreakG:Pw,nonASCIIwhitespace:Lw};function RE(e,t){return bT.parse(e,t)}v(()=>mn(`ok`,[cn({ok:x(!0),value:St()}),cn({ok:x(!1),error:cn({kind:x(`guest_threw`),name:w().max(80),message:w().max(512),transportMessage:w().max(512).optional()})})]));var zE=v(()=>w().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),BE=zE.refine(e=>{if(e===`env`)return!1;try{return RE(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);v(()=>ui(BE,Dr(zE).min(1))),v(()=>ui(BE,Dr(w().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var VE=L([`read`,`write`]),HE=Gm,UE=P({access:A(VE),confirm:A(HE)}),WE=L([`none`,`read`,`write`]),GE=D(UE),KE=D(WE);function qE(e){let t=GE({access:e.access,confirm:e.confirm});if(je(t))throw new K(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function JE(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 YE(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:JE(e,t)})}function XE(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=KE(i[n]);return Wt(a)?a.success:`none`}async function ZE(e,t,n,r,i){let a=await QE(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function QE(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=$E(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?YE(`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(),$E(e,t,n)):YE(`declined`,n)}function $E(e,t,n){let r=XE(e,t,n.module);if(r===`none`)return YE(`not-granted`,n);if(r===`read`&&n.access!==`read`)return YE(`read-only`,n)}function eD(e,t,n){let r={module:e.module,operation:e.descriptor.name,...qE(e)};return{...e,prepare:i=>fn({try:e=>ZE(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(T(t=>t===void 0?e.prepare(i):S({execute:()=>Cb({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var tD=oc();async function nD(e){let t=await Kn(e);if(Ga(t))return{value:t.value};let n=Ma(t.cause);if(je(n))throw ja(t.cause);return{issues:tD(n.success.issue).issues}}function rD(e){let t=Pg(e),n=Cm(t)[`~standard`].jsonSchema,r=Tm(t),i=Am(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>nD(r(e)),encode:e=>nD(i(e))})}function iD(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function aD(e){return Lm(e)?rD(e):iD(e)}var oD=Symbol(`mycelium.operation`),sD=Symbol(`mycelium.module`),cD=new WeakMap,lD=new WeakMap;function uD(e){let t=Object.freeze({[oD]:!0}),n=aD(e.input),r=e.output===void 0?void 0:aD(e.output),i={replay:e.replay??`unsafe`,...qE(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new BC(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 YC({reason:`Capability output failed its declared schema`,rawCause:new VC(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 cD.set(t,a),t}function dD(e){let t=Dr(zE).safeParse(e.namespace??[]);if(!t.success)throw new K(`Invalid module namespace`);let n=Object.freeze({[sD]:!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 lD.set(n,i),n}function fD(e){return lD.has(e)}function pD(e){return cD.get(e)}function mD(e){return lD.get(e)}function hD(e,t,n){let r=mD(e);if(r===void 0)throw new K(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(fD(a)){let n=mD(a);if(n===void 0)throw new K(`Unknown child module registration`);i[e]=hD(a,t,[r,...n.namespace].join(`.`));continue}let o=pD(a);if(o===void 0)throw new K(`Unknown operation registration: ${e}`);let s=Object.freeze({[oD]:!0});cD.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 gD(dD(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 gD(e,t){let n=mD(e);if(n===void 0)throw new K(`Unknown module registration`);let r=Object.freeze({[sD]:!0});return lD.set(r,Object.freeze({...n,grantKey:t})),r}function _D(e,t){if(t.length===0||t.length>160)throw new K(`Grant key must be non-empty and bounded`);return gD(e,t)}function vD(e,t){return hD(e,t,``)}function yD(e,t){return e<t?-1:+(e>t)}function bD(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var xD=160;function SD(e){if(e.length===0||e.length>xD)throw new K(`Module id must be non-empty and bounded`)}function CD(e){if(!e.split(`.`).every(e=>zE.safeParse(e).success))throw new K(`Operation key must be a path segment or a dotted relative path`)}function wD(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function TD(e){let t=wD(e);return BE.safeParse(t).success?t:`module_${t}`}function ED(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`?wD(i.name):TD(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 DD=14695981039346656037n,OD=1099511628211n,kD=18446744073709551615n;function AD(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*OD&kD,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*OD&kD,n=(n^BigInt(r>>>8&255))*OD&kD}return n}function jD(e,t,n){let r=AD(DD,e),i=[...t.entries()].sort(([e],[t])=>yD(e,t));for(let[e,t]of i)r=AD(r,e),r=AD(r,t);let a=[...n].sort((e,t)=>yD(e.id,t.id));for(let e of a)r=AD(r,e.id),r=AD(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function MD(){return[NC,MC,PC]}function ND(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(CD(t),fD(o)){let s=mD(o);if(s===void 0)throw new K(`Unknown child module registration`);return ND(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=pD(o);if(s===void 0)throw new K(`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 PD(e,t=[]){let n=e.map(e=>{let t=mD(e);if(t===void 0)throw new K(`Unknown module registration`);return SD(t.id),t}).sort((e,t)=>yD(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new K(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=ED(n,`transport`),a=ED(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new K(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new K(`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 K(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new K(`Missing namespace path: ${e.id}`);return ND(e.grantKey,e,t,n,e.description)}).sort((e,t)=>yD(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new K(`Duplicate operation path`);for(let e of MD()){if(c.has(e.path))throw new K(`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 K(`Operation conflicts with namespace: ${e}`)}let l;try{l=OC({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}),...MD()]})}catch(e){throw new K(bD(e))}let u=jD(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 FD(){return null}var ID=yn(),LD=v(()=>ei([Cn(),w(),mr(),jn()])),RD=v(()=>ui(w(),St())),zD=v(()=>pw.extend({timeoutMs:jn().int().min(1).max(9e5).optional(),abortGraceMs:jn().int().min(1).max(3e4).optional()}).optional()),BD=64,VD=262144,HD=new TextEncoder,UD=e=>{e(S(void 0))};function WD(e){let t=zD.safeParse(e);if(!t.success)throw new K(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...mw({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function GD(e){return b(function*(){let t=yield*cy(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=$n(t=>e===0?(t(S(void 0)),Vn(()=>void 0)):(n.add(t),Vn(()=>n.delete(t))));return Object.freeze({start:r=>te(i=>Vn(()=>{e+=1}).pipe(_(ne(i(t.withPermits(1)(r)).pipe(ar(Vn(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(UD)}}))))))),awaitIdle:r})}})})}function KD(e,t=0){if(t>BD)throw Error(`JSON value exceeds the nesting bound`);let n=LD.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>KD(e,t+1));let r=RD.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,KD(n,t+1)]))}function qD(e){return ID.parse(KD(e))}function JD(e){let t=JSON.stringify(qD(e)),n=HD.encode(t).byteLength;if(n>VD)throw new XC({size:n});return Object.freeze({text:t})}function YD(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 qD(await r(i))}catch(t){throw iw(t)?t:t instanceof NS?new QC({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof BC?new QC({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Ar({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function XD(e){return $n(t=>{let n=t.bind(void 0,ii);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),Vn(e.removeEventListener.bind(e,`abort`,n))})}function ZD(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 QD(e,t,n){return e===`deadline_exceeded`?new WC({limitMs:t,elapsedMs:n??0}):new KC({by:`caller`})}function $D(e){return go.pipe(Te(t=>t-e))}function eO(e){return go.pipe(T(t=>lr(()=>{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 GC({capacity:e.policy.capacity,waitedMs:Math.max(0,t-i)});return a={kind:`refused`,failure:n},n},l=()=>{if(r.signal.aborted)throw QD(o,e.policy.timeoutMs)},u=ZD(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=lr(()=>go.pipe(T(u=>a.kind===`refused`?y(a.failure):(u>=d&&s(`deadline_exceeded`),r.signal.aborted?$D(t).pipe(T(t=>y(QD(o,e.policy.timeoutMs,t)))):u>=i+e.policy.waitMs?y(c(u)):(a={kind:`admitted`},e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:YD(e.createBindings(p),l),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(Hr(e=>ka(e)?Zt(e):y(aw(ja(e)))))))))),ee=t=>ey(t).pipe(mi({duration:e.policy.abortGraceMs,orElse:()=>y(o===`deadline_exceeded`?new WC({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new KC({by:`caller`,acknowledged:!1}))})),te,ne=!1,re=r=>(ne=!0,$D(t).pipe(T(t=>{let i=aw(r),a=i instanceof WC?new WC({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=ew(a,n),s=ui(w(),yn()).parse(sw(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??FD(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=lr(()=>e.sandbox.onFailure?.(c)??ii);return rt(`sandbox_failure`,c).pipe(pr({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),_(o._tag===`Unknown`?Xo(Zo(Yo(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(_(rt(`sandbox_health_alert`).pipe(pr({ref:n,adapter:c.adapter})))):ii),_(l.pipe(Hr(e=>rt(`sandbox_failure_record_failed`,e)))),Mr(o))})));return b(function*(){if(r.signal.aborted){let n=yield*$D(t);return yield*y(QD(o,e.policy.timeoutMs,n))}i=yield*go,te=yield*e.backingWork.start(m);let n=yield*go,l=An(Math.max(0,i+e.policy.waitMs-n)).pipe(_(go),T(e=>a.kind===`admitted`?Pt:a.kind===`refused`?S({kind:`busy`,failure:a.failure}):r.signal.aborted?S({kind:`cancelled`}):e>=d?(s(`deadline_exceeded`),S({kind:`deadline`})):S({kind:`busy`,failure:c(e)}))),u=yield*En(Qv(te).pipe(Te(e=>Object.freeze({kind:`settled`,exit:e}))),En(An(Math.max(0,d-n)).pipe(_(Vn(()=>(s(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),En(XD(r.signal).pipe(Mr(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(_(y(f)));if(u.kind===`settled`&&o===void 0)return yield*Se(u.exit,{onFailure:Zt,onSuccess:e=>li({try:()=>JD(e),catch:t=>iw(t)?t:new ZC({kind:ow(e),rawCause:t})})});u.kind===`deadline`&&s(`deadline_exceeded`);let p=yield*$D(t);return yield*ee(te).pipe(_(y(QD(o,e.policy.timeoutMs,p))))}).pipe(Ae(()=>(s(`cancelled`),(te===void 0?ii:ey(te).pipe(Qr(e.policy.abortGraceMs),pn)).pipe(_(lr(()=>ne?ii:re(new KC({by:`operator`})).pipe(pn))))))).pipe(vn(e=>re(e).pipe(T(y))),ar(Vn(u)))})))}var tO=nh(()=>I([Wm,Um,Gm,N,M,Cg,mh(AbortSignal),F(tO),nO])),nO=Ym(M,tO);function rO(e){return O(nO)(e)}var iO=new Map([[`openai`,`OpenAI`],[`openai-codex`,`OpenAI`],[`anthropic`,`Anthropic`],[`cloudflare-workers-ai`,`Cloudflare Workers AI`]]),aO=Ym(M,Fg),oO=O(P({samplingParams:k(aO),samplingParamsByThinkingLevel:k(P({off:k(aO),minimal:k(aO),low:k(aO),medium:k(aO),high:k(aO),xhigh:k(aO),max:k(aO)}))}));function sO(e){return{...e,...oO(e)}}function cO(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(rO(e),sO(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(rO(e),sO(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,sO(t))),a}function lO(e){let t=new Set,n=[];for(let r of e.messages){if(r.role===`toolResult`){t.delete(r.toolCallId)&&n.push(r);continue}if(r.role!==`system`&&t.clear(),r.role===`assistant`){if(r.stopReason===`error`||r.stopReason===`aborted`)continue;for(let e of r.content)e.type===`toolCall`&&t.add(e.id)}n.push(r)}return vi({...e,messages:n})}var uO=async(e,t,n)=>{let{streamSimple:r}=await yi(async()=>{let{streamSimple:e}=await import(`./compat-CxZajpXB.js`);return{streamSimple:e}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]));return r(e,lO(t),cO(n))},dO=P({error:P({code:A(M),type:A(M)})});Dm(P({type:j(`response.failed`),response:dO})),Dm(U(dO)),Dm(P({type:j(`error`),status:A(N.check(zh(),Lh({minimum:100,maximum:599}))),code:A(M),error:A(dO.fields.error)})),O(mh(Uint8Array)),Dm(yg.check(Lh({minimum:0,maximum:60}))),Dm(yg.check(zh(),Lh({minimum:0,maximum:864e10}))),Dm(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Dm(j(`rejected`)),Dm(j(`0`)),Dm(Ag),Dm(P({type:j(`error`),error:P({type:j(`overloaded_error`)})}));var fO=[/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],pO=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,mO=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function hO(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!mO.some(t=>t.test(e.errorMessage))&&(fO.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&pO.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 gO(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function _O(e){return new RegExp(e.join(`|`),`i`)}var vO=_O([`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])`]),yO=_O([`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`]),bO=6e4;function xO(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 SO=class extends Error{constructor(){super(`Aborted`)}};function CO(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new SO);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new SO)},{once:!0})})}async function wO(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||!TO(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=xO(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await CO(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof SO){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function TO(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!vO.test(t)&&yO.test(t)}var EO=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`])})])}),DO={assign:0,create:0,clone:0,discard:0,update:0};function OO(e){return AO(e,null)}function kO(e){return AO(typeof e,`object`)&&!OO(e)}function AO(e,t){return e===t}function jO(e){return AO(e,`__proto__`)||AO(e,`constructor`)||AO(e,`prototype`)}function MO(e,t){return jO(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function NO(e){return Object.getOwnPropertyNames(e)}var PO={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function FO(){return PO}function IO(e){return FO().immutableTypes?Object.freeze(e):e}function LO(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 RO(e,t){return{...e,...t}}function zO(e,t,n={}){DO.create+=1;let r=RO(t,n);return IO(FO().enumerableKind?RO(r,e):LO(r,e))}function BO(e){return kO(e)}function VO(e){return BO(e)&&MO(e,`~optional`)}function HO(e){return NO(e).filter(t=>!VO(e[t]))}function UO(e,t={}){let n=HO(e);return zO({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var WO;(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`})(WO||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var GO=new Float64Array(1);new DataView(GO.buffer),new Uint8Array(GO.buffer),new TextEncoder;var KO=`-?(?:0|[1-9][0-9]*)`,qO=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function JO(e){return zO({"~kind":`String`},{type:`string`},e)}var YO=`^${KO}$`;`${qO}`;function XO(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var ZO=[...XO(97,122),...XO(65,90)],QO=[`0`,...XO(49,57)];[...QO],[...ZO,...QO],[...QO],new RegExp(YO);var $O={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},ek={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},tk=1e3,nk=Symbol(`Mule model limit`),rk=Symbol(`Mule model attempt limit`);function ik(e,t){return hO(e,t)}var ak=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),ok=(e,t)=>({kind:e,value:`mule_${e}_${Vg()}`,parent:t}),sk=()=>ii;function ck(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 lk=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function uk(e,t){return e.find(e=>e.descriptor.name===t.name)}function dk(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function fk(e,t,n,r,i){let a=ok(`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=lk(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*dk(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*Vr(e.prepare(t));if(je(o)){let e=lk(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*dk(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function pk(e,t,n,r){return b(function*(){let i,a;yield*Xb(Fb(e.tool.execute()),o=>je(o)?(a=o.failure,ii):i===void 0?o.success.type===`result`?(i=o.success.result,ii):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):ii);let o=a===void 0?i??lk(`Tool "${e.call.name}" returned no result`):lk(a.message),s={call:e.call,identity:e.identity,result:o};return yield*dk(s,t,n,r),s})}function mk(e,t,n,r){let i=ck(e.call,e.result),a=ok(`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 hk(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>uk(a,e)?.executionMode===`sequential`);return b(function*(){let t=e=>e.kind===`finalized`?S(e.value):pk(e,n,r,i),s=o?yield*$r(e,e=>T(fk(uk(a,e),e,n,r,i),t)):yield*b(function*(){let o=yield*$r(e,e=>fk(uk(a,e),e,n,r,i));return yield*Hn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*$r(s,e=>mk(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var gk=e=>lk(`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 _k(e,t,n,r){return b(function*(){let i=yield*$r(e,e=>b(function*(){let i=ok(`tool_call`,n),a={call:e,identity:i,result:gk(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*dk(a,t,n,r),a}));return yield*$r(i,e=>mk(e,t,n,r))})}function vk(e,t){return fn({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=>ak(`model`,`Pi model stream failed`,e)})}function yk(e,t,n){return e.pipe(mi({duration:t,orElse:()=>y(n())}))}function bk(e,t,n,r,i,a){let o=ok(`message`,r),s,c={started:!1,terminal:void 0};return ir(b(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??ek.firstEventMs,ek.firstEventMs),d=Math.min(l?.attemptMs??ek.attemptMs,ek.attemptMs),f=Math.min(l?.outputBytes??ek.outputBytes,ek.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*y(ak(`model`,`Model stream limits must be positive safe integers`));let p=performance.now(),m=p,ee=0,te=0,ne=new TextEncoder,re=!1,ie=e=>ak(`model`,`Model ${e} after ${String(Math.round(performance.now()-p))} ms (max provider gap ${String(Math.round(Math.max(ee,performance.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`?rk:nk),ae=t=>{let n=performance.now()-p,r=d-n,i=Math.min(re?ek.idleMs:u,e.modelStreamIdleTimeoutMs??ek.idleMs)-(performance.now()-m),a=r<=i?`attempt timed out`:re?`stream timed out (silence)`:`first event timed out`;return yk(t,Math.max(0,Math.min(r,i)),()=>ie(a))},oe=new AbortController,se={};yield*Er(()=>fn({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)},tk);e.then(()=>{clearTimeout(n),t(!0)},()=>{clearTimeout(n),t(!1)})})},catch:e=>ak(`model`,`Pi model stream failed`,e)}).pipe(Rt(()=>!1),T(t=>t?ii:e.onUndrained??ii)));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(fn({try:()=>{let t=e.stream??uO;return se.response=Promise.resolve(t(e.model,lO(de),le)),se.response},catch:e=>ak(`model`,`Pi model stream could not start`,e)})),me=pe[Symbol.asyncIterator]();se.iterator=me;let he=e=>{let a=performance.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 y(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,ii;case`error`:return c.terminal=e.error,ii}},ge=()=>ae(vk(me,oe)),_e=yield*ge();for(;!_e.done;)yield*he(_e.value),_e=yield*ge();let ve=c.terminal??(yield*ae(fn({try:()=>pe.result(),catch:e=>ak(`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(vn(l=>{if(l.cause!==nk&&l.cause!==rk)return y(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===rk}})})))}function xk(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*y(ak(`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?ii: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*An(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*y(ak(`model`,`Retry policy is unavailable`));u++,p=e;let i=Math.max(xO(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*y(ak(`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*y(ak(`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*bk(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*li({try:()=>a.limitReached===!0||e.retryable(p),catch:e=>ak(`model`,`Typed model retry decision failed`,e)}))){let t=yield*li({try:()=>e.retryAfterMs?.(p),catch:e=>ak(`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(Ae(()=>u===0||f?ii:ee(!1,p)))})}var Sk=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function Ck(e,t,n,r,i,a){return $r(e,e=>b(function*(){let o=ok(`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(pn)}function wk(e,t,n,r,i,a,o,s){return b(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*Ck(a,t,n,r,i,o);let c=yield*xk(e,t,r,i,o,s),l=Sk(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*_k(u,r,i,o),terminate:!1}:yield*hk(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 Tk(e,t,n,r,i,a){let o=ok(`turn`,i);return b(function*(){if(Sk(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*$r(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=uk(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*fk(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*pk(e,i,o,a)}else s={call:n.call,identity:ok(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?gk(n.call):lk(`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*dk(s,i,o,a);return{message:yield*mk(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 Ek(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 Dk(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 Ok(e,t=sk){return b(function*(){let n=yield*cy(1),r={started:!1,ended:!1},i=e=>lr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(Fn(()=>Vn(()=>{e.type===`run_start`&&(r.started=!0)}))),a=ok(`run`),o=ok(`terminal`,a);return yield*Ak(e,i,a,o).pipe(Pe(e=>{let t=kk(e);return!r.started||r.ended||t===void 0?ii:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(He)}))})}function kk(e){if(Ga(e))return;if(ka(e.cause))return`cancelled`;let t=Na(e.cause);if(!(Fr(t)&&t.value.phase===`listener`))return`failed`}function Ak(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*Tk(e,e.resume,i,a,n,t),c=Sk(s.message),l=c===`completed`?yield*Ek(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*Dk(n,r,s.message,a,c,t);o.push(...l.pending)}do{let u=yield*wk(e,i,a,n,ok(`turn`,n),o,t,l);l=void 0,s=u.message;let d=Sk(u.message);if(d!==`completed`)return yield*Dk(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*Ek(e,u,i,a);o=[...f.pending],c=f.continue}while(c);return yield*Dk(n,r,s,a,`completed`,t)})}var jk={run:Ok},Mk=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 QC({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)}},Nk=8192,Pk=Nk*4,Fk=new TextEncoder,Ik=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),Lk=class e{wake;#e={stdout:{decoder:Ik(),pending:new Uint8Array},stderr:{decoder:Ik(),pending:new Uint8Array}};#t=Ik();#n=Array.from({length:Nk},()=>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 vv({capacity:1,strategy:`dropping`}).pipe(Te(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+=Pk){let r=t.subarray(e,e+Pk),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,Sv(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)%Nk,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 Fk.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=Fk.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:Fk.encode(e).length,newlines:e.split(`
|
|
21
|
+
`).length-1};for(this.#i===Nk&&this.#p(),this.#n[(this.#r+this.#i)%Nk]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>Nk||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-Nk),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)%Nk];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 kb(this.wake).pipe(Pb(()=>An(`100 millis`).pipe(Te(()=>this.#u?void 0:this.#g()))),Ub(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}},Rk=P({code:M}),zk='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 Bk(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await ZE(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function Vk(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=>Bk(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 Hk(e,t){let n=e.safeParse(t);if(!n.success)throw new BC(n.error.issues);return n.data}function Uk(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(Hk(CS,t))),describe:t=>Promise.resolve().then(()=>e.describe(Hk(SS,t))),search:t=>Promise.resolve().then(()=>e.search(Hk(xS,t)))})}function Wk(e,t,n,r,i){return Object.freeze({...Vk(e,n,r,i),forage:Uk(t)})}function Gk(e,t,n,r,i,a,o,s){let c=n.execution??WD(void 0),l=new Mk,u=(u,d,f,p,m)=>eO({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=>Wk(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>lr(()=>{let n=Vg();return u(n,e,t).pipe(ar(Vn(()=>{l.dispose(n)})))}),f=(e,t,n)=>lr(()=>{let r=Vg(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(Et({onSuccess:e=>S(Kk({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof XC&&t.length>0?S(Kk({text:tw(e),isError:!0},t)):y(qk(e))}}),ar(Vn(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:zk,parameters:UO({code:JO()},{additionalProperties:!1})},prepare:e=>Tm(Rk)(e.arguments).pipe(Te(({code:t})=>({execute:()=>Mb(b(function*(){let n=yield*Lk.make();yield*Er(()=>Vn(()=>{n.dispose()}));let r=yield*Yn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return Hb(n.updates,hb(Qv(r)).pipe(Ib(e=>{let t=n.finish();return zb(Db(t===void 0?[]:[t]),hb(e))})),{haltStrategy:`right`}).pipe(qb(e=>e.type===`result`))}))})),dt(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function Kk(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 qk(e){let t={_tag:`MuleError`,phase:`tool`,message:iw(e)?tw(e):e.message};return e instanceof GC?{...t,cause:e}:t}function Jk(e,t){return e<t?-1:+(e>t)}var Yk=128,Xk=v(()=>w().min(1).max(160)),Zk=v(()=>g({version:w().min(1).max(160),modules:Dr(St())})),Qk=1e3;function $k(e){if(e.length>Yk)throw new K(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>Jk(e.id,t.id)),n=new Set;for(let e of t){if(!Xk.safeParse(e.id).success)throw new K(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new K(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function eA(e){if(e>Qk)throw new K(`Candidate module count exceeds bound`)}function tA(e,t){let n=Zk.safeParse(e);if(!n.success)throw new K(`Capability source snapshot must have a non-empty bounded version`);eA(t+n.data.modules.length)}function nA(e,t,n,r,i){return te(a=>b(function*(){let o=t=>fn({try:()=>t.release(),catch:()=>new zC(e.id,`release`)}).pipe(vn(e=>Vn(()=>{n.push(e)}))),s=yield*li({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=>Ba(e),()=>Ha(new zC(e.id,`acquire`)))}},catch:()=>new zC(e.id,`acquire`)});yield*uo(t,qt(()=>s.outcome).pipe(T(e=>Ga(e)?o(e.value):ii)));let c=yield*a(qt(()=>s.outcome)).pipe(Ae(()=>Vn(()=>{s.controller.abort()})));return Ka(c)?yield*Zt(c.cause):c.value}))}function rA(e){return b(function*(){let t=yield*li({try:()=>$k(e.sources),catch:e=>e instanceof K?e:new K(`Capability sources are invalid`)});yield*li({try:()=>{eA(e.modules.length)},catch:e=>e instanceof K?e:new K(`Static capability modules are invalid`)});let n=yield*oo(),r=[],i=!1,a=[...e.modules],o=[];return yield*b(function*(){for(let s of t){let t=yield*nA(s,n,r,()=>{i=!0},e.session);yield*li({try:()=>{tA(t.snapshot,a.length)},catch:e=>e instanceof K?e:new K(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*li({try:()=>PD(a,o),catch:e=>e instanceof K?e:new K(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=Gk(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*mo(n,Wa));let e=r[0];e!==void 0&&(yield*y(e))})})}).pipe(Pe(e=>Ga(e)?ii:mo(n,e)))})}var iA=2;function aA(e){return b(function*(){for(let t=0;t<iA;t+=1){let t=yield*rA(e);if(!t.isStale())return t;yield*t.close()}return yield*y(new zC(void 0,`stale`))})}function oA(e,t,n){return te(r=>r(e.take(1)).pipe(T(()=>Vn(t).pipe(ar(e.release(1)))),T(n)))}function sA(e,t){return bt(e.candidate.close().pipe(Et({onFailure:t=>no(e.settled,t).pipe(_(y(t))),onSuccess:()=>ro(e.settled,void 0).pipe(_(Vn(()=>{t.delete(e)})))})))}function cA(e,t){return e.runCleanup?sA(e.installed,t):eo(e.installed.settled)}function lA(e,t){return Hn(e.map(e=>cA(e,t).pipe(In)),{concurrency:`unbounded`}).pipe(T(e=>{let t=e.find(Ka);return t===void 0?ii:Zt(t.cause)}))}function uA(e){return b(function*(){let t=yield*cy(1),n=yield*li({try:()=>WD(e.execution),catch:e=>e instanceof K?e:new K(`Execution policy is invalid`)}),r=yield*GD(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*li({try:()=>PD(e.modules),catch:e=>e instanceof K?e:new K(`Capability compilation failed`)}),o=yield*li({try:()=>Object.freeze(e.tools.map(t=>eD(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof K?e:new K(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*aA({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*$a(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>oA(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=>lA(e,c));return yield*Er(()=>u().pipe(Ht)),Object.freeze({acquire:()=>t.withPermits(1)(b(function*(){if(l)return yield*y(new RC);if(s===void 0||s.candidate.isStale()){let t=yield*aA({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*$a(),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*sA(n,c)))}let n=s;n.leases+=1;let a,u=()=>oA(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?ii:cA(e,c));return yield*Er(()=>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 dA(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>bt(fn({try:()=>e.execute(t,n),catch:aw}))})}function fA(e){return uA({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(Te(e=>Object.freeze({acquire:()=>e.acquire().pipe(Te(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function pA(e,t){let n=await Kn(e,t);if(Ga(n))return n.value;let r=Na(n.cause);if(Fr(r))throw r.value;if(ka(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=ja(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function mA(e){let t=await pA(oo()),n=e.onSandboxFailure;try{let r=await pA(uA({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:dA(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>qt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(co(t))),i=async e=>{let t=await pA(oo());try{let n=await pA(r.acquire().pipe(co(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??=pA(n.release().pipe(ar(mo(t,Wa)))),i)})}catch(e){throw await pA(mo(t,Wa)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=pA(r.close().pipe(ar(mo(t,Wa)))),a)})}catch(e){throw await pA(mo(t,Wa)),e}}var hA=nh(()=>I([Um,Gm,Eh,M,$m(F(hA)),Rm(Ym(M,hA))])),gA=M.check($h(1),ng(256)),_A=M.check($h(1),ng(128)),vA=P({kind:j(`sandbox_failure`),ref:gA,executionId:gA,adapter:_A,buildSha:R(_A),tag:L([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:Ym(M,hA),healthAlert:Gm});function yA(e){return uD(e)}function bA(e){return dD(e)}var xA=Object.freeze({module:bA,operation:yA,make:mA,gate:vD,grantAs:_D}),SA=Fg,CA=4096,wA=new TextEncoder,TA=SA.check(B(e=>wA.encode(JSON.stringify(e)).byteLength<=CA)),EA=D(TA);function DA(e,t){if(Lm(e))return Wt(D(e)(t));let n=e[`~standard`].validate(t);if(xr(n,`then`))throw new G(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function OA(e,t){let n=EA(t);if(je(n))throw new G(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!DA(e.schema,n.success))throw new G(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function kA(e,t){return JSON.stringify(e)===JSON.stringify(t)}function AA(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 jA(e){return AA({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function MA(e,t,n){fr(rt(`shiitake_operation_failed`,bs(t)).pipe(pr({operation:e,errorKind:t instanceof Error?`error`:`non-error`,...n})))}var NA=64,PA=256,FA=new WeakMap,IA=new TextEncoder;function LA(e){let t=FA.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:IA.encode(n).byteLength});return FA.set(e,r),r}function RA(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 zA(e){let t=new Set,n=!1,r,i=e=>{yr(kv(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:yr(bv(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=lr(()=>o.closed?S(`closed`):r===void 0?o.lagged?S(`reset`):n?S(`closed`):Mv(o.frames).pipe(Io(()=>S(`closed`)),T(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=LA(e).bytes),S(e)):y(r))):y(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),Ev(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=RA(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=LA(t);n.bytes+o>1048576||!Sv(n.frames,t)?(i(n),n.lagged=!0,Sv(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Ev(e.frames)}}}}var BA=new WeakMap;function VA(e,t){for(let n of BA.get(e)??[])if(n.observes(t))return!0;return!1}function HA(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 UA(e,t){if(e.pendingCount>=PA){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 WA(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){UA(e,t);return}e.wake=void 0;try{n(t)}catch(t){MA(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function GA(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&WA(n,`activity`)}function KA(e,t,n=`durable`){let r=BA.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){MA(`owner-observation-publish`,e);continue}}function qA(e){let t=BA.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){MA(`owner-execution-change-publish`,e)}}function JA(e){let t=new Map,n=new Set,r=BA.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){MA(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){GA(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&GA(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`||WA(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),BA.set(e,r),Object.freeze({register:(e,r)=>lr(()=>{if(i)return y(new G(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=NA)return y(new G(`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=Vn(()=>a(s)),u=$n(e=>{let t=a(s);if(t!==void 0){e(S(t));return}let n=t=>{e(S(t))};return s.wake=n,Vn(()=>{s.wake===n&&(s.wake=void 0)})});return S(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:Vn(()=>{if(!i){i=!0,r.delete(s),r.size===0&&BA.delete(e);for(let e of n)o(e)}})})}var YA=200,XA={onExcessProperty:`error`},ZA=new TextEncoder,QA=H.pipe(z(V(0))),$A=M.pipe(z($h(1)),z(B(e=>ZA.encode(e).byteLength<=256)));D(P({limit:k(H.pipe(z(Lh({minimum:1,maximum:YA})))),after:k(M)}),XA);var ej=U(Zm([QA,$A]));D(ej),Fm(ej),D(P({session_id:$A,last_activity_at:QA,state:L([`needs_you`,`running`,`errored`,`done`]),bytes:H.pipe(z(V(0)))}),XA);var tj=O(P({extension_id:M,value_json:M})),nj=O(U(ax)),rj=O(ox),ij=Fm(U(ax));function aj(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
22
|
+
extension_id TEXT PRIMARY KEY
|
|
23
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention (
|
|
24
|
+
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
25
|
+
extension_id TEXT NOT NULL,
|
|
26
|
+
id TEXT NOT NULL,
|
|
27
|
+
value_json TEXT NOT NULL,
|
|
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 oj(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=tj(e);return rj({...nj(t.value_json),extensionId:t.extension_id})})}function sj(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 cj(e,t){return oj(e,t).some(e=>e.inbox!==!1||e.waitingOn!==void 0)}function lj(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 G(`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 G(`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,ij(r))}function uj(e,t,n,r){e.sql.exec(`DELETE FROM session_attention WHERE session_id = ? AND extension_id = ? AND id = ?`,t,n,r)}function dj(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 fj(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 pj=M.check($h(1),ng(256)),mj=262144,hj=M.check(B(e=>new TextEncoder().encode(e).byteLength<=mj,{message:`Mail content must be at most ${String(mj)} UTF-8 bytes`})),gj=P({kind:j(`agent`),agentId:pj,sessionId:pj}),_j=P({kind:j(`agent`),agentId:pj,sessionId:k(pj)}),vj=P({kind:j(`system`),systemId:j(`hub`)}),yj=P({itemId:pj,kind:M.check($h(1),ng(64)),summary:M.check($h(1),ng(200))}),bj=P({commandId:pj,outcome:L([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:k(M.check($h(1),ng(200))),waitingOnYou:k(F(yj).check($h(1),ng(8)))}),xj=L([`recipient_offline`,`recipient_left`]),Sj=P({outcome:j(`undeliverable`),reason:xj}),Cj=P({outcome:j(`accepted`),commandId:pj});I([bj,Sj,Cj]);var wj=I([bj,Cj,P({outcome:j(`undeliverable`),reason:j(`recipient_left`)})]),Tj=`[redacted]`,Ej=/\b(bearer|basic)\s+[^\s"',;]+/giu,Dj=/\b((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization)["']?\s*[:=]\s*["']?)(?!(?:bearer|basic)\s)[^\s"',;&]+/giu,Oj=/[A-Za-z0-9][\w-]{23,}/gu;function kj(e){return e.replace(Ej,`$1 ${Tj}`).replace(Dj,`$1${Tj}`).replace(Oj,e=>/\d/u.test(e)&&/[A-Za-z]/u.test(e)?Tj:e)}function Aj(e){let t=kj(e.replace(/[\p{Cc}\p{Zl}\p{Zp}\s]+/gu,` `).trim()).slice(0,200).trimEnd();return t.length===0?void 0:t}var jj={key:pj,to:_j,replyTo:F(gj),content:hj,createdAt:N.check(V(0)),meta:k(Fg)},Mj=I([P({...jj,from:gj,reply:k(wj)}),P({...jj,from:vj,reply:P({outcome:j(`undeliverable`),reason:j(`recipient_offline`)})})]),Nj=P({jobId:pj,sessionId:pj,commandFactId:pj,recovery:A(P({maxRecoveries:H.check(V(0)),windowMs:k(H.check(Ph(0)))}))}),Pj=P({work:P({sessionId:pj,commandFactId:pj}),mail:A(Mj)}),Fj=P({work:Nj,delivery:L([`steer`,`followUp`]),mail:A(Mj)}),Ij=e=>{let t=O(Fj)(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}},Lj=e=>O(Pj)(e.payload);function Rj(e,t,n,r){let i=O(pj)(t),a=O(gj)(e.from),o=O(Cj)({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 zj=O(P({mail_key:M,agent_id:M,reply_to_json:U(F(gj))})),Bj=Fm(U(F(gj)));function Vj(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_delegators (
|
|
31
|
+
session_id TEXT PRIMARY KEY,
|
|
32
|
+
mail_key TEXT NOT NULL,
|
|
33
|
+
agent_id TEXT NOT NULL,
|
|
34
|
+
reply_to_json TEXT NOT NULL
|
|
35
|
+
)`)}function Hj(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,Bj(n.replyTo))}function Uj(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=zj(n);return{key:r.mail_key,agentId:r.agent_id,replyTo:r.reply_to_json}}var Wj=8,Gj=O(P({agent_id:M,sender_session_id:M,name:M})),Kj=O(rx),qj=O(P({work_id:M}));function Jj(e,t,n){let r=Uj(e,t)?.replyTo[0];if(r===void 0)return Yj(e,t,n);let i=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,r.agentId,r.sessionId).toArray()[0];return Kj({agentId:r.agentId,sessionId:r.sessionId,name:i===void 0?r.agentId:Gj(i).name})}function Yj(e,t,n){if(n===void 0)return;let r=e.sql.exec(`SELECT agent_id, sender_session_id, name FROM session_work_senders WHERE agent_id = ? ORDER BY session_id = ? DESC, rowid DESC LIMIT 1`,n,t).toArray()[0];if(r===void 0)return;let i=Gj(r);return Kj({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function Xj(e,t,n,r){return e.sql.exec(`SELECT work_id FROM session_work_senders WHERE session_id = ? AND agent_id = ? ORDER BY rowid DESC LIMIT ?`,t,n,r).toArray().map(e=>qj(e).work_id)}function Zj(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_work_senders (
|
|
36
|
+
session_id TEXT NOT NULL,
|
|
37
|
+
work_id TEXT NOT NULL,
|
|
38
|
+
agent_id TEXT NOT NULL,
|
|
39
|
+
sender_session_id TEXT NOT NULL,
|
|
40
|
+
name TEXT NOT NULL,
|
|
41
|
+
PRIMARY KEY (session_id, work_id)
|
|
42
|
+
)`)}function Qj(e,t,n,r){e.sql.exec(`INSERT OR IGNORE INTO session_work_senders
|
|
43
|
+
(session_id, work_id, agent_id, sender_session_id, name)
|
|
44
|
+
VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function $j(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=Gj(r);return Kj({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function eM(e,t,n){let r=$j(e,t,n);return r===void 0?[]:tM(e,t,[r])}function tM(e,t,n){return oj(e,t).filter(e=>n.some(t=>e.waitingOn?.agentId===t.agentId)).slice(0,Wj).map(e=>({itemId:e.id,kind:e.kind,summary:e.summary}))}var nM=new TextEncoder,rM=new TextDecoder,iM=/^[A-Za-z0-9_-]+$/u,aM=P({v:j(1),generation:M.pipe(z($h(1)),z(ng(128)),z(B(e=>nM.encode(e).byteLength<=128))),sequence:H.pipe(z(Ph(0)),z(Ih(2**53-1)))}),oM={onExcessProperty:`error`},sM=D(aM,oM),cM=D(U(aM),oM);function lM(e){let t=sM({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(nM.encode(n).byteLength>384)return;let r=vc(n);return nM.encode(r).byteLength<=512?r:void 0}function uM(e){if(nM.encode(e).byteLength>512||!iM.test(e))return;let t=yc(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=rM.decode(t.success),r=cM(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&vc(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var dM=M.check($h(1),ng(256)),fM=I([P({agentId:dM,sessionId:dM,...bj.fields}),P({agentId:dM,sessionId:k(dM),...Sj.fields})]),pM=`fungi_agent_reply`,mM=RegExp(`<(?=\\s*/?\\s*${pM})`,`giu`);function hM(e){return e.replace(mM,`<`)}function gM(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function _M(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]),`<${pM} ${t.map(([e,t])=>`${e}="${gM(t)}"`).join(` `)}>`}function vM(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:hM(e.text)}:e):hM(e.content);if(t===void 0)return{...e,content:n};let r=_M(t),i=`</${pM}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var yM={onExcessProperty:`error`},bM=new TextEncoder,xM=e=>M.pipe(z($h(1)),z(B(t=>bM.encode(t).byteLength<=e))),SM=xM(256),CM=xM(4096),wM=M.pipe(z(vh(/^[0-9a-f]{64}$/u))),TM=nh(()=>I([M,N,Gm,Um,F(TM),Ym(M,TM)])),EM=P({type:j(`text`),text:M,textSignature:k(M)}),DM=P({type:j(`thinking`),thinking:M,thinkingSignature:k(M),redacted:k(Gm)}),OM=P({type:j(`image`),data:M,mimeType:M}),kM=P({type:j(`toolCall`),id:M,name:M,arguments:Ym(M,TM),thoughtSignature:k(M),namespace:k(M),argumentsError:k(M)}),AM=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(Gm)})}),jM=P({role:j(`user`),content:I([M,$m(F(I([EM,OM])))]),timestamp:N}),MM=P({role:j(`user`),content:M,timestamp:N}),NM=P({name:M,description:M,parameters:Ym(M,TM),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)})})]))}),PM=I([P({role:j(`system`),content:I([M,$m(F(EM))]),sections:k(Ym(M,I([M,Um]))),toolsAdded:k($m(F(NM))),toolsRemoved:k($m(F(P({name:M})))),timestamp:N}),jM,P({role:j(`assistant`),content:$m(F(I([EM,DM,kM]))),api:M,provider:M,model:M,responseModel:k(M),responseId:k(M),diagnostics:k($m(F(P({type:M,timestamp:N,error:k(P({name:k(M),message:M,stack:k(M),code:k(I([M,N]))})),details:k(Ym(M,TM))})))),usage:AM,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(TM)})),errorMessage:k(M),providerError:k(M),modelFailure:k(EO),rawStopReason:k(M),providerThinkingLevel:k(M),endTurn:k(Gm),timestamp:N,durationMs:k(N)}),P({role:j(`toolResult`),toolCallId:M,toolName:M,content:$m(F(I([EM,OM]))),usage:k(AM),isError:Gm,timestamp:N,durationMs:k(N)})]),FM=L([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),IM=nh(()=>P({kind:FM,value:SM,parent:A(IM)})),LM=I([P({type:j(`auto_retry_start`),run:IM,attempt:N,maxAttempts:N,delayMs:N,dueAt:H.check(V(0)),errorMessage:M}),P({type:j(`auto_retry_attempt`),run:IM,attempt:N}),P({type:j(`auto_retry_end`),run:IM,attempt:N,success:Gm,finalError:k(M)})]),RM=P({core:wM,extensions:F(Zm([SM,M.pipe(z(vh(/^sha256:[0-9a-f]{64}$/u)))])).pipe(z(ng(128)))}),zM=P({content:$m(F(I([EM,OM]))),usage:A(AM),isError:Gm,terminate:A(Gm)}),BM={workId:SM},VM=98304,HM=L([`manual`,`threshold`,`overflow`]),UM=I([P({...BM,kind:j(`sandbox_failure`),event:vA}),P({kind:j(`document`),workId:Um,extensionId:SM,name:SM,valueJson:M}),P({kind:j(`model_preference`),workId:Um,preference:R(dx)}),P({...BM,kind:j(`command`),meta:k(TA),reply:k(fM),delivery:k(L([`steer`,`followUp`])),requestId:SM,targetWorkId:k(SM),receiptId:SM,message:jM,contract:RM}),P({...BM,kind:j(`command`),work:j(`compact`),instructions:k(Ix),meta:k(TA),requestId:SM,receiptId:SM,timestamp:H.check(V(0)),contract:RM}),P({kind:j(`operator`),workId:Um,requestId:SM,author:L([`operator`,`party`]),meta:k(TA),message:MM}),P({...BM,kind:j(`cancellation`),requestId:SM,receiptId:SM,targetWorkId:SM,meta:k(TA)}),P({...BM,kind:j(`model_selection`),provider:SM,model:SM,catalogRevision:SM,definitionRevision:SM,selectionPolicyRevision:SM}),P({...BM,kind:j(`run_started`),run:IM,contract:RM}),P({...BM,kind:j(`turn_started`),run:IM,turn:IM}),P({...BM,kind:j(`model_prompt`),run:IM,turn:IM,attempt:N.pipe(z(zh()),z(Ph(0))),contract:RM,systemPrompt:M.pipe(z(B(e=>bM.encode(e).byteLength<=1048576)))}),P({...BM,kind:j(`message_start`),run:IM,turn:IM,message:IM,role:L([`assistant`,`system`,`toolResult`,`user`]),partial:k(P({text:M.pipe(z(B(e=>bM.encode(e).byteLength<=VM))),offset:N.pipe(z(zh()),z(V(0)))}))}),P({...BM,kind:j(`message`),data:k(TM),run:IM,turn:IM,message:IM,value:PM}),P({...BM,kind:j(`tool_intent`),replay:L([`safe`,`unsafe`]).pipe(fh(S(`unsafe`))),contract:RM,run:IM,turn:IM,toolCall:IM,call:kM}),P({...BM,kind:j(`tool_outcome`),data:k(TM),run:IM,turn:IM,toolCall:IM,call:kM,result:zM}),P({...BM,kind:j(`live_retry`),event:LM}),P({...BM,kind:j(`compaction`),head:SM,model:Zm([jM]),data:P({reason:k(HM),resumesRun:Gm,tokensBefore:N,tokensAfter:k(N),usage:AM,contextRevision:SM,receipt:k(CM),details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})}),P({...BM,kind:j(`compaction_checkpoint`),trigger:HM,resumesRun:Gm,head:SM,contextRevision:SM,summary:M,tokensBefore:N,usage:AM,details:P({readFiles:F(M),modifiedFiles:F(M)})}),P({...BM,kind:j(`compaction_notice`),trigger:HM,result:j(`nothing_to_compact`),diagnostic:k(M.check(ng(200)))}),P({...BM,kind:j(`compaction_notice`),trigger:HM,result:j(`failed`),usage:k(AM),diagnostic:k(M.check(ng(200)))}),P({...BM,kind:j(`compaction_notice`),trigger:HM,result:j(`stale`),usage:k(AM)}),P({...BM,kind:j(`compaction_notice`),trigger:HM,result:j(`insufficient`),usage:k(AM)}),P({...BM,kind:j(`run_terminal`),run:IM,terminal:IM,diagnostic:k(M.check(ng(200))),outcome:L([`completed`,`cancelled`,`failed`])}),P({...BM,kind:j(`work_terminal`),diagnostic:k(M),outcome:L([`completed`,`interrupted`,`cancelled`,`failed`])})]),WM=jg(UM);function GM(e){return{kind:e.kind,workId:e.workId,run:e.run,turn:e.turn,message:e.message,role:e.role}}function KM(e,t){return WM(ZM(XM(e)),ZM(XM(t)))}var qM=U(UM),JM=U(Hm),YM=D(qM,yM),XM=Fm(JM),ZM=O(qM,yM);function QM(e){return`work`in e}function $M(e){return e.kind===`command`&&!QM(e)?e:void 0}function eN(e){return QM(e)?e.timestamp:e.message.timestamp}function tN(e){return vM(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 nN(e){return vM(e.message,e.reply)}function rN(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 iN(e){return zt(YM(e),e=>e.kind===`command`&&!QM(e)&&e.delivery===void 0?{...e,delivery:`followUp`}:e)}function aN(e){let t=XM(e);return ZM(t),t}var oN=i_({family:`session`,version:1,kinds:{session:{prefix:`session`},work:{prefix:`session_work`},fact:{prefix:`session_fact`},receipt:{prefix:`session_receipt`}}}),sN=M.pipe(z($h(1))),cN=H.pipe(z(V(0))),lN={onExcessProperty:`error`},uN=P({value_json:M}),dN=P({state_version:H.pipe(z(V(1))),revision:sN}),fN=P({status:L([`running`,`stopped`]),reason:R(M),stopped_at:R(cN),revision:sN}),pN=P({extension_id:sN,key:sN,job_id:sN}),mN=P({collection:sN,key:sN,value_json:M}),hN=P({sequence:cN});function gN(e){return new G(`store`,`unavailable`,e)}function _N(e,t,n){let r=D(e,lN);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw gN(n);return t.success})}function vN(e){e.transactionSync(()=>{yN(e)})}function yN(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_records (
|
|
45
|
+
extension_id TEXT NOT NULL,
|
|
46
|
+
collection TEXT NOT NULL,
|
|
47
|
+
key TEXT NOT NULL,
|
|
48
|
+
index_value TEXT,
|
|
49
|
+
value_json TEXT NOT NULL,
|
|
50
|
+
PRIMARY KEY (extension_id, collection, key)
|
|
51
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_shiitake_extension_records_index
|
|
52
|
+
ON shiitake_extension_records(extension_id, collection, index_value, key)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_state (
|
|
53
|
+
extension_id TEXT PRIMARY KEY,
|
|
54
|
+
state_version INTEGER NOT NULL CHECK (state_version >= 1),
|
|
55
|
+
revision TEXT NOT NULL
|
|
56
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_status (
|
|
57
|
+
extension_id TEXT PRIMARY KEY,
|
|
58
|
+
status TEXT NOT NULL CHECK (status IN ('running', 'stopped')),
|
|
59
|
+
reason TEXT,
|
|
60
|
+
stopped_at INTEGER,
|
|
61
|
+
revision TEXT NOT NULL,
|
|
62
|
+
CHECK ((status = 'running') = (reason IS NULL)),
|
|
63
|
+
CHECK ((reason IS NULL) = (stopped_at IS NULL))
|
|
64
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_timers (
|
|
65
|
+
extension_id TEXT NOT NULL,
|
|
66
|
+
key TEXT NOT NULL,
|
|
67
|
+
job_id TEXT NOT NULL,
|
|
68
|
+
PRIMARY KEY (extension_id, key)
|
|
69
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_settled_cursors (
|
|
70
|
+
consumer TEXT PRIMARY KEY,
|
|
71
|
+
sequence INTEGER NOT NULL CHECK (sequence >= 0)
|
|
72
|
+
)`)}function bN(e,t,n,r){return _N(uN,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 xN(e,t,n,r){return _N(uN,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
|
|
74
|
+
WHERE extension_id = ? AND collection = ?
|
|
75
|
+
AND (? IS NULL OR index_value = ?)
|
|
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 SN(e,t,n,r,i,a){e.sql.exec(`INSERT INTO shiitake_extension_records
|
|
78
|
+
(extension_id, collection, key, index_value, value_json)
|
|
79
|
+
VALUES (?, ?, ?, ?, ?)
|
|
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 CN(e,t,n,r){e.sql.exec(`DELETE FROM shiitake_extension_records
|
|
82
|
+
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r)}function wN(e,t){return _N(mN,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 TN(e,t){e.sql.exec(`DELETE FROM shiitake_extension_records WHERE extension_id = ?`,t)}function EN(e,t){let n=_N(dN,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 DN(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_state (extension_id, state_version, revision)
|
|
85
|
+
VALUES (?, ?, ?)
|
|
86
|
+
ON CONFLICT(extension_id) DO UPDATE SET
|
|
87
|
+
state_version = excluded.state_version, revision = excluded.revision`,t,n,r)}function ON(e,t){let n=_N(fN,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 kN(e,t,n){e.sql.exec(`INSERT INTO shiitake_extension_status
|
|
89
|
+
(extension_id, status, reason, stopped_at, revision)
|
|
90
|
+
VALUES (?, ?, ?, ?, ?)
|
|
91
|
+
ON CONFLICT(extension_id) DO UPDATE SET status = excluded.status,
|
|
92
|
+
reason = excluded.reason, stopped_at = excluded.stopped_at,
|
|
93
|
+
revision = excluded.revision`,t,n.status,n.reason,n.stoppedAt,n.revision)}var AN=`extension_timer`;function jN(e,t,n){return _N(pN,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 MN(e,t,n,r,i){NN(e,t,n,r);let a=oN.work.generate();t.enqueueAcceptedJob({jobId:a,queue:a,lane:AN,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 NN(e,t,n,r){let i=jN(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 PN(e,t){return _N(pN,e.sql.exec(`SELECT extension_id,key,job_id FROM shiitake_extension_timers WHERE extension_id=?`,t).toArray(),`Extension timer is invalid`)}function FN(e,t,n){for(let r of PN(e,n))t.recordCancellationIntent({jobId:r.job_id,cancellationId:`${r.job_id}:cancel`,onlyIfQueued:!0})}function IN(e,t,n){for(let r of PN(e,n)){let i=t.readJob(r.job_id);if(i===void 0)throw gN(`Extension timer job is missing`);i.state!==`queued`&&i.state!==`running`&&MN(e,t,n,r.key,i.notBefore)}}function LN(e,t,n){for(let r of PN(e,n))NN(e,t,n,r.key)}function RN(e,t,n,r){let i=jN(e,n,r);if(i===void 0)return;let a=t.readJob(i);if(a===void 0)throw gN(`Extension timer job is missing`);return a.notBefore}function zN(e,t){return _N(hN,e.sql.exec(`SELECT sequence FROM shiitake_settled_cursors WHERE consumer = ?`,t).toArray(),`Settled cursor is invalid`)[0]?.sequence}function BN(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 VN=P({extension_id:M,name:M,initial_json:M,fork:L([`inherit-at-fork-point`,`current`,`fresh`]),max_bytes:H.pipe(z(Ph(0)))});function HN(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_document_specs (
|
|
95
|
+
extension_id TEXT NOT NULL, name TEXT NOT NULL, initial_json TEXT NOT NULL,
|
|
96
|
+
fork TEXT NOT NULL, max_bytes INTEGER NOT NULL,
|
|
97
|
+
PRIMARY KEY (extension_id, name)
|
|
98
|
+
)`)}function UN(e,t){e.sql.exec(`INSERT INTO session_document_specs
|
|
99
|
+
(extension_id, name, initial_json, fork, max_bytes) VALUES (?, ?, ?, ?, ?)
|
|
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 WN(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(VN)(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 G(`store`,`rejected`,`Session document exceeds its declared size bound`);return[{kind:`document`,workId:null,extensionId:n.extension_id,name:n.name,valueJson:r}]})}var GN=wm(M),KN=`The conversation history before this point was compacted into the following summary:
|
|
102
|
+
|
|
103
|
+
<summary>
|
|
104
|
+
`,qN=`
|
|
105
|
+
</summary>`;function JN(e,t){return{role:`user`,content:[{type:`text`,text:KN+e+qN}],timestamp:t}}function YN(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(KN)||!n.endsWith(qN))throw Error(`Compaction model message is not a summary`);return n.slice(KN.length,n.length-qN.length)}function XN(){return{edited:new Set,read:new Set,written:new Set}}function ZN(e,t){if(e.role===`assistant`)for(let n of e.content){if(n.type!==`toolCall`)continue;let e=n.arguments.path;GN(e)&&(n.name===`edit`&&t.edited.add(e),n.name===`read`&&t.read.add(e),n.name===`write`&&t.written.add(e))}}function QN(e){let t=new Set([...e.edited,...e.written]);return{modifiedFiles:[...t].sort(),readFiles:[...e.read].filter(e=>!t.has(e)).sort()}}function $N(e,t){let n=[];return e.length>0&&n.push(`<read-files>\n${e.join(`
|
|
106
|
+
`)}\n</read-files>`),t.length>0&&n.push(`<modified-files>\n${t.join(`
|
|
107
|
+
`)}\n</modified-files>`),n.length===0?``:`\n\n${n.join(`
|
|
108
|
+
|
|
109
|
+
`)}`}var eP=2e3;function tP(e){return e.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function nP(e){if(e.length<=eP)return e;let t=String(e.length-eP);return`${e.slice(0,eP)}\n\n[... ${t} more characters truncated]`}function rP(e){let t=GN(e.content)?e.content:tP(e.content);return t?`[User]: ${t}`:void 0}function iP(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 aP(e){let t=tP(e.content);return t?`[Tool result]: ${nP(t)}`:void 0}function oP(e){let t=[];for(let n of e)if(n.role===`system`){let e=GN(n.content)?n.content:tP(n.content);e&&t.push(`[System]: ${e}`)}else if(n.role===`user`){let e=rP(n);e!==void 0&&t.push(e)}else if(n.role===`assistant`)t.push(...iP(n));else{let e=aP(n);e!==void 0&&t.push(e)}return t.join(`
|
|
111
|
+
|
|
112
|
+
`)}function sP(e,t,n){return n.enabled?e>t-n.reserveTokens:!1}function cP(e,t,n){return!n.enabled||n.backgroundTokens===0?!1:e>t-n.reserveTokens-n.backgroundTokens&&!sP(e,t,n)}var lP={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4,backgroundTokens:32768},uP=`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
|
+
|
|
114
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,dP=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
115
|
+
|
|
116
|
+
Use this EXACT format:
|
|
117
|
+
|
|
118
|
+
## Goal
|
|
119
|
+
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
120
|
+
|
|
121
|
+
## Constraints & Preferences
|
|
122
|
+
- [Any constraints, preferences, or requirements mentioned by user]
|
|
123
|
+
- [Or "(none)" if none were mentioned]
|
|
124
|
+
|
|
125
|
+
## Progress
|
|
126
|
+
### Done
|
|
127
|
+
- [x] [Completed tasks/changes]
|
|
128
|
+
|
|
129
|
+
### In Progress
|
|
130
|
+
- [ ] [Current work]
|
|
131
|
+
|
|
132
|
+
### Blocked
|
|
133
|
+
- [Issues preventing progress, if any]
|
|
134
|
+
|
|
135
|
+
## Key Decisions
|
|
136
|
+
- **[Decision]**: [Brief rationale]
|
|
137
|
+
|
|
138
|
+
## Next Steps
|
|
139
|
+
1. [Ordered list of what should happen next]
|
|
140
|
+
|
|
141
|
+
## Critical Context
|
|
142
|
+
- [Any data, examples, or references needed to continue]
|
|
143
|
+
- [Or "(none)" if not applicable]
|
|
144
|
+
|
|
145
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,fP=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
146
|
+
|
|
147
|
+
Update the existing structured summary with new information. RULES:
|
|
148
|
+
- PRESERVE all existing information from the previous summary
|
|
149
|
+
- ADD new progress, decisions, and context from the new messages
|
|
150
|
+
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
151
|
+
- UPDATE "Next Steps" based on what was accomplished
|
|
152
|
+
- PRESERVE exact file paths, function names, and error messages
|
|
153
|
+
- If something is no longer relevant, you may remove it
|
|
154
|
+
|
|
155
|
+
Use this EXACT format:
|
|
156
|
+
|
|
157
|
+
## Goal
|
|
158
|
+
[Preserve existing goals, add new ones if the task expanded]
|
|
159
|
+
|
|
160
|
+
## Constraints & Preferences
|
|
161
|
+
- [Preserve existing, add new ones discovered]
|
|
162
|
+
|
|
163
|
+
## Progress
|
|
164
|
+
### Done
|
|
165
|
+
- [x] [Include previously done items AND newly completed items]
|
|
166
|
+
|
|
167
|
+
### In Progress
|
|
168
|
+
- [ ] [Current work - update based on progress]
|
|
169
|
+
|
|
170
|
+
### Blocked
|
|
171
|
+
- [Current blockers - remove if resolved]
|
|
172
|
+
|
|
173
|
+
## Key Decisions
|
|
174
|
+
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
|
|
175
|
+
|
|
176
|
+
## Next Steps
|
|
177
|
+
1. [Update based on current state]
|
|
178
|
+
|
|
179
|
+
## Critical Context
|
|
180
|
+
- [Preserve important context, add new if needed]
|
|
181
|
+
|
|
182
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,pP=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
|
|
183
|
+
|
|
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
|
+
|
|
186
|
+
## Original Request
|
|
187
|
+
[What did the user ask for?]
|
|
188
|
+
|
|
189
|
+
## Progress So Far
|
|
190
|
+
- [Key decisions and work completed in these messages]
|
|
191
|
+
|
|
192
|
+
## Context Needed to Continue
|
|
193
|
+
- [Information from these messages needed to understand the later work]
|
|
194
|
+
|
|
195
|
+
Only summarize information explicitly present above. Do not infer or recreate later messages.`;function mP(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 hP=Ym(M.check($h(1),ng(160)),L([`none`,`read`,`write`])).check(B(e=>Object.keys(e).length<=256)),gP=D(P({version:H.check(V(0),Ih(2**53-1)),grants:hP}),{onExcessProperty:`error`}),_P=D(U(hP)),vP=Fm(U(hP)),yP=D(P({version:H,grants_json:M}));function bP(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_tool_grants (
|
|
196
|
+
session_id TEXT PRIMARY KEY,
|
|
197
|
+
version INTEGER NOT NULL,
|
|
198
|
+
grants_json TEXT NOT NULL
|
|
199
|
+
)`)}function xP(e,t,n){let r=gP(n);if(je(r))throw new G(`contract`,`invalid`,`Session grants delivery is invalid`);let i=vP(r.success.grants),a=SP(e,t);if(a!==void 0){if(r.success.version<a.version)throw new G(`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
|
+
VALUES (?, ?, ?)
|
|
201
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
202
|
+
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function SP(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=yP(n);if(je(r))throw new G(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:r.success.version,grantsJson:r.success.grants_json}}function CP(e,t){let n=SP(e,t);if(n===void 0)return null;let r=_P(n.grantsJson);if(je(r))throw new G(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:n.version,grants:r.success}}function wP(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 TP=200,EP={onExcessProperty:`error`},DP=new TextEncoder,OP=M.pipe(z($h(1)),z(B(e=>DP.encode(e).byteLength<=256))),kP=H.pipe(z(V(0))),AP=L([0,1,2]),jP=L([`needs_you`,`running`,`errored`,`done`]),MP=L([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),NP=P({session_id:OP,title:R(M),created_at:kP,last_activity_at:kP,settled_at:R(kP),state:jP,tier:AP}),PP=D(NP,EP);D(NP.mapFields(lm({revision:kP})),EP),D(P({revision:kP}),EP);var FP=D(P({outcome:R(MP)}),EP),IP=U(Zm([AP,kP,OP])),LP=D(IP),RP=Fm(IP),zP=`session_id, title, created_at, last_activity_at, settled_at, state, tier`;function BP(e){return new G(`store`,`unavailable`,e)}function VP(e){switch(e){case`needs_you`:return 0;case`running`:return 1;case`errored`:case`done`:return 2}}function HP(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 UP(e){e.sql.exec(`
|
|
204
|
+
CREATE TABLE IF NOT EXISTS session_inbox (
|
|
205
|
+
session_id TEXT PRIMARY KEY REFERENCES sessions(id),
|
|
206
|
+
title TEXT,
|
|
207
|
+
created_at INTEGER NOT NULL,
|
|
208
|
+
last_activity_at INTEGER NOT NULL,
|
|
209
|
+
settled_at INTEGER,
|
|
210
|
+
outcome TEXT CHECK (
|
|
211
|
+
outcome IS NULL OR outcome IN (
|
|
212
|
+
'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
|
|
213
|
+
)
|
|
214
|
+
),
|
|
215
|
+
state TEXT NOT NULL
|
|
216
|
+
CHECK (state IN ('needs_you', 'running', 'errored', 'done')),
|
|
217
|
+
tier INTEGER NOT NULL CHECK (tier IN (0, 1, 2)),
|
|
218
|
+
revision INTEGER NOT NULL
|
|
219
|
+
)
|
|
220
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_order
|
|
221
|
+
ON session_inbox(tier, last_activity_at DESC, session_id)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_revision
|
|
222
|
+
ON session_inbox(revision)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_coldest
|
|
223
|
+
ON session_inbox(last_activity_at, session_id)`),e.sql.exec(`
|
|
224
|
+
CREATE TABLE IF NOT EXISTS session_inbox_clock (
|
|
225
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
226
|
+
revision INTEGER NOT NULL
|
|
227
|
+
)
|
|
228
|
+
`),e.sql.exec(`INSERT OR IGNORE INTO session_inbox_clock (singleton, revision) VALUES (1, 0)`),e.sql.exec(`
|
|
229
|
+
CREATE TABLE IF NOT EXISTS session_inbox_tombstones (
|
|
230
|
+
session_id TEXT PRIMARY KEY,
|
|
231
|
+
revision INTEGER NOT NULL
|
|
232
|
+
) STRICT
|
|
233
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_tombstones_revision ON session_inbox_tombstones(revision)`)}function WP(e){e.sql.exec(`UPDATE session_inbox_clock SET revision = revision + 1 WHERE singleton = 1`)}var GP=`(SELECT revision FROM session_inbox_clock WHERE singleton = 1)`;function KP(e,t){let n=t.title===void 0?``:t.title,r=t.title===void 0?0:1;WP(e),e.sql.exec(`INSERT INTO session_inbox
|
|
234
|
+
(session_id, title, created_at, last_activity_at, settled_at, outcome,
|
|
235
|
+
state, tier, revision)
|
|
236
|
+
SELECT id, ?, created_at, COALESCE(?, created_at), NULL, NULL, 'done', 2,
|
|
237
|
+
${GP}
|
|
238
|
+
FROM sessions
|
|
239
|
+
WHERE id = ?
|
|
240
|
+
ON CONFLICT (session_id) DO UPDATE SET
|
|
241
|
+
title = CASE WHEN ? = 1 THEN excluded.title ELSE title END,
|
|
242
|
+
last_activity_at = MAX(last_activity_at, excluded.last_activity_at),
|
|
243
|
+
revision = excluded.revision`,n,t.activityAt??null,t.sessionId,r)}function qP(e,t){WP(e),e.sql.exec(`INSERT INTO session_inbox_tombstones (session_id, revision)
|
|
244
|
+
VALUES (?, ${GP})
|
|
245
|
+
ON CONFLICT (session_id) DO UPDATE SET revision = excluded.revision`,t)}function JP(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=FP(r);if(i._tag===`Failure`)throw BP(`Stored inbox row is invalid`);let a=t.settled?.outcome??i.success.outcome,o=HP(t.head,a,sj(e,t.queue));WP(e),e.sql.exec(`UPDATE session_inbox
|
|
246
|
+
SET outcome = ?, state = ?, tier = ?, revision = ${GP},
|
|
247
|
+
settled_at = CASE WHEN ? = 1 THEN ? ELSE settled_at END,
|
|
248
|
+
last_activity_at = MAX(last_activity_at, ?)
|
|
249
|
+
WHERE session_id = ?`,a,o,VP(o),t.settled===void 0?0:1,n,n,t.queue)}function YP(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=FP(r);if(i._tag===`Failure`)throw BP(`Stored inbox row is invalid`);let a=HP(n,i.success.outcome,sj(e,t));WP(e),e.sql.exec(`UPDATE session_inbox SET state = ?, tier = ?, revision = ${GP} WHERE session_id = ?`,a,VP(a),t)}function XP(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 ZP(e){let t=LP(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function QP(e,t){let n=t===void 0?void 0:ZP(t),r=n===void 0?e.sql.exec(`SELECT ${zP} FROM session_inbox
|
|
250
|
+
ORDER BY tier ASC, last_activity_at DESC, session_id ASC
|
|
251
|
+
LIMIT ?`,TP).toArray():e.sql.exec(`SELECT ${zP} FROM session_inbox
|
|
252
|
+
WHERE tier > ?
|
|
253
|
+
OR (tier = ? AND last_activity_at < ?)
|
|
254
|
+
OR (tier = ? AND last_activity_at = ? AND session_id > ?)
|
|
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],TP).toArray(),i=[],a;for(let e of r){let t=PP(e);if(t._tag===`Failure`)throw BP(`Stored inbox row is invalid`);let n=t.success;a=[n.tier,n.last_activity_at,n.session_id],i.push(XP(n))}return{sessions:i,next:r.length===TP&&a!==void 0?RP(a):void 0}}var $P={onExcessProperty:`error`};function eF(e){return new G(`store`,`incompatible`,e)}var tF=P({id:M,timestamp:N,data_json:M}),nF=U(P({kind:j(`compaction`),workId:M,resumesRun:k(Gm),trigger:k(L([`manual`,`threshold`,`overflow`])),tokensAfter:k(N),firstKeptEntryId:M,summary:M,tokensBefore:N,usage:AM,contextRevision:M,details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})),rF=D(tF,$P),iF=D(nF,$P);function aF(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=rF(n);if(je(t))throw eF(`Stored compaction row cannot be read`);let r=iF(t.success.data_json);if(je(r))throw eF(`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 = ?`,aN({kind:`compaction`,workId:i.workId,head:i.firstKeptEntryId,model:[JN(i.summary,t.success.timestamp)],data:a}),t.success.id)}}var oF=D(P({data_json:M}),$P);function sF(e){e.sql.exec(`UPDATE session_entries
|
|
257
|
+
SET data_json = json_set(
|
|
258
|
+
json_remove(data_json, '$.result.details'),
|
|
259
|
+
'$.data', json(json_extract(data_json, '$.result.details'))
|
|
260
|
+
)
|
|
261
|
+
WHERE type = 'tool_outcome'
|
|
262
|
+
AND json_type(data_json, '$.result.details') IS NOT NULL
|
|
263
|
+
AND json_type(data_json, '$.data') IS NULL`),e.sql.exec(`UPDATE session_entries
|
|
264
|
+
SET data_json = json_set(
|
|
265
|
+
json_remove(data_json, '$.value.details'),
|
|
266
|
+
'$.data', json(json_extract(data_json, '$.value.details'))
|
|
267
|
+
)
|
|
268
|
+
WHERE type = 'message'
|
|
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=oF(t);if(je(e)||iN(e.success.data_json)._tag===`Failure`)throw eF(`A stored tool result cannot be read`)}}var cF=M.pipe(z($h(1))),lF=H.pipe(z(V(0))),uF=P({name:M}),dF=P({sql:M}),fF=P({extension_id:cF,key:cF,due_at:lF}),pF=P({extension_id:cF}),mF=P({seq:lF}),hF=P({count:lF}),gF=P({data_json:M});function _F(e){return new G(`store`,`incompatible`,e)}function vF(e,t,n){let r=D(e);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw _F(n);return t.success})}function yF(e,t,...n){return e.sql.exec(t,...n).toArray()}function bF(e,t){return vF(uF,yF(e,`PRAGMA table_info(${t})`),`Store table description is invalid`).map(e=>e.name)}function xF(e,t){let n=vF(hF,yF(e,`SELECT COUNT(*) AS count FROM ${t}`),`Store row count is invalid`)[0];if(n===void 0)throw _F(`Store row count is missing`);return n.count}var SF=`
|
|
271
|
+
CREATE TABLE watchdog_jobs (
|
|
272
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
273
|
+
job_id TEXT UNIQUE NOT NULL,
|
|
274
|
+
queue_name TEXT NOT NULL,
|
|
275
|
+
lane TEXT NOT NULL,
|
|
276
|
+
priority INTEGER NOT NULL,
|
|
277
|
+
payload_json TEXT NOT NULL,
|
|
278
|
+
not_before INTEGER NOT NULL DEFAULT 0 CHECK (not_before >= 0),
|
|
279
|
+
attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0),
|
|
280
|
+
recovery_max INTEGER,
|
|
281
|
+
recovery_window_ms INTEGER CHECK (recovery_window_ms IS NULL OR recovery_window_ms > 0),
|
|
282
|
+
recovery_window_started_at INTEGER,
|
|
283
|
+
state TEXT NOT NULL CHECK (state IN ('queued', 'running', 'completing', 'settled')),
|
|
284
|
+
outcome TEXT CHECK (
|
|
285
|
+
outcome IS NULL OR outcome IN (
|
|
286
|
+
'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
|
|
287
|
+
)
|
|
288
|
+
),
|
|
289
|
+
claim_token TEXT,
|
|
290
|
+
recovery_count INTEGER NOT NULL DEFAULT 0,
|
|
291
|
+
cancellation_id TEXT UNIQUE,
|
|
292
|
+
failure_reason TEXT,
|
|
293
|
+
CHECK (recovery_max IS NULL OR recovery_max >= 0),
|
|
294
|
+
CONSTRAINT watchdog_execution_state CHECK (
|
|
295
|
+
(state = 'queued' AND outcome IS NULL AND claim_token IS NULL) OR
|
|
296
|
+
(state = 'running' AND outcome IS NULL AND claim_token IS NOT NULL) OR
|
|
297
|
+
(state = 'completing' AND outcome IS NOT NULL AND claim_token IS NOT NULL) OR
|
|
298
|
+
(state = 'settled' AND outcome IS NOT NULL)
|
|
299
|
+
)
|
|
300
|
+
)
|
|
301
|
+
`,CF=[`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`],wF=[`sequence`,`job_id`,`queue_name`,`lane`,`priority`,`payload_json`,`recovery_max`,`state`,`outcome`,`claim_token`,`recovery_count`,`cancellation_id`,`failure_reason`],TF=`watchdog_jobs_before_marker_6`;function EF(e){let t=bF(e,`watchdog_jobs`);if(t.length===0||vF(dF,yF(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&&CF.every(e=>t.includes(e)))return;if(!wF.every(e=>t.includes(e)))throw _F(`Watchdog jobs table has an unknown shape`);let n=CF.filter(e=>t.includes(e)),r=xF(e,`watchdog_jobs`);e.sql.exec(`ALTER TABLE watchdog_jobs RENAME TO ${TF}`),e.sql.exec(SF);let i=n.join(`, `);if(e.sql.exec(`INSERT INTO watchdog_jobs (${i}) SELECT ${i} FROM ${TF} ORDER BY sequence`),xF(e,`watchdog_jobs`)!==r)throw _F(`Watchdog jobs were not all carried over`);let a=vF(mF,yF(e,`SELECT seq FROM sqlite_sequence WHERE name = ?`,TF),`Watchdog job counter is invalid`)[0];e.sql.exec(`DROP TABLE ${TF}`),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 DF=`shiitake_extension_timers_before_marker_6`;function OF(e){let t=bF(e,`shiitake_extension_timers`);if(t.length===0||t.includes(`job_id`))return;let n=vF(fF,yF(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&&bF(e,`watchdog_jobs`).length===0)throw _F(`Extension timers have no Watchdog jobs to move to`);let r=new Set(bF(e,`shiitake_extension_status`).length===0?[]:vF(pF,yF(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 ${DF}`),e.sql.exec(`CREATE TABLE shiitake_extension_timers (
|
|
302
|
+
extension_id TEXT NOT NULL,
|
|
303
|
+
key TEXT NOT NULL,
|
|
304
|
+
job_id TEXT NOT NULL,
|
|
305
|
+
PRIMARY KEY (extension_id, key)
|
|
306
|
+
)`);for(let t of n){let n=oN.work.generate();e.sql.exec(`INSERT INTO watchdog_jobs
|
|
307
|
+
(job_id, queue_name, lane, priority, payload_json, not_before,
|
|
308
|
+
state, outcome, claim_token, recovery_count, cancellation_id)
|
|
309
|
+
VALUES (?, ?, ?, 0, ?, ?, 'queued', NULL, NULL, 0, ?)`,n,n,AN,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 ${DF}`)}function kF(e){e.sql.exec(`UPDATE session_entries
|
|
310
|
+
SET data_json = json_set(
|
|
311
|
+
data_json, '$.event.dueAt',
|
|
312
|
+
CAST(timestamp + json_extract(data_json, '$.event.delayMs') AS INTEGER)
|
|
313
|
+
)
|
|
314
|
+
WHERE type = 'live_retry'
|
|
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 vF(gF,yF(e,`SELECT data_json FROM session_entries WHERE type = 'live_retry'`),`Stored retry fact is invalid`))if(iN(t.data_json)._tag===`Failure`)throw _F(`A stored retry fact cannot be read`)}var AF=[`private_local_exec_rules`,`local_birddog_outbox`];function jF(e){for(let t of AF)e.sql.exec(`DROP TABLE IF EXISTS ${t}`)}function MF(e){e.sql.exec(`DROP TABLE IF EXISTS oyster_conversation_agents`)}var NF=[{marker:2,apply:aF},{marker:3,apply:sF},{marker:5,apply:kF},{marker:6,apply:EF},{marker:6,apply:OF},{marker:6,apply:jF},{marker:7,apply:MF}],PF=P({version:H});function FF(e){let t=vF(PF,yF(e,`SELECT version FROM woodstock_schema`),`Woodstock schema marker is invalid`)[0];if(t===void 0)throw _F(`Woodstock schema marker is missing`);for(let n of NF)n.marker>t.version&&n.apply(e)}function IF(e){let t=[...e].reverse().find(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`),n=LF(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(!zF(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 LF(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 RF(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 zF(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 BF(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=zF(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 VF={onExcessProperty:`error`},HF=new TextEncoder,UF=M.pipe(z($h(1)),z(B(e=>HF.encode(e).byteLength<=256))),WF=H.pipe(z(Ph(0))),GF=H.pipe(z(V(0))),KF=P({id:UF,leaf_id:R(UF)}),qF=P({session_id:UF}),JF=P({id:UF,leaf_id:R(UF),created_at:GF,updated_at:GF,metadata_json:R(M)}),YF=U(P({title:zx})),XF=D(YF,VF),ZF=Fm(YF),QF=P({id:UF}),$F=P({version:H,protocol:M}),eI=P({name:UF}),tI=P({id:UF,session_id:UF,parent_id:R(UF),sequence:WF,type:M,role:R(L([`user`,`assistant`,`tool_result`])),state:L([`complete`,`streaming`]),request_id:R(UF),work_id:R(UF),data_json:M,timestamp:GF,completed_at:R(GF),damaged:L([0,1])}),nI=P({id:UF,session_id:UF,sequence:WF,request_id:UF,work_id:UF,data_json:M,timestamp:GF,origin_kind:L([`user`,`extension`]),origin_id:R(UF),origin_correlation:R(UF)}),rI=P({kind:j(`extension`),extensionId:UF,correlation:R(UF)}),iI=I([P({kind:j(`user`)}),rI]),aI=D(iI,VF),oI=jg(iI),sI=e=>[`id`,`session_id`,`sequence`,`request_id`,`work_id`,`data_json`,`timestamp`,`origin_kind`,`origin_id`,`origin_correlation`].map(t=>e+t).join(`, `),cI=P({next_sequence:WF}),lI=P({present:j(1)}),uI=D(qF,VF),dI=D(JF,VF),fI=D(QF,VF),pI=D($F,VF),mI=D(eI,VF),hI=D(P({candidate_id:R(UF),path_count:H.pipe(z(Ph(0))),root_count:H.pipe(z(V(0))),missing_parent_count:H.pipe(z(V(0))),leaf_state:L([`complete`,`streaming`])}),VF),gI=D(tI,VF),_I=D(nI,VF),vI=D(cI,VF),yI=D(lI,VF);function bI(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
|
+
EXISTS (SELECT 1 FROM session_lineage_damage AS damage
|
|
318
|
+
WHERE damage.session_id = ${e}.session_id) AS damaged`}var xI=bI(`session_entries`);function SI(e,t){return t===void 0?e:{...e,meta:t}}function CI(e,t){if(LI(e,t)===void 0)return;let n=e.sql.exec(`SELECT id, leaf_id, created_at, updated_at, metadata_json
|
|
319
|
+
FROM sessions
|
|
320
|
+
WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=dI(n);if(r._tag===`Failure`)throw $(`Stored Session summary row is invalid`);let i=DI(e,t,r.success),a=r.success.metadata_json;if(a===null)return i;let o=XF(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 wI=D(P({id:UF,sequence:WF}),VF);function TI(e,t,n,r){let i=e.sql.exec(`SELECT command.id AS id, command.sequence AS sequence
|
|
321
|
+
FROM session_entries AS command
|
|
322
|
+
WHERE command.session_id = ? AND command.type = 'command'
|
|
323
|
+
AND command.role = 'user' AND command.state = 'complete'
|
|
324
|
+
AND NOT EXISTS (
|
|
325
|
+
SELECT 1 FROM session_entries AS cancelled
|
|
326
|
+
WHERE cancelled.work_id = command.work_id
|
|
327
|
+
AND cancelled.session_id = command.session_id
|
|
328
|
+
AND cancelled.type = 'cancellation'
|
|
329
|
+
AND cancelled.sequence < command.sequence
|
|
330
|
+
)
|
|
331
|
+
ORDER BY command.sequence ASC LIMIT 1`,t).toArray()[0];if(i===void 0)return null;let a=wI(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
|
+
WHERE parent.session_id = ? AND parent.sequence < ?
|
|
333
|
+
AND (SELECT COUNT(*) FROM session_entries AS child
|
|
334
|
+
WHERE child.parent_id = parent.id
|
|
335
|
+
AND child.session_id = parent.session_id
|
|
336
|
+
AND child.state = 'complete') > 1
|
|
337
|
+
LIMIT 1`,t,o.sequence).toArray()[0]===void 0?o.id:EI(e,t,n)}function EI(e,t,n){let r=hI(e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, type, role, state, work_id) AS (
|
|
338
|
+
SELECT id, parent_id, sequence, type, role, state, work_id
|
|
339
|
+
FROM session_entries
|
|
340
|
+
WHERE session_id = ? AND id = ?
|
|
341
|
+
UNION
|
|
342
|
+
SELECT parent.id, parent.parent_id, parent.sequence,
|
|
343
|
+
parent.type, parent.role, parent.state, parent.work_id
|
|
344
|
+
FROM branch AS child
|
|
345
|
+
CROSS JOIN session_entries AS parent
|
|
346
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
347
|
+
)
|
|
348
|
+
SELECT
|
|
349
|
+
(SELECT command.id FROM branch AS command
|
|
350
|
+
WHERE command.type = 'command' AND command.role = 'user'
|
|
351
|
+
AND command.state = 'complete'
|
|
352
|
+
AND NOT EXISTS (
|
|
353
|
+
SELECT 1 FROM branch AS cancelled
|
|
354
|
+
WHERE cancelled.type = 'cancellation'
|
|
355
|
+
AND cancelled.work_id = command.work_id
|
|
356
|
+
AND cancelled.sequence < command.sequence
|
|
357
|
+
)
|
|
358
|
+
ORDER BY command.sequence ASC LIMIT 1) AS candidate_id,
|
|
359
|
+
(SELECT COUNT(*) FROM branch) AS path_count,
|
|
360
|
+
(SELECT COUNT(*) FROM branch WHERE parent_id IS NULL) AS root_count,
|
|
361
|
+
(SELECT COUNT(*) FROM branch AS child
|
|
362
|
+
WHERE child.parent_id IS NOT NULL
|
|
363
|
+
AND NOT EXISTS (
|
|
364
|
+
SELECT 1 FROM session_entries AS parent
|
|
365
|
+
WHERE parent.session_id = ? AND parent.id = child.parent_id
|
|
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 DI(e,t,n){if(n.leaf_id===null)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:``});let r=RI(e,t,n.leaf_id);if(r?.state!==`complete`)throw $(`Stored Session summary leaf is invalid`);let i=TI(e,t,n.leaf_id,r.sequence),a=i===null?void 0:RI(e,t,i)?.entry,o=a===void 0?void 0:$M(a);if(o!==void 0)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:Array.from(WR(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 OI(e,t){try{return CI(e,t)?.title??``}catch(e){if(e instanceof G&&e.cause===`unavailable`)return null;throw e}}function $(e){return new G(`store`,`unavailable`,e)}function kI(e){return new G(`store`,`incompatible`,e)}function AI(e){return e.kind===`command`||e.kind===`cancellation`||e.kind===`operator`?e.requestId:null}function jI(e){return e.kind===`command`?QM(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 MI(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function NI(e,t){let n=gI(t);if(n._tag===`Failure`)throw $(`Stored Session entry row is invalid`);let r=n.success;if(r.damaged===1)throw OL(e,r.session_id);let i=iN(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!==AI(a)||r.role!==jI(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 PI(e){let t=_I(e);if(t._tag===`Failure`)throw $(`Stored command admission row is invalid`);let n=t.success,r=iN(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!==eN(i))throw $(`Stored command admission columns disagree with its data`);let a=aI(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 FI(e,t){return LI(e,t)!==void 0}var II=D(P({...KF.fields,damaged:L([0,1])}),VF);function LI(e,t){let n=e.sql.exec(`SELECT id, leaf_id,
|
|
368
|
+
EXISTS (SELECT 1 FROM session_lineage_damage
|
|
369
|
+
WHERE session_id = sessions.id) AS damaged
|
|
370
|
+
FROM sessions WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=II(n);if(r._tag===`Failure`)throw $(`Stored Session row is invalid`);if(r.success.damaged===1)throw OL(e,t);return Object.freeze({id:r.success.id,leaf_id:r.success.leaf_id})}function RI(e,t,n){let r=e.sql.exec(`SELECT ${xI}
|
|
371
|
+
FROM session_entries
|
|
372
|
+
WHERE session_id = ? AND id = ?`,t,n).toArray()[0];return r===void 0?void 0:NI(e,r)}function zI(e,t){if(t.leaf_id===null){let n=e.sql.exec(`SELECT 1 AS present
|
|
373
|
+
FROM session_entries
|
|
374
|
+
WHERE session_id = ?
|
|
375
|
+
LIMIT 1`,t.id).toArray()[0];if(n===void 0)return;throw yI(n)._tag===`Failure`?$(`Session entry presence is invalid`):$(`Session leaf is invalid`)}let n=RI(e,t.id,t.leaf_id);if(n?.state!==`complete`)throw $(`Session leaf is invalid`);return n}function BI(e,t){let n=e.sql.exec(`SELECT ${xI}
|
|
376
|
+
FROM session_entries
|
|
377
|
+
WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:NI(e,n)}function VI(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 ${sI(``)}
|
|
378
|
+
FROM session_command_admissions
|
|
379
|
+
WHERE session_id = ? AND ${r} = ?`,t,i).toArray()[0];return a===void 0?void 0:PI(a)}var HI=`FROM session_command_admissions AS a
|
|
380
|
+
WHERE a.session_id = ?
|
|
381
|
+
AND NOT EXISTS (
|
|
382
|
+
SELECT 1 FROM session_entries AS e
|
|
383
|
+
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
384
|
+
AND e.type IN ('command', 'cancellation', 'run_terminal', 'work_terminal')
|
|
385
|
+
)`;function UI(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 WI=O(P({identity:R(M)}));function GI(e,t,n){let{identity:r}=WI(e.sql.exec(`SELECT json_extract(?, ?) AS identity`,JSON.stringify(n??null),t).one());if(r===null||r.length===0)throw new G(`runtime`,`rejected`,`Request author is required`);return{path:t,value:r}}function KI(e,t,n,r){let i=eL(e,t,n);if(i!==void 0&&GI(e,r.path,i.entry.meta).value!==r.value)throw new G(`runtime`,`rejected`,`Message author does not match`)}function qI(e,t,n){let r=e.sql.exec(`SELECT ${sI(`a.`)} ${HI}
|
|
386
|
+
AND json_extract(a.data_json, '$.work') IS NULL
|
|
387
|
+
AND a.origin_kind = 'user'
|
|
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:PI(r)}var JI=O(P({total:H.check(V(0))}));function YI(e,t,n,r=`all`){let i=r===`prompts`?`AND json_extract(a.data_json, '$.work') IS NULL`:``,a=JI(e.sql.exec(`SELECT COUNT(*) AS total ${HI} ${i}`,t).one()).total;return{commands:e.sql.exec(`SELECT ${sI(`a.`)} ${HI} ${i}
|
|
390
|
+
ORDER BY (json_extract(a.data_json, '$.delivery') = 'steer') DESC,
|
|
391
|
+
a.sequence ASC LIMIT ?`,t,n).toArray().map(PI),total:a}}function XI(e,t,n,r,i=200){return e.sql.exec(`SELECT ${sI(`a.`)}
|
|
392
|
+
FROM session_command_admissions AS a
|
|
393
|
+
WHERE a.session_id = ?
|
|
394
|
+
AND json_extract(a.data_json, '$.delivery') = ?
|
|
395
|
+
AND (? IS NULL OR json_extract(a.data_json, '$.targetWorkId') = ?)
|
|
396
|
+
AND NOT EXISTS (
|
|
397
|
+
SELECT 1 FROM session_entries AS e
|
|
398
|
+
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
399
|
+
AND e.type IN ('command', 'run_terminal', 'work_terminal')
|
|
400
|
+
)
|
|
401
|
+
ORDER BY a.sequence ASC LIMIT ?`,t,n,r??null,r??null,i).toArray().map(PI)}function ZI(e,t,n){return XI(e,t,`steer`,n,1).length>0}function QI(e,t,n,r){return e.transactionSync(()=>XI(e,t,n,r).map(n=>{let r=$M(RI(e,t,n.id)?.entry??RL(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:nN(r)}}))}function $I(e,t){e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${sI(`a.`)}
|
|
402
|
+
FROM session_command_admissions AS a
|
|
403
|
+
WHERE a.session_id = ?
|
|
404
|
+
AND json_extract(a.data_json, '$.delivery') = 'steer'
|
|
405
|
+
AND json_extract(a.data_json, '$.targetWorkId') = ?
|
|
406
|
+
ORDER BY a.sequence ASC`,t.sessionId,t.parentWorkId).toArray().map(PI);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(RI(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}),RL(e,{sessionId:t.sessionId,id:oN.fact.generate(),entry:i})}})}function eL(e,t,n){return VI(e,t,{id:n})}function tL(e,t,n){return VI(e,t,{workId:n})}function nL(e,t,n){return VI(e,t,{requestId:n})}function rL(e,t,n){return LI(e,t),e.sql.exec(`SELECT 1 AS present FROM session_entries
|
|
407
|
+
INDEXED BY idx_session_entries_work_terminal
|
|
408
|
+
WHERE session_id = ? AND work_id = ?
|
|
409
|
+
AND type IN ('run_terminal', 'work_terminal')
|
|
410
|
+
LIMIT 1`,t,n).toArray().length>0}function iL(e,t,n){return LI(e,t),Object.freeze(e.sql.exec(`SELECT ${xI}
|
|
411
|
+
FROM session_entries
|
|
412
|
+
WHERE session_id = ? AND work_id = ?
|
|
413
|
+
ORDER BY sequence ASC`,t,n).toArray().map(t=>NI(e,t)))}function aL(e,t,n){let r=e.sql.exec(`SELECT ${xI}
|
|
414
|
+
FROM session_entries
|
|
415
|
+
WHERE session_id = ? AND work_id = ? AND type = 'live_retry'
|
|
416
|
+
ORDER BY sequence DESC
|
|
417
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=NI(e,r);if(i.entry.kind!==`live_retry`)throw $(`Stored live retry entry is invalid`);return{event:i.entry.event,timestamp:i.timestamp}}function oL(e,t,n,r){return e.sql.exec(`SELECT 1 FROM session_entries INDEXED BY idx_session_entries_successful_tool
|
|
418
|
+
WHERE session_id = ? AND work_id = ? AND type = 'tool_outcome'
|
|
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 sL(e,t,n){let r=e.sql.exec(`SELECT ${bI(`intent`)}
|
|
421
|
+
FROM session_entries AS intent
|
|
422
|
+
WHERE intent.session_id = ? AND intent.work_id = ?
|
|
423
|
+
AND intent.type = 'tool_intent'
|
|
424
|
+
AND NOT EXISTS (
|
|
425
|
+
SELECT 1 FROM session_entries AS outcome
|
|
426
|
+
WHERE outcome.session_id = intent.session_id
|
|
427
|
+
AND outcome.work_id = intent.work_id
|
|
428
|
+
AND outcome.type = 'tool_outcome'
|
|
429
|
+
AND json_extract(outcome.data_json, '$.toolCall.value') =
|
|
430
|
+
json_extract(intent.data_json, '$.toolCall.value')
|
|
431
|
+
)
|
|
432
|
+
ORDER BY intent.sequence DESC
|
|
433
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=NI(e,r);if(i.entry.kind!==`tool_intent`)throw $(`Stored tool intent is invalid`);return i.entry.call.name}function cL(e,t){let n=vI(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
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 lL(e,t){let n=vI(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
436
|
+
FROM (
|
|
437
|
+
SELECT sequence
|
|
438
|
+
FROM session_command_admissions
|
|
439
|
+
WHERE session_id = ?
|
|
440
|
+
UNION ALL
|
|
441
|
+
SELECT sequence
|
|
442
|
+
FROM session_entries
|
|
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 uL(e,t){let n=LI(e,t);if(n!==void 0)return n;let r=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
445
|
+
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
446
|
+
VALUES (?, '/', NULL, NULL, ?, ?, NULL)`,t,r,r),KP(e,{sessionId:t,activityAt:r,title:``});let i=LI(e,t);if(i===void 0)throw $(`Created Session row is unavailable`);return i}function dL(e,t,n){return e.transactionSync(()=>fL(e,t,n))}function fL(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=uI(r);if(e._tag===`Failure`)throw $(`Session creation receipt is invalid`);return e.success.session_id}n();let i=oN.session.generate();return uL(e,i),e.sql.exec(`INSERT INTO session_creation_receipts (request_id, session_id) VALUES (?, ?)`,t,i),i}function pL(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 mL=7,hL=1,gL=`shiitake.extension/v0`;function _L(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(mI(n)._tag===`Failure`)throw $(`Store catalog row is invalid`);return!0}function vL(e){if(!_L(e,`woodstock_schema`))return _L(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=pI(t[0]);if(n._tag!==`Success`)return`unmarked`;let r=n.success.version;return r>mL?`newer`:n.success.protocol===gL?r===mL?`v0`:r>=hL&&r<mL?`upgradable`:`unmarked`:`unmarked`}function yL(e){FF(e),e.sql.exec(`UPDATE woodstock_schema SET version = ?`,mL)}function bL(e){let t=vL(e);if(t!==`v0`){if(t===`upgradable`){yL(e);return}if(t===`newer`)throw kI(`This Agent was saved by a newer Fungi. Update Fungi to open it. Its files have not been changed.`);if(t===`unmarked`)throw kI(`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 (?, ?)`,mL,gL)}}function xL(e){e.sql.exec(`
|
|
447
|
+
CREATE TABLE IF NOT EXISTS session_entries (
|
|
448
|
+
id TEXT PRIMARY KEY,
|
|
449
|
+
session_id TEXT NOT NULL,
|
|
450
|
+
parent_id TEXT,
|
|
451
|
+
sequence INTEGER NOT NULL,
|
|
452
|
+
type TEXT NOT NULL,
|
|
453
|
+
role TEXT,
|
|
454
|
+
state TEXT NOT NULL CHECK (state IN ('complete', 'streaming')),
|
|
455
|
+
request_id TEXT,
|
|
456
|
+
work_id TEXT,
|
|
457
|
+
data_json TEXT NOT NULL,
|
|
458
|
+
timestamp INTEGER NOT NULL,
|
|
459
|
+
completed_at INTEGER,
|
|
460
|
+
UNIQUE (session_id, sequence)
|
|
461
|
+
)
|
|
462
|
+
`)}var SL=[`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`],CL=D(P({installed:H.pipe(z(V(0)))}),VF),wL=D(P({session_id:M}),VF),TL=`Woodstock Session holds a broken lineage; a store never repairs itself — delete this Session (deleteSession), or reset the owning store`,EL=D(P({damaged:H.pipe(z(Ph(0))),first:M}),VF),DL=class extends G{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 OL(e,t){let n=e.storeName??`Woodstock store`;return new DL(n,t,`${n}: ${AL(e,t)}`)}function kL(e,t){return e.sql.exec(`SELECT session_id FROM session_lineage_damage WHERE session_id = ?`,t).toArray().length>0}function AL(e,t){let n=EL(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 jL(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_lineage_damage (session_id TEXT PRIMARY KEY)`);let t=CL(e.sql.exec(`SELECT COUNT(*) AS installed FROM sqlite_master
|
|
463
|
+
WHERE type = 'trigger'
|
|
464
|
+
AND name IN (SELECT value FROM json_each(?))`,JSON.stringify(SL)).one());if(t._tag===`Failure`)throw $(`Stored Session lineage guards are invalid`);if(t.success.installed!==SL.length){let t=e.sql.exec(`SELECT child.session_id AS session_id
|
|
465
|
+
FROM session_entries AS child
|
|
466
|
+
LEFT JOIN session_entries AS parent ON parent.id = child.parent_id
|
|
467
|
+
WHERE child.parent_id IS NOT NULL
|
|
468
|
+
AND (parent.id IS NULL
|
|
469
|
+
OR parent.session_id != child.session_id
|
|
470
|
+
OR parent.state != 'complete'
|
|
471
|
+
OR parent.sequence >= child.sequence)
|
|
472
|
+
UNION
|
|
473
|
+
SELECT session_id FROM session_entries
|
|
474
|
+
WHERE parent_id IS NULL AND state = 'complete'
|
|
475
|
+
GROUP BY session_id HAVING COUNT(*) > 1`).toArray().map(e=>{let t=wL(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),KP(e,{sessionId:n,title:null})}e.sql.exec(`
|
|
476
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_replace
|
|
477
|
+
BEFORE INSERT ON session_entries
|
|
478
|
+
WHEN EXISTS (
|
|
479
|
+
SELECT 1 FROM session_entries AS child
|
|
480
|
+
WHERE child.parent_id = NEW.id
|
|
481
|
+
AND (child.session_id != NEW.session_id
|
|
482
|
+
OR child.sequence <= NEW.sequence
|
|
483
|
+
OR NEW.state != 'complete'))
|
|
484
|
+
BEGIN
|
|
485
|
+
SELECT RAISE(ABORT, 'Session entry would strand its children');
|
|
486
|
+
END
|
|
487
|
+
`),e.sql.exec(`
|
|
488
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_replace_position
|
|
489
|
+
BEFORE INSERT ON session_entries
|
|
490
|
+
WHEN EXISTS (
|
|
491
|
+
SELECT 1 FROM session_entries AS held
|
|
492
|
+
JOIN session_entries AS child ON child.parent_id = held.id
|
|
493
|
+
WHERE held.session_id = NEW.session_id
|
|
494
|
+
AND held.sequence = NEW.sequence
|
|
495
|
+
AND held.id != NEW.id)
|
|
496
|
+
BEGIN
|
|
497
|
+
SELECT RAISE(ABORT, 'Session entry would strand its children');
|
|
498
|
+
END
|
|
499
|
+
`),e.sql.exec(`
|
|
500
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_damaged_session
|
|
501
|
+
BEFORE INSERT ON session_entries
|
|
502
|
+
WHEN EXISTS (
|
|
503
|
+
SELECT 1 FROM session_lineage_damage WHERE session_id = NEW.session_id)
|
|
504
|
+
BEGIN
|
|
505
|
+
SELECT RAISE(ABORT, '${TL}');
|
|
506
|
+
END
|
|
507
|
+
`),e.sql.exec(`
|
|
508
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_insert
|
|
509
|
+
BEFORE INSERT ON session_entries
|
|
510
|
+
BEGIN
|
|
511
|
+
SELECT RAISE(ABORT, 'Session entry parent is not an earlier complete entry of its Session')
|
|
512
|
+
WHERE NEW.parent_id IS NOT NULL AND NOT EXISTS (
|
|
513
|
+
SELECT 1 FROM session_entries AS parent
|
|
514
|
+
WHERE parent.id = NEW.parent_id
|
|
515
|
+
AND parent.session_id = NEW.session_id
|
|
516
|
+
AND parent.state = 'complete'
|
|
517
|
+
AND parent.sequence < NEW.sequence);
|
|
518
|
+
SELECT RAISE(ABORT, 'Session already has a root entry')
|
|
519
|
+
WHERE NEW.parent_id IS NULL AND EXISTS (
|
|
520
|
+
SELECT 1 FROM session_entries AS other
|
|
521
|
+
WHERE other.session_id = NEW.session_id
|
|
522
|
+
AND other.state = 'complete'
|
|
523
|
+
AND other.id != NEW.id);
|
|
524
|
+
END
|
|
525
|
+
`),e.sql.exec(`
|
|
526
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_update
|
|
527
|
+
BEFORE UPDATE OF id, session_id, parent_id, sequence, state
|
|
528
|
+
ON session_entries
|
|
529
|
+
BEGIN
|
|
530
|
+
SELECT RAISE(ABORT, 'Session entry lineage columns are immutable');
|
|
531
|
+
END
|
|
532
|
+
`),e.sql.exec(`
|
|
533
|
+
CREATE TRIGGER IF NOT EXISTS session_entries_lineage_delete
|
|
534
|
+
BEFORE DELETE ON session_entries
|
|
535
|
+
WHEN EXISTS (SELECT 1 FROM sessions WHERE id = OLD.session_id)
|
|
536
|
+
AND EXISTS (SELECT 1 FROM session_entries WHERE parent_id = OLD.id)
|
|
537
|
+
BEGIN
|
|
538
|
+
SELECT RAISE(ABORT, 'Session entry still has children');
|
|
539
|
+
END
|
|
540
|
+
`)}function ML(e){e.transactionSync(()=>{NL(e)})}function NL(e){bL(e),e.sql.exec(`
|
|
541
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
542
|
+
id TEXT PRIMARY KEY,
|
|
543
|
+
cwd TEXT NOT NULL,
|
|
544
|
+
parent_session TEXT,
|
|
545
|
+
leaf_id TEXT,
|
|
546
|
+
created_at INTEGER NOT NULL,
|
|
547
|
+
updated_at INTEGER NOT NULL,
|
|
548
|
+
metadata_json TEXT
|
|
549
|
+
)
|
|
550
|
+
`),xL(e),HN(e),aj(e),Zj(e),Vj(e),bP(e),UP(e),e.sql.exec(`
|
|
551
|
+
CREATE TABLE IF NOT EXISTS session_creation_receipts (
|
|
552
|
+
request_id TEXT PRIMARY KEY,
|
|
553
|
+
session_id TEXT NOT NULL UNIQUE REFERENCES sessions(id)
|
|
554
|
+
)
|
|
555
|
+
`),e.sql.exec(`DELETE FROM session_delegators
|
|
556
|
+
WHERE NOT EXISTS (
|
|
557
|
+
SELECT 1 FROM session_creation_receipts AS creation
|
|
558
|
+
WHERE creation.session_id = session_delegators.session_id
|
|
559
|
+
AND creation.request_id = session_delegators.mail_key
|
|
560
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_parent ON session_entries(parent_id)`),e.sql.exec(`DROP INDEX IF EXISTS idx_session_entries_lineage`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_ancestry
|
|
561
|
+
ON session_entries(id, session_id, parent_id, sequence, state, type)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_session ON session_entries(session_id, sequence)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_streaming ON session_entries(session_id, state)`),e.sql.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_session_entries_request
|
|
562
|
+
ON session_entries(session_id, request_id)
|
|
563
|
+
WHERE request_id IS NOT NULL`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_work ON session_entries(work_id, sequence)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_work_terminal
|
|
564
|
+
ON session_entries(session_id, work_id)
|
|
565
|
+
WHERE type IN ('run_terminal', 'work_terminal')`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_model_preference
|
|
566
|
+
ON session_entries(session_id, sequence)
|
|
567
|
+
WHERE type = 'model_preference'`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_cancellation_target
|
|
568
|
+
ON session_entries(session_id, json_extract(data_json, '$.targetWorkId'))
|
|
569
|
+
WHERE type = 'cancellation'`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_successful_tool
|
|
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`),jL(e),e.sql.exec(`
|
|
572
|
+
CREATE TABLE IF NOT EXISTS session_request_withdrawals (
|
|
573
|
+
session_id TEXT NOT NULL,
|
|
574
|
+
request_id TEXT NOT NULL,
|
|
575
|
+
PRIMARY KEY (session_id, request_id)
|
|
576
|
+
)
|
|
577
|
+
`),e.sql.exec(`
|
|
578
|
+
CREATE TABLE IF NOT EXISTS session_command_admissions (
|
|
579
|
+
id TEXT PRIMARY KEY,
|
|
580
|
+
session_id TEXT NOT NULL,
|
|
581
|
+
sequence INTEGER NOT NULL,
|
|
582
|
+
request_id TEXT NOT NULL,
|
|
583
|
+
work_id TEXT NOT NULL,
|
|
584
|
+
data_json TEXT NOT NULL,
|
|
585
|
+
timestamp INTEGER NOT NULL,
|
|
586
|
+
origin_kind TEXT NOT NULL CHECK (origin_kind IN ('user', 'extension')),
|
|
587
|
+
origin_id TEXT,
|
|
588
|
+
origin_correlation TEXT,
|
|
589
|
+
CHECK ((origin_kind = 'user') = (origin_id IS NULL)),
|
|
590
|
+
CHECK (origin_kind = 'extension' OR origin_correlation IS NULL),
|
|
591
|
+
-- This orders durable acceptance facts, not conversation entries.
|
|
592
|
+
UNIQUE (session_id, sequence),
|
|
593
|
+
UNIQUE (session_id, request_id),
|
|
594
|
+
UNIQUE (session_id, work_id)
|
|
595
|
+
)
|
|
596
|
+
`),yN(e)}function PL(e,t){let n=LI(e,t)?.leaf_id;return n==null?null:fR(e,t,n)}function FL(e,t){let n=LI(e,t)?.leaf_id;return n==null?null:dR(e,t,n)?.sequence??null}function IL(e,t,n){return e.transactionSync(()=>RL(e,{sessionId:t,id:oN.fact.generate(),entry:{kind:`model_preference`,workId:null,preference:n}}))}function LL(e,t,n){e.transactionSync(()=>{uL(e,t);let r=n===null?null:ZF({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),KP(e,{sessionId:t,title:OI(e,t)}))})}function RL(e,t){let n=zI(e,uL(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=cL(e,t.sessionId);e.sql.exec(`INSERT INTO session_entries
|
|
597
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
598
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
599
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.id,t.sessionId,n?.id??null,a,t.entry.kind,jI(t.entry),r,AI(t.entry),t.entry.workId,aN(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),KP(e,t.entry.kind===`command`?{sessionId:t.sessionId,activityAt:i,title:OI(e,t.sessionId)}:{sessionId:t.sessionId,activityAt:i}));let o=RI(e,t.sessionId,t.id);if(o===void 0)throw $(`Appended Session entry is unavailable`);return o}function zL(e,t){let n=zI(e,uL(e,t.sessionId)),r=RI(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?cL(e,t.sessionId):r?.sequence??cL(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||!MI(e.run,t.entry.run)||!MI(e.turn,t.entry.turn)||!MI(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
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
601
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
602
|
+
VALUES (?, ?, ?, ?, 'message', ?, 'complete',
|
|
603
|
+
NULL, ?, ?, ?, ?)`,t.id,t.sessionId,o,s,jI(t.entry),t.entry.workId,aN(t.entry),c,i),e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,t.id,i,t.sessionId),KP(e,{sessionId:t.sessionId,activityAt:i});let l=RI(e,t.sessionId,t.id);if(l===void 0)throw $(`Completed Session leaf is unavailable`);return l}var BL=4e3,VL=4194304,HL={selected:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
|
|
604
|
+
SELECT id, parent_id, sequence, state
|
|
605
|
+
FROM session_entries
|
|
606
|
+
WHERE session_id = ? AND id = ?
|
|
607
|
+
UNION ALL
|
|
608
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state
|
|
609
|
+
FROM branch AS child
|
|
610
|
+
CROSS JOIN session_entries AS parent
|
|
611
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
612
|
+
AND child.sequence > ?
|
|
613
|
+
AND +parent.sequence < child.sequence
|
|
614
|
+
)`,fork:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
|
|
615
|
+
SELECT id, parent_id, sequence, state
|
|
616
|
+
FROM session_entries
|
|
617
|
+
WHERE session_id = ? AND id = ? AND state != 'streaming'
|
|
618
|
+
UNION
|
|
619
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state
|
|
620
|
+
FROM branch AS child
|
|
621
|
+
CROSS JOIN session_entries AS parent
|
|
622
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
623
|
+
AND child.sequence > ?
|
|
624
|
+
AND parent.state != 'streaming'
|
|
625
|
+
)`},UL={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`}},WL=D(P({id:UF,parent_id:R(M),sequence:WF,state:L([`complete`,`streaming`])}),VF),GL=new WeakMap;function KL(e,t,n,r=2**53-1){let i=GL.get(e);GL.set(e,{sessionId:t,before:r,encoded:new Map});try{return e.transactionSync(n)}finally{i===void 0?GL.delete(e):GL.set(e,i)}}function qL(e,t,n){return GL.get(e)?.sessionId===t?n():e.transactionSync(n)}function JL(e,t,n,r){let i=GL.get(e);if(i?.sessionId!==t)return;i.ancestry??=e.sql.exec(`WITH RECURSIVE read_window (before_sequence, rows) AS (VALUES (?, ?)),
|
|
626
|
+
ancestry (id, parent_id, sequence, state, head, context_closed, taken) AS (
|
|
627
|
+
SELECT id, parent_id, sequence, state,
|
|
628
|
+
${SR(`session_entries`)}, 0,
|
|
629
|
+
CASE WHEN state != 'streaming'
|
|
630
|
+
AND sequence < (SELECT before_sequence FROM read_window)
|
|
631
|
+
THEN 1 ELSE 0 END
|
|
632
|
+
FROM session_entries INDEXED BY idx_session_entries_ancestry
|
|
633
|
+
WHERE session_id = ? AND id = ?
|
|
634
|
+
UNION ALL
|
|
635
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
|
|
636
|
+
COALESCE(child.head, ${SR(`parent`)}),
|
|
637
|
+
child.context_closed OR
|
|
638
|
+
(child.head IS child.id AND child.state != 'streaming'),
|
|
639
|
+
child.taken + CASE WHEN parent.state != 'streaming'
|
|
640
|
+
AND parent.sequence < (SELECT before_sequence FROM read_window)
|
|
641
|
+
THEN 1 ELSE 0 END
|
|
642
|
+
FROM ancestry AS child
|
|
643
|
+
CROSS JOIN session_entries AS parent INDEXED BY idx_session_entries_ancestry
|
|
644
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
645
|
+
AND +parent.sequence < child.sequence
|
|
646
|
+
AND (child.taken < (SELECT rows FROM read_window)
|
|
647
|
+
OR (child.context_closed = 0
|
|
648
|
+
AND (child.head IS NOT child.id OR child.state = 'streaming')))
|
|
649
|
+
)
|
|
650
|
+
SELECT id, parent_id, sequence, state FROM ancestry
|
|
651
|
+
WHERE context_closed = 0
|
|
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=WL(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 YL(e){return`${e} AS MATERIALIZED (
|
|
654
|
+
SELECT json_extract(value, '$.id') AS id,
|
|
655
|
+
json_extract(value, '$.parent_id') AS parent_id,
|
|
656
|
+
json_extract(value, '$.sequence') AS sequence,
|
|
657
|
+
json_extract(value, '$.state') AS state
|
|
658
|
+
FROM json_each(?)
|
|
659
|
+
)`}var XL=H.pipe(z(V(0))),ZL=D(P({length:XL,root_id:R(UF),root_parent_id:R(M),broken:XL,newest_id:R(UF),newest_sequence:R(WF)}),VF),QL=D(P({sequence:WF}),VF),$L=D(P({work_id:UF}),VF),eR=D(P({work_id:UF,diagnostic:M}),VF);function tR(e,t,n,r,...i){let a=t.walk===`selected`?JL(e,t.sessionId,t.tipId,n):void 0;return a===void 0?e.sql.exec(`${HL[t.walk]} ${r}`,t.sessionId,t.tipId,t.sessionId,n.floor,...i).toArray():e.sql.exec(`WITH ${YL(`branch`)} ${r}`,a,...i).toArray()}function nR(e,t,n,r){let i=UL[r],a=ZL(e.sql.exec(`${HL[r]},
|
|
660
|
+
kept AS MATERIALIZED (
|
|
661
|
+
SELECT id, parent_id, sequence FROM branch
|
|
662
|
+
WHERE state != 'streaming'
|
|
663
|
+
),
|
|
664
|
+
links AS (
|
|
665
|
+
SELECT parent_id, LAG(id) OVER (ORDER BY sequence) AS previous
|
|
666
|
+
FROM kept
|
|
667
|
+
)
|
|
668
|
+
SELECT
|
|
669
|
+
(SELECT COUNT(*) FROM kept) AS length,
|
|
670
|
+
(SELECT id FROM kept ORDER BY sequence ASC LIMIT 1) AS root_id,
|
|
671
|
+
(SELECT parent_id FROM kept ORDER BY sequence ASC LIMIT 1)
|
|
672
|
+
AS root_parent_id,
|
|
673
|
+
(SELECT COUNT(*) FROM links
|
|
674
|
+
WHERE previous IS NOT NULL AND parent_id IS NOT previous) AS broken,
|
|
675
|
+
(SELECT id FROM kept ORDER BY sequence DESC LIMIT 1) AS newest_id,
|
|
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 rR=D(P({state:L([`complete`,`streaming`]),newest_sequence:WF,root_id:R(UF),root_parent_id:R(M)}),VF);function iR(e,t){let n=LI(e,t.sessionId),r=t.leafId??n?.leaf_id;if(r==null)return;let i=UL.selected,a=e.sql.exec(`SELECT tip.state AS state, tip.sequence AS newest_sequence,
|
|
678
|
+
root.id AS root_id, root.parent_id AS root_parent_id
|
|
679
|
+
FROM session_entries AS tip
|
|
680
|
+
LEFT JOIN (
|
|
681
|
+
SELECT id, parent_id FROM session_entries
|
|
682
|
+
WHERE session_id = ? AND state = 'complete'
|
|
683
|
+
ORDER BY sequence ASC LIMIT 1
|
|
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=rR(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 aR(e,t,n,r){let i=Object.freeze(tR(e,t,{floor:n-1,ceiling:r},`SELECT ${xI}
|
|
686
|
+
FROM session_entries
|
|
687
|
+
WHERE session_id = ? AND state != 'streaming'
|
|
688
|
+
AND sequence BETWEEN ? AND ?
|
|
689
|
+
AND id IN (SELECT id FROM branch)
|
|
690
|
+
ORDER BY sequence ASC`,t.sessionId,n,r).map(t=>NI(e,t))),a=UL.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 oR=D(P({sizes:U(F(Zm([WF,XL]))),deepest_parent:R(M),deepest_sequence:R(WF)}),VF);function sR(e,t,n,r,i,a){let o=t.walk===`selected`?JL(e,t.sessionId,t.tipId):void 0;if(o!==void 0){let s=GL.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=JL(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
|
+
(SELECT json_group_array(json_array(sequence, bytes)) FROM (
|
|
692
|
+
SELECT sequence, octet_length(data_json) AS bytes
|
|
693
|
+
FROM session_entries
|
|
694
|
+
WHERE ${n===`newest`?``:`session_id = ? AND`}
|
|
695
|
+
state != 'streaming'
|
|
696
|
+
AND sequence > ? AND sequence < ?
|
|
697
|
+
AND id IN (SELECT id FROM ${o===void 0?`branch`:`candidates`})
|
|
698
|
+
ORDER BY sequence ${s}
|
|
699
|
+
LIMIT ?)) AS sizes,
|
|
700
|
+
(SELECT parent_id FROM branch ORDER BY sequence ASC LIMIT 1)
|
|
701
|
+
AS deepest_parent,
|
|
702
|
+
(SELECT sequence FROM branch ORDER BY sequence ASC LIMIT 1)
|
|
703
|
+
AS deepest_sequence`,l=e=>`CASE WHEN ${e}.state != 'streaming'
|
|
704
|
+
AND ${e}.sequence < ? AND ${e}.sequence > ?
|
|
705
|
+
THEN 1 ELSE 0 END`,u=oR((o===void 0?n===`newest`?e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, state, taken) AS (
|
|
706
|
+
SELECT id, parent_id, sequence, state,
|
|
707
|
+
${l(`session_entries`)}
|
|
708
|
+
FROM session_entries
|
|
709
|
+
WHERE session_id = ? AND id = ?
|
|
710
|
+
UNION ALL
|
|
711
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
|
|
712
|
+
child.taken + ${l(`parent`)}
|
|
713
|
+
FROM branch AS child
|
|
714
|
+
CROSS JOIN session_entries AS parent
|
|
715
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
716
|
+
AND +parent.sequence < child.sequence
|
|
717
|
+
AND child.taken < ? AND child.sequence > ?
|
|
718
|
+
)
|
|
719
|
+
${c}`,i,r,t.sessionId,t.tipId,i,r,t.sessionId,a,r,r,i,a).toArray():tR(e,t,{floor:r},c,t.sessionId,r,i,a):e.sql.exec(`WITH ${YL(`branch`)},
|
|
720
|
+
candidates AS MATERIALIZED (
|
|
721
|
+
SELECT id FROM branch
|
|
722
|
+
WHERE state != 'streaming' AND sequence > ? AND sequence < ?
|
|
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 $(UL.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 cR(e,t,n){let r=sR(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>VL)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:aR(e,t,Math.min(o.sequence,s.sequence),Math.max(o.sequence,s.sequence)),more:r.length>i})}function lR(e,t,n){return tR(e,t,{floor:n-1,ceiling:n},`SELECT 1 AS present
|
|
725
|
+
FROM session_entries
|
|
726
|
+
WHERE session_id = ? AND state != 'streaming' AND sequence = ?
|
|
727
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,n).length>0}function uR(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=QL(r);if(i._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return lR(e,t,i.success.sequence)?i.success.sequence:void 0}function dR(e,t,n){let[r]=_R(e,t,n,`SELECT id, sequence FROM session_entries
|
|
729
|
+
WHERE session_id = ? AND type = 'model_preference'
|
|
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:RI(e,t,r)}function fR(e,t,n){let r=dR(e,t,n)?.entry;return r?.kind===`model_preference`?r.preference:null}function pR(e,t,n,r){if(t===void 0)return;let i=tR(e,t,{floor:0},`SELECT ${xI}
|
|
732
|
+
FROM session_entries
|
|
733
|
+
WHERE session_id = ? AND state != 'streaming' AND type = 'document'
|
|
734
|
+
AND json_extract(data_json, '$.extensionId') = ?
|
|
735
|
+
AND json_extract(data_json, '$.name') = ?
|
|
736
|
+
AND id IN (SELECT id FROM branch)
|
|
737
|
+
ORDER BY sequence DESC
|
|
738
|
+
LIMIT 1`,t.sessionId,n,r)[0],a=i===void 0?void 0:NI(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 mR=D(P({oldest:R(WF),newest:R(WF)}),VF);function hR(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=mR(e.sql.exec(`SELECT MIN(oldest) AS oldest, MAX(newest) AS newest FROM (
|
|
739
|
+
SELECT MIN(sequence) AS oldest, MAX(sequence) AS newest
|
|
740
|
+
FROM session_entries INDEXED BY idx_session_entries_work
|
|
741
|
+
WHERE work_id IN (SELECT value FROM json_each(?))
|
|
742
|
+
AND session_id = ?
|
|
743
|
+
UNION ALL
|
|
744
|
+
SELECT MIN(sequence), MAX(sequence) FROM session_entries
|
|
745
|
+
INDEXED BY idx_session_entries_cancellation_target
|
|
746
|
+
WHERE session_id = ? AND type = 'cancellation'
|
|
747
|
+
AND json_extract(data_json, '$.targetWorkId')
|
|
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(tR(e,t,o,`SELECT DISTINCT work_id
|
|
750
|
+
FROM session_entries
|
|
751
|
+
WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'command'
|
|
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=$L(e);if(t._tag===`Failure`)throw $(`Stored Session command work is invalid`);return t.success.work_id})),c=new Map;for(let n of tR(e,t,o,`SELECT work_id, diagnostic FROM (
|
|
754
|
+
SELECT work_id, sequence,
|
|
755
|
+
json_extract(data_json, '$.diagnostic') AS diagnostic
|
|
756
|
+
FROM session_entries
|
|
757
|
+
WHERE session_id = ? AND sequence > ? AND state != 'streaming'
|
|
758
|
+
AND work_id IN (SELECT value FROM json_each(?))
|
|
759
|
+
AND type IN ('work_terminal', 'run_terminal')
|
|
760
|
+
AND id IN (SELECT id FROM branch)
|
|
761
|
+
)
|
|
762
|
+
WHERE diagnostic IS NOT NULL
|
|
763
|
+
ORDER BY sequence ASC`,t.sessionId,a,r)){let e=eR(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 tR(e,t,o,`SELECT ${xI}
|
|
764
|
+
FROM session_entries
|
|
765
|
+
WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'cancellation'
|
|
766
|
+
AND json_extract(data_json, '$.targetWorkId')
|
|
767
|
+
IN (SELECT value FROM json_each(?))
|
|
768
|
+
AND id IN (SELECT id FROM branch)
|
|
769
|
+
ORDER BY sequence ASC`,t.sessionId,a,r).map(t=>NI(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 gR(e,t,n,r){return r===void 0?{sql:`walk (id, parent_id, sequence, state) AS (
|
|
770
|
+
SELECT id, parent_id, sequence, state
|
|
771
|
+
FROM session_entries
|
|
772
|
+
WHERE session_id = ? AND id = ?
|
|
773
|
+
UNION ALL
|
|
774
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state
|
|
775
|
+
FROM walk AS child
|
|
776
|
+
CROSS JOIN session_entries AS parent
|
|
777
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
778
|
+
AND +parent.sequence < child.sequence
|
|
779
|
+
AND ${n}
|
|
780
|
+
)`,bindings:[e,t,e],recursive:!0}:{sql:`${YL(`ancestors`)},
|
|
781
|
+
stopped AS (
|
|
782
|
+
SELECT child.*,
|
|
783
|
+
COALESCE(SUM(CASE WHEN ${n} THEN 0 ELSE 1 END)
|
|
784
|
+
OVER (ORDER BY child.sequence DESC
|
|
785
|
+
ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS stops
|
|
786
|
+
FROM ancestors AS child
|
|
787
|
+
),
|
|
788
|
+
walk AS (
|
|
789
|
+
SELECT id, parent_id, sequence, state FROM stopped WHERE stops = 0
|
|
790
|
+
)`,bindings:[r],recursive:!1}}function _R(e,t,n,r,i,a){let o=JL(e,t,n),s=o=>{let s=gR(t,n,a(`child`),o);return e.sql.exec(`WITH ${s.recursive?`RECURSIVE `:``}targets AS MATERIALIZED (
|
|
791
|
+
${r}
|
|
792
|
+
),
|
|
793
|
+
${s.sql}
|
|
794
|
+
${vR(a(`walk`))}`,...i,...s.bindings).toArray()},c=s(o);if(o!==void 0){let r=c.at(-1);if(r!==void 0){let i=bR(r);if(i._tag===`Failure`)throw $(`Stored Session walk row is invalid`);(i.success.continues===1&&i.success.parent_id!==null||JL(e,t,n,{floor:i.success.sequence-1})===void 0)&&(c=s(void 0))}}return xR(c)}function vR(e){return`SELECT id, parent_id, sequence, target, continues FROM (
|
|
795
|
+
SELECT id, parent_id, sequence,
|
|
796
|
+
id IN (SELECT id FROM targets) AS target,
|
|
797
|
+
COALESCE((${e}), 0) AS continues
|
|
798
|
+
FROM walk
|
|
799
|
+
)
|
|
800
|
+
WHERE target = 1 OR sequence = (SELECT MIN(sequence) FROM walk)
|
|
801
|
+
ORDER BY sequence DESC`}var yR=L([0,1]),bR=D(P({id:UF,parent_id:R(M),sequence:WF,target:yR,continues:yR}),VF);function xR(e){let t=UL.selected;if(e.length===0)throw $(t.empty);let n=e.map(e=>{let t=bR(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 SR(e){return`CASE WHEN ${e}.type = 'compaction' AND ${e}.state != 'streaming'
|
|
802
|
+
THEN json_extract(${e}.data_json, '$.head') END`}var CR=`WITH RECURSIVE walk (id, parent_id, sequence, state, head) AS (
|
|
803
|
+
SELECT id, parent_id, sequence, state,
|
|
804
|
+
${SR(`session_entries`)}
|
|
805
|
+
FROM session_entries
|
|
806
|
+
WHERE session_id = ? AND id = ?
|
|
807
|
+
UNION ALL
|
|
808
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
|
|
809
|
+
COALESCE(child.head, ${SR(`parent`)})
|
|
810
|
+
FROM walk AS child
|
|
811
|
+
CROSS JOIN session_entries AS parent
|
|
812
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
813
|
+
AND +parent.sequence < child.sequence
|
|
814
|
+
AND (child.head IS NOT child.id OR child.state = 'streaming')
|
|
815
|
+
)`;function wR(e,t,n,r,i){let a=JSON.stringify(r.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[])),o=_R(e,t,n.id,`SELECT id, sequence FROM session_entries
|
|
816
|
+
WHERE session_id = ? AND type = 'compaction' AND work_id = ?
|
|
817
|
+
AND sequence < ? AND state != 'streaming'
|
|
818
|
+
UNION ALL
|
|
819
|
+
SELECT id, sequence
|
|
820
|
+
FROM session_entries
|
|
821
|
+
INDEXED BY idx_session_entries_cancellation_target
|
|
822
|
+
WHERE session_id = ? AND type = 'cancellation'
|
|
823
|
+
AND json_extract(data_json, '$.targetWorkId')
|
|
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 ${xI}
|
|
826
|
+
FROM session_entries
|
|
827
|
+
WHERE id IN (SELECT value FROM json_each(?))
|
|
828
|
+
ORDER BY sequence ASC`,JSON.stringify(o)).toArray().map(t=>NI(e,t)))}function TR(e,t,n){let r=UL.selected,i=JL(e,t,n);GL.get(e)?.ancestry?.[0]?.id!==n&&(i=void 0);let a=i===void 0?{sql:CR,bindings:[t,n,t]}:{sql:`WITH ${YL(`ancestors`)},
|
|
829
|
+
boundary AS (
|
|
830
|
+
SELECT sequence, json_extract(data_json, '$.head') AS head
|
|
831
|
+
FROM session_entries
|
|
832
|
+
WHERE session_id = ? AND type = 'compaction'
|
|
833
|
+
AND state != 'streaming'
|
|
834
|
+
AND id IN (SELECT id FROM ancestors)
|
|
835
|
+
ORDER BY sequence DESC LIMIT 1
|
|
836
|
+
),
|
|
837
|
+
walk AS (
|
|
838
|
+
SELECT * FROM ancestors
|
|
839
|
+
WHERE sequence >= COALESCE((
|
|
840
|
+
SELECT ancestors.sequence FROM ancestors, boundary
|
|
841
|
+
WHERE ancestors.id = boundary.head
|
|
842
|
+
AND ancestors.state != 'streaming'
|
|
843
|
+
AND ancestors.sequence <= boundary.sequence
|
|
844
|
+
), 0)
|
|
845
|
+
)`,bindings:[i,t]},o=e.sql.exec(`${a.sql}
|
|
846
|
+
SELECT ${xI}
|
|
847
|
+
FROM session_entries
|
|
848
|
+
WHERE id IN (SELECT id FROM walk) AND state != 'streaming'
|
|
849
|
+
ORDER BY sequence ASC`,...a.bindings).toArray().map(t=>NI(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 ER(e,t){let n=LI(e,t.sessionId)?.leaf_id;if(n==null)return Object.freeze([]);let r=TR(e,t.sessionId,n),i=r.rows[0];return!r.compacted||i===void 0?r.rows:Object.freeze([...wR(e,t.sessionId,i,r.rows,t.workId??null),...r.rows])}function DR(e,t,n){return e.entry.kind===`compaction`&&e.entry.workId===t||e.entry.kind===`cancellation`&&n.has(e.entry.targetWorkId)}function OR(e,t,n,r,i){let a=iR(e,{sessionId:t,leafId:n.id});if(a===void 0)throw $(`Accepted Session command lineage is unavailable`);let o=r===void 0?[]:tR(e,r,{floor:n.sequence},`SELECT ${xI}
|
|
850
|
+
FROM session_entries
|
|
851
|
+
WHERE session_id = ? AND sequence > ? AND state != 'streaming'
|
|
852
|
+
AND id IN (SELECT id FROM branch)
|
|
853
|
+
AND (work_id = ?
|
|
854
|
+
OR (type = 'command'
|
|
855
|
+
AND json_extract(data_json, '$.targetWorkId') = ?))
|
|
856
|
+
ORDER BY sequence ASC`,t,n.sequence,i,i).map(t=>NI(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=TR(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??uR(e,a,t)??0,l=c>n.sequence?[]:aR(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([...wR(e,t,l[0]??n,u,i),...o.filter(e=>e.sequence<c&&DR(e,i,d)),...u])}function kR(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 AR(e,t){let n=kR(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=RF(o,t),c=[];i!==void 0&&c.push(...i.model);for(let e of o){let t=$M(e.entry);t!==void 0&&!n.has(t.workId)&&c.push(nN(t)),e.entry.kind===`operator`&&c.push(tN(e.entry)),e.entry.kind===`message`&&s.has(e.id)&&c.push(e.entry.value)}return Object.freeze(c)}function jR(e,t){return e.transactionSync(()=>{let n=RI(e,t.sessionId,t.commandFactId),r=`replay`,i=eL(e,t.sessionId,t.commandFactId);if(n===void 0&&i!==void 0&&(n=RL(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&&aN(n.entry)!==aN(i.entry))throw $(`Accepted Session command disagrees with its admission`);let a=MR(e,t.sessionId,n.entry.workId),o=iL(e,t.sessionId,n.entry.workId),s=n.entry.workId,c=iR(e,{sessionId:t.sessionId}),l=OR(e,t.sessionId,n,c,s),u=Object.freeze({...n,entry:n.entry});return Object.freeze({command:u,modelPreference:fR(e,t.sessionId,n.id),messages:AR(l,n.entry.workId),path:l,entryDelivery:r,resume:IF(o),abnormalTerminal:BF(o),recoveredPartial:a})})}function MR(e,t,n){let r=iL(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 NR(e){return`[interrupted] Tool "${e.name}" (id: ${e.id}) was still executing when the run was terminated.`}var PR=200;function FR(e,t,n){let r=e.sql.exec(`WITH RECURSIVE tail (id, parent_id, sequence, type, depth) AS (
|
|
857
|
+
SELECT entry.id, entry.parent_id, entry.sequence, entry.type, 1
|
|
858
|
+
FROM sessions
|
|
859
|
+
JOIN session_entries AS entry
|
|
860
|
+
ON entry.session_id = sessions.id AND entry.id = sessions.leaf_id
|
|
861
|
+
WHERE sessions.id = ?
|
|
862
|
+
UNION ALL
|
|
863
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.type,
|
|
864
|
+
child.depth + 1
|
|
865
|
+
FROM tail AS child
|
|
866
|
+
CROSS JOIN session_entries AS parent
|
|
867
|
+
WHERE parent.id = child.parent_id AND parent.session_id = ?
|
|
868
|
+
AND +parent.sequence < child.sequence
|
|
869
|
+
AND child.type != 'compaction'
|
|
870
|
+
AND child.depth < ?
|
|
871
|
+
)
|
|
872
|
+
SELECT ${xI}
|
|
873
|
+
FROM session_entries
|
|
874
|
+
WHERE session_id = ? AND work_id = ? AND type = 'message'
|
|
875
|
+
AND state = 'complete'
|
|
876
|
+
AND id IN (SELECT id FROM tail)
|
|
877
|
+
ORDER BY sequence DESC`,t,t,PR,t,n).toArray().map(t=>NI(e,t)),i=r.findIndex(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`),a=r[i]?.entry;if(a?.kind!==`message`||a.value.role!==`assistant`||a.value.stopReason===`error`||a.value.stopReason===`aborted`)return 0;let o=new Set(r.slice(0,i).flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`toolResult`?[e.value.toolCallId]:[])),s=a.value.content.flatMap(e=>e.type===`toolCall`&&!o.has(e.id)?[e]:[]);for(let r of s){let i=oN.fact.generate();RL(e,{sessionId:t,id:i,entry:{kind:`message`,workId:n,run:a.run,turn:a.turn,message:{kind:`tool_result`,value:i,parent:a.message},value:{role:`toolResult`,toolCallId:r.id,toolName:r.name,content:[{type:`text`,text:NR(r)}],isError:!0,timestamp:Date.now()}}})}return s.length}function IR(e,t){e.sql.exec(`UPDATE session_entries SET data_json = ? WHERE session_id = ? AND id = ? AND state = 'streaming'`,aN({...t.entry,partial:{text:t.text,offset:t.offset}}),t.sessionId,t.entry.message.value)}function LR(e,t){let n=LI(e,t.sessionId)?.leaf_id;if(n==null)return`stale`;let r=e.sql.exec(`${CR}
|
|
878
|
+
SELECT sequence
|
|
879
|
+
FROM session_entries
|
|
880
|
+
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(QL(r)._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return`current`}function RR(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 RL(e,{sessionId:t.sessionId,id:oN.fact.generate(),entry:r})})}D(P({session_id:M,work_id:M,timestamp:N,diagnostic:R(M)}),VF);function zR(e,t){return e.transactionSync(()=>RL(e,{sessionId:t.sessionId,id:oN.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 BR(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 VR(e,t){return e.transactionSync(()=>UR(e,t))}function HR(e,t){return e.transactionSync(()=>LR(e,{sessionId:t.sessionId,head:t.head})===`stale`?`stale`:UR(e,t))}function UR(e,t){if(LI(e,t.sessionId)?.leaf_id!==t.expectedLeafId)throw new G(`store`,`conflict`,`Session leaf changed during compaction`);let n={kind:`compaction`,workId:t.workId,head:t.head,model:[JN(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 RL(e,{sessionId:t.sessionId,id:oN.fact.generate(),entry:t.details===void 0?r:{...r,data:{...r.data,details:t.details}}})}function WR(e){return Array.isArray(e)}function GR(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 KR(e,t){return!WR(e)||!WR(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 qR(e,t){if(t.type===`compact`)return QM(e)&&e.instructions===t.instructions;let n=$M(e);return n?.delivery===t.delivery&&KR(n.message.content,GR(t))}function JR(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:GR(e),timestamp:n},contract:r},c=i===void 0?s:{...s,targetWorkId:i};return a===void 0?c:{...c,reply:a}}function YR(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 XR(e,t,n,r,i,a,o,s,c){let l=nL(e,t,n.requestId);if(l!==void 0){if(!qR(l.entry,n)||!kA(l.entry.meta,r)||!YR($M(l.entry)?.reply,c)||!oI(l.origin,i))throw new G(`contract`,`conflict`,`Request id conflicts with an accepted Session command`);return $R(l,`replay`)}let u=oN.fact.generate();uL(e,t);let d=Date.now(),f=JR(n,u,d,a,s,c);e.sql.exec(`INSERT INTO session_command_admissions
|
|
881
|
+
(id, session_id, sequence, request_id, work_id, data_json, timestamp,
|
|
882
|
+
origin_kind, origin_id, origin_correlation)
|
|
883
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,u,t,lL(e,t),n.requestId,u,aN(SI(f,r)),d,i.kind,i.kind===`user`?null:i.extensionId,i.kind===`user`?null:i.correlation);let p=eL(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`}),$R(p,`new`)}function ZR(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 G(`contract`,`closed`,`Request was withdrawn`,n)}function QR(e,t,n){let r=nL(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=fI(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 $R(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 ez(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 tz(e,t,n,r,i){return e.transactionSync(()=>{let a=n(),o=a.state===`running`?tL(e,t,a.jobId):void 0,s=o===void 0?void 0:rz(e,t,o.id,n,r,!1,i);for(let a=lL(e,t);a>0;){let{commands:o}=YI(e,t,64);if(o.length===0)return s;a-=o.length;for(let a of o){if(rz(e,t,a.id,n,r,!1,i,!0)===void 0)throw $(`Pending Session command could not be cancelled`);RL(e,{sessionId:t,id:a.id,entry:a.entry})}}throw $(`Session cancellation did not settle its pending admissions`)})}function nz(e,t,n,r,i,a=!1,o){return e.transactionSync(()=>rz(e,t,n,r,i,a,o))}function rz(e,t,n,r,i,a=!1,o,s=!1){let c=r(),l=eL(e,t,n);if(l?.entry.kind!==`command`)return;let u=iL(e,t,l.entry.workId),d=u.find(({entry:e})=>e.kind===`cancellation`);if(d?.entry.kind===`cancellation`)return ez(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`))||$M(l.entry)?.delivery===`steer`&&u.some(({entry:e})=>e.kind===`command`)&&!f)return;let p=oN.fact.generate(),m=i({jobId:l.entry.workId,cancellationId:p,onlyIfPending:a});if(m.status===`missing`&&$M(l.entry)?.delivery!==`steer`&&!s||m.status===`decided`||m.status===`conflict`&&a)return;if(m.status!==`recorded`&&m.status!==`missing`)throw new G(`store`,`conflict`,`Session cancellation identity conflicts`);let ee=RL(e,{sessionId:t,id:p,entry:SI({kind:`cancellation`,requestId:p,receiptId:p,workId:l.entry.workId,targetWorkId:l.entry.workId},o)});return m.status===`missing`&&RL(e,{sessionId:t,id:oN.fact.generate(),entry:{kind:`work_terminal`,workId:l.entry.workId,outcome:`cancelled`}}),ez(ee,`new`,f)}function iz(e,t){e.transactionSync(()=>{t.assertIdleSession?.(t.sessionId);let n=LI(e,t.sessionId);if(n===void 0)throw $(`Session is unavailable for branch selection`);zI(e,n);let r=RI(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),KP(e,{sessionId:n.id,activityAt:i,title:OI(e,n.id)})})}function az(e,t){return e.transactionSync(()=>{if(ZR(e,t.sessionId,t.requestId),LI(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=fI(n);if(r._tag===`Failure`)throw $(`Stored Session entry identity is invalid`);let i=RI(e,t.sessionId,r.success.id);if(i?.entry.kind===`operator`&&i.entry.author===t.author&&kA(i.entry.meta,t.meta)&&i.entry.message.content===t.text)return!1;throw new G(`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 RL(e,{sessionId:t.sessionId,id:oN.fact.generate(),entry:SI(r,t.meta)}),!0})}function oz(e,t){return e.transactionSync(()=>{if(t.assertIdleSession?.(t.sessionId),LI(e,t.sessionId)===void 0)throw $(`Source Session is unavailable`);let n=nR(e,t.sessionId,t.entryId,`fork`),r=oN.session.generate(),i=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
884
|
+
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
885
|
+
VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),wP(e,t.sessionId,r);let a=null,o=null,s=1,c=new Map,l=0;for(;;){let t=cR(e,n,{after:l,from:`oldest`,rows:BL});for(let n of t.rows){let t=oN.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
|
|
886
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
887
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
888
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,jI(i),n.state,AI(i),i.workId,aN(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=iR(e,{sessionId:t.sessionId});for(let t of WN(e,(t,n)=>pR(e,u,t,n)))RL(e,{sessionId:r,id:oN.fact.generate(),entry:t});return KP(e,{sessionId:r,activityAt:i,title:OI(e,r)}),r})}function sz(e,t,n,r){if(LI(e,t)===void 0)throw $(`Session document owner is unavailable`);return pR(e,iR(e,{sessionId:t}),n,r)}function cz(e,t,n,r,i){if(LI(e,t)===void 0)throw $(`Session document owner is unavailable`);RL(e,{sessionId:t,id:oN.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var lz=2097152,uz=200,dz=200,fz=new TextEncoder;function pz(e){return new G(`store`,`unavailable`,e)}function mz(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)eL(e,t,n)!==void 0&&r.set(n,n);return r}function hz(e,t){return n=>{let r=eL(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function gz(e,t,n){return{commandIds:mz(e,t,n),diagnostics:yz(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:hz(e,t)}}function _z(e,t,n,r){let i=hR(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)&&eL(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:hz(e,t)}}function vz(e,t){let n=$M(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:rN(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 yz(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 bz(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 xz=new WeakMap;function Sz(e){let t=xz.get(e);if(t===void 0)throw pz(`Session compaction entry position is unavailable`);return t}function Cz(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??uR(e,t,a.head);if(o===void 0)throw pz(`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});xz.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function wz(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 Tz(e){return fz.encode(JSON.stringify(e)).byteLength}function Ez(e,t){let n=lM({generation:e,sequence:t});if(n===void 0)throw pz(`Session cursor is unavailable`);return n}function Dz(e,t,n,r,i=!1){let a=vz(t,r),o=bz(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:Tz(a))+(o===void 0?0:Tz(o))+(s===void 0?0:Tz(s));if(c>lz)throw pz(`Session projection entry exceeds the read bound`);return e.bytes+c>lz?!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 Oz(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==dz;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!Dz(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw pz(`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 kz(e){return Array.isArray(e)}function Az(e,t){let{commands:n,total:r}=YI(e,t,dz+1,`prompts`),i=[],a=fz.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=Mz(e),n=fz.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===dz||a+n>lz)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function jz(e,t,n){let r=qI(e,t,n);return r===void 0?null:Mz(r)}function Mz(e){let t=$M(e.entry);if(t===void 0)throw pz(`Pending Session prompt is unavailable`);let n=t.message.content,r=kz(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 Nz(e,t,n){let r=uM(n);if(r?.generation===t.rootId)return lR(e,t,r.sequence)?r.sequence:void 0}function Pz(e,t,n,r,i=()=>({}),a){return qL(e,t,()=>{let o=Az(e,t),s=iR(e,{sessionId:t});if(s===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:o,activity:r.facts,progress:r.readProgress(),toolOutput:r.toolOutput,extensions:i(),attention:oj(e,t)});let c=s.rootId,l=n.before===void 0?2**53-1:Nz(e,s,n.before);if(l===void 0)throw pz(`Session read cursor is unavailable`);let u=cR(e,s,{before:l,from:`newest`,rows:dz}),d=Oz(u.rows,u.more,n.limit,_z(e,t,s,u.rows),`backward`,n.includeSandboxFailures===!0),f=u.rows.slice(u.rows.length-d.consumed),p=u.rows.at(-1),m=f[0],ee={sessionId:t,cursor:p===void 0?null:Ez(c,p.sequence),hasMore:d.hasMore,oldestCursor:d.hasMore&&m!==void 0?Ez(c,m.sequence):null,messages:d.messages,terminals:d.terminals,compactions:Cz(e,s,f),compactionNotices:wz(f),pending:o,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:oj(e,t)},te=Jj(e,t,a);return te!==void 0&&Object.assign(ee,{parent:te}),Object.freeze(n.includeSandboxFailures===!0?{...ee,sandboxFailures:d.sandboxFailures}:ee)})}var Fz=Object.freeze({kind:`reset`});function Iz(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return lR(e,t,n.sequence)?n.sequence:void 0}function Lz(e,t,n,r,i,a,o,s,c){let l=cR(e,t,{after:n,from:`oldest`,rows:dz}),u=Oz(l.rows,l.more,uz,_z(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:Ez(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:Cz(e,t,d),compactionNotices:wz(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 Rz(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:uM(n);return n!==void 0&&s===void 0?Fz:qL(e,t,()=>{let c=Az(e,t),l=iR(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:oj(e,t),pending:c}],hasMore:!1}:Fz;let u=Iz(e,l,s);return u===void 0?Fz:Lz(e,l,u,r,i,a(),oj(e,t),c,o)})}function zz(e,t,n){let r=eL(e,t,n);if(r===void 0)throw pz(`Accepted Session command is unavailable`);if(!rL(e,t,r.entry.workId))return;let i=iL(e,t,r.entry.workId),a=gz(e,t,i),o=i.flatMap(e=>{let t=bz(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=x_(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:Uj(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:eM(e,t,r.entry.workId)}}var Bz=65536,Vz=250,Hz=2048,Uz=new TextEncoder,Wz=()=>({chunks:[],length:0,bytes:0});function Gz(e,t){for(let n=0;n<t.length;){let r=Math.min(n+Hz,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=Uz.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=Hz?(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>Bz&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function Kz(e){return e.chunks[0]?.offset??0}function qz(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function Jz(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:qz(e.text,Kz(e.text)),thinking:qz(e.thinking,Kz(e.thinking)),textOffset:Kz(e.text),thinkingOffset:Kz(e.thinking),textTruncated:Kz(e.text)>0,thinkingTruncated:Kz(e.thinking)>0}}function Yz(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function Xz(e,t,n,r){let i=Zz.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<Kz(a.text)||c<Kz(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:qz(a.text,s)},thinking:{offset:c,append:qz(a.thinking,c)}}}var Zz=new WeakMap;function Qz(e,t,n){let r=Zz.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var $z=D(P({droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))}),{onExcessProperty:`error`});function eB(e,t){return b(function*(){let n=yield*nB(e,t),r=()=>{KA(e,t.sessionId,`progress`)};return{started:e=>Vn(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>Vn(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=$z(e.result.data);if(je(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(`
|
|
889
|
+
`).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=>Vn(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function tB(e){let t=Zz.get(e);if(t!==void 0)return t;let n=new Map;return Zz.set(e,n),n}function nB(e,t){return b(function*(){let n=tB(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*Er(()=>Vn(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&KA(e,t.sessionId,`progress`))})),i})}function rB(e){return new G(`runtime`,`rejected`,e)}function iB(e,t,n){let r=tB(e).get(t);return Jz(r?.workId===n?r.value:null)}function aB(e,t,n){let r=Zz.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function oB(e,t,n,r){return b(function*(){let i=yield*nB(e,t);if(r!==void 0&&i.value===null){let n=Wz();n.length=r.offset,Gz(n,r.text),i.value={recovered:!0,messageId:r.messageId,revision:1,text:n,thinking:Wz()},KA(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,KA(e,t.sessionId,`progress`))},d=Vn(()=>{l();let n=i.value!==null;i.value=null,n&&KA(e,t.sessionId,`progress`),a=void 0});return yield*Er(()=>d),Object.freeze({started:e=>Vn(()=>{l(),a=e,o=0,i.value?.recovered!==!0&&(i.value=null),s=0}),update:n=>lr(()=>{let r=a;if(r===void 0)return y(rB(`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 y(rB(`Mule progress identity conflicts`));let l=n.event;if(l.type!==`text_delta`&&l.type!==`thinking_delta`||l.delta.length===0)return ii;let d=i.value===null||i.value.recovered===!0,f=(d?null:i.value)??{messageId:n.message.value,revision:0,text:Wz(),thinking:Wz()};Gz(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<Vz?ii:(o=m,li({try:()=>{IR(e,{sessionId:t.sessionId,entry:{kind:`message_start`,workId:t.commandId,run:r.run,turn:r.turn,message:r.message,role:`assistant`},text:qz(f.text,Kz(f.text)),offset:Kz(f.text)})},catch:e=>new G(`store`,`rejected`,`Native Session store operation failed`,void 0,e)}))}),terminal:e=>d.pipe(_(n(e)))})})}var sB=new WeakMap;function cB(e){let t=sB.get(e);if(t!==void 0)return t;let n=new Map;return sB.set(e,n),n}function lB(e,t){return cB(e).get(t)??null}function uB(e,t,n){cB(e).set(t,Object.freeze({trigger:n})),KA(e,t,`progress`)}function dB(e,t){cB(e).delete(t)&&KA(e,t,`progress`)}var fB=Object.freeze({admitNew:()=>{}});function pB(e){return e===void 0?fB:Object.freeze({admitNew:()=>{if(e.underPressure())throw new G(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function mB(e,t){let n=RR(e,t);return KA(e,t.sessionId),n}function hB(e,t){let n=VR(e,t);return KA(e,t.sessionId),n}function gB(e,t){let n=HR(e,t);return n!==`stale`&&KA(e,t.sessionId),n}function _B(e){return new G(`store`,`rejected`,e)}function vB(e){return new G(`store`,`conflict`,e)}function yB(e){return li({try:e,catch:e=>e instanceof G?e:new G(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function bB(e){return yB(()=>{ML(e)})}function xB(e,t,n,r,i,a,o){return yB(()=>{let s=nz(e,t,n,i,a,r,o);return s?.delivery===`new`&&KA(e,t,`settlement`),s})}function SB(e,t){return yB(()=>{let n=QI(e,t.sessionId,t.delivery,t.workId);return n.length>0&&KA(e,t.sessionId),n})}function CB(e,t){return yB(()=>{$I(e,t),KA(e,t.sessionId,`settlement`)})}function wB(e,t,n,r,i){return yB(()=>{let a=tz(e,t,n,r,i);return KA(e,t,`settlement`),a?.accepted})}function TB(e,t){return yB(()=>{iz(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),KA(e,t.sessionId)})}function EB(e,t){return yB(()=>{az(e,t)&&KA(e,t.sessionId)})}function DB(e,t){return yB(()=>{let n=oz(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return KA(e,n),Object.freeze({sessionId:n})})}function OB(e,t){return yB(()=>{let n=jR(e,{sessionId:$x(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&KA(e,t.sessionId),n})}function kB(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function AB(e,t){return yB(()=>{let n=eL(e,t.sessionId,t.commandFactId);if(n===void 0)throw _B(`Accepted Session command is unavailable`);let r=iL(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=kB(t.value);if(e!==``)return e}}return``})}function jB(e,t){return b(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*AB(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*yB(()=>{let n=eL(e,t.sessionId,i);if(n===void 0)throw _B(`Accepted Session command is unavailable`);if(GB(e,t.sessionId,i,n.entry.workId)===null)return;let r=BI(e,i);if(r===void 0)throw _B(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=BI(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw _B(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function MB(e,t,n){return yB(()=>{let r=eL(e,t.sessionId,t.commandFactId);if(r===void 0)throw _B(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=iL(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function NB(e,t){return yB(()=>{let n=eL(e,t.sessionId,t.commandFactId);if(n===void 0)throw _B(`Accepted Session command is unavailable`);return yz(iL(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function PB(e,t,n,r,i,a,o){return yB(()=>{let s=$x(t),c=nS(r);return KL(e,s,()=>a(Pz(e,s,c,n(),i,o)),c.before===void 0?void 0:uM(c.before)?.sequence)})}function FB(e,t,n){return yB(()=>dL(e,tS({requestId:t}),n))}function IB(e,t,n){return fL(e,tS({requestId:t}),n)}function LB(e,t){return yB(()=>pL(e,{sessionId:$x(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{qP(e,t)}}))}function RB(e,t){return yB(()=>QP(e,t))}function zB(e,t,n,r,i,a,o,s){return yB(()=>{let c=$x(t);return KL(e,c,()=>s(Rz(e,c,n,r,i,a,o)))})}function BB(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function VB(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 HB(e,t,n,r,i){i?.();let a=iL(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||KM(a.entry,n))return`replay`;throw vB(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=oN.fact.generate();if(BI(e,r)===void 0&&eL(e,t.sessionId,r)===void 0)return RL(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw _B(`Session fact identity allocation failed`)}function UB(e,t,n,r,i){let{delivery:a,appended:o}=e.transactionSync(()=>{let a=i?.()??!1;return{delivery:HB(e,t,n,r),appended:a}});a===`new`?KA(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`):o&&KA(e,t.sessionId)}function WB(e,t,n){return yB(()=>{UB(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function GB(e,t,n,r){let i=eL(e,t,n);if(i?.entry.workId!==r)throw _B(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function KB(e,t,n,r){let i=GB(e,t,n,r),a=iL(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 qB(e,t){return yB(()=>{if(eL(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw _B(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};UB(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),t.outcome!==`completed`&&FR(e,t.sessionId,t.workId)>0))})}function JB(e,t,n,r,i){return yB(()=>{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}),UB(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?BB(e.run,a.run)&&VB(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?BB(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&BB(e.terminal,a.terminal):!1,r.type===`run_end`&&r.outcome!==`completed`?()=>FR(e,t.sessionId,t.commandId)>0:void 0)})}function YB(e,t,n){return yB(()=>{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=iL(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&BB(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!BB(i.entry.run,r.run)||!BB(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw vB(`Mule message-start identity conflicts`);return`replay`}if(i.entry.kind!==`message_start`||!KM(GM(i.entry),r))throw vB(`Mule message-start identity conflicts`);return`replay`}return RL(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&KA(e,t.sessionId)})}function XB(e,t,n,r){return yB(()=>{UB(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`&&BB(e.turn,r.turn)&&e.attempt===r.attempt&&VB(e.contract,n))})}function ZB(e,t,n,r){return yB(()=>{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=iL(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&BB(e.message,n.message));if(i?.entry.kind===`message`){if(!KM(i.entry,a))throw vB(`Mule completed-message identity conflicts`)}else zL(e,{sessionId:t.sessionId,id:n.message.value,entry:a});let o=n.retry===void 0||n.value.role!==`assistant`?`replay`:tV(e,t,eV(n.retry,r),n.turn);return i?.entry.kind===`message`&&o===`replay`?`replay`:`new`})===`new`&&KA(e,t.sessionId)})}function QB(e,t,n,r){return yB(()=>{UB(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`&&BB(e.toolCall,r.toolCall)&&VB(e.contract,n))})}function $B(e,t,n){return yB(()=>{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};UB(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&BB(e.toolCall,n.toolCall))})}function eV(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. `+AA({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 tV(e,t,n,r){let i=iL(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&BB(e.turn,r));if(i===void 0)throw vB(`Retry has no recorded turn`);return HB(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&&BB(e.event.run,n.run))}function nV(e,t,n,r){return yB(()=>{e.transactionSync(()=>tV(e,t,n,r))===`new`&&KA(e,t.sessionId)}).pipe(dt(rV))}var rV=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function iV(e,t,n,r,i){return b(function*(){let a=yield*oB(e,t,n=>ZB(e,t,n,r),i),o=yield*eB(e,t),s=(i,s)=>{switch(i.type){case`model_prompt`:return XB(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return JB(e,t,n,i,s);case`message_start`:return i.value.role===`user`?ii:YB(e,t,i).pipe(_(i.value.role===`assistant`?a.started(i):ii));case`message_update`:return a.update(i);case`message_end`:return i.value.role===`user`?ii:i.value.role===`assistant`?a.terminal(i):ZB(e,t,i,r);case`tool_execution_start`:return QB(e,t,n,i).pipe(_(o.started(i)));case`tool_execution_end`:return $B(e,t,i).pipe(_(o.terminal(i)));case`tool_execution_update`:return o.update(i);case`turn_end`:return ii}};return(e,t)=>s(e,t).pipe(dt(rV))})}function aV(e,t,n){return yB(()=>zz(e,$x(t),$x(n)))}var oV=rI.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),sV=P({requestId:k(M),meta:k(TA),data:k(SA),origin:k(oV),id:M,sequence:H.check(Ph(0)),commandId:R(M),value:PM}),cV=L([`manual`,`threshold`,`overflow`]),lV=P({queue:I([P({state:j(`idle`)}),P({state:j(`queued`),commandId:hg,runningWork:R(P({phase:L([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),P({state:j(`running`),commandId:hg})]),cancellationRequested:Gm,retry:R(P({attempt:H.check(Ph(0)),maxAttempts:H.check(Ph(0)),delayMs:H.check(V(0)),errorMessage:M,scheduledAt:H.check(V(0))})),activeTool:R(M),lastModelChoiceSequence:R(H.check(Ph(0))),compaction:R(P({trigger:cV}))}),uV=M,dV=Ym(M,I([P({status:j(`running`),revision:uV,value:SA,catalog:k(SA)}),P({status:j(`stopped`),revision:uV,reason:M})])),fV=P({id:M,version:M,revision:uV,status:L([`running`,`stopped`]),reason:R(M),stoppedAt:R(N)}),pV=P({commandId:M,outcome:L([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:H.check(Ph(0)),diagnostic:R(M),meta:k(TA)}),mV=P({id:M,sequence:H.check(Ph(0)),at:H.check(V(0)),tokensBefore:N,tokensAfter:R(N),trigger:R(cV)}),hV=P({id:M,sequence:H.check(Ph(0)),at:H.check(V(0)),trigger:cV,result:L([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:R(M)}),gV=M.check(B(e=>new TextEncoder().encode(e).byteLength<=65536)),_V=P({messageId:M,revision:H.check(V(0)),text:gV,thinking:gV,textOffset:H.check(V(0)),thinkingOffset:H.check(V(0)),textTruncated:Gm,thinkingTruncated:Gm}),vV=P({commandId:M,requestId:M,meta:k(TA),origin:k(oV),text:M,images:k(F(Cx)),delivery:L([`steer`,`followUp`])}),yV=F(P({toolCallId:M,revision:H.check(V(0)),tail:M.check(B(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
|
|
890
|
+
`).length<=200)),droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))})).check(ng(4)),bV=P({total:H.check(V(0)),prompts:F(vV),hasMore:Gm}),xV=P({tokens:H.check(V(0)),window:R(H.check(Ph(0)))}),SV=P({parent:k(rx),sessionId:M,cursor:R(M),hasMore:Gm,oldestCursor:k(R(M)),messages:F(sV),terminals:F(pV),sandboxFailures:k(F(vA)),compactions:k(F(mV)),compactionNotices:k(F(hV)),pending:bV,activity:lV,progress:R(_V),toolOutput:yV,extensions:dV,attention:cx,context:k(xV)}),CV=I([P({kind:j(`heartbeat`)}),P({kind:j(`activity`),activity:lV}),P({kind:j(`tool_output`),toolOutput:yV,activity:lV}),P({kind:j(`update`),delivery:L([`replay`,`live`]),cursor:R(M),messages:F(sV),terminals:F(pV),sandboxFailures:k(F(vA)),compactions:k(F(mV)),compactionNotices:k(F(hV)),pending:bV,activity:lV,extensions:dV,attention:cx,context:k(xV)}),P({kind:j(`progress`),progress:P({messageId:M,revision:H.check(V(0)),text:P({offset:H.check(V(0)),append:gV}),thinking:P({offset:H.check(V(0)),append:gV})}),activity:lV}),P({kind:j(`reset`),reason:j(`history_unavailable`),cursor:R(M),baseline:SV})]),wV=P({status:j(`accepted`),commandId:M,sessionId:k(M)});O(U(I([wV,P({status:j(`held`),reason:j(`recipient_offline`),message:j(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var TV=P({status:j(`unknown`)}),EV=O(U(I([wV,TV])));function DV(e){return EV(e)}var OV=I([wV,TV,P({status:j(`too_late`),commandId:M})]),kV=P({sessionId:M}),AV=O(U(SV),{onExcessProperty:`error`}),jV=O(U(CV),{onExcessProperty:`error`}),MV=O(U(wV)),NV=O(U(OV)),PV=O(U(kV)),FV=O(U(_x)),IV=O(U(fV)),LV=O(U(F(fV))),RV=O(U(SA));function zV(e){return IV(e)}function BV(e){return LV(e)}function VV(e){return RV(e)}function HV(e){return MV(e)}function UV(e){return NV(e)}function WV(e){return O(U(R(vV)))(e)}function GV(e){return PV(e)}var KV=P({acceptedSender:R(M),delegator:R(M),terminal:pV,content:M,usage:F(P({provider:M,model:M,usage:AM})),toolCalls:H.check(V(0)),waitingOnYou:F(P({itemId:M,kind:M,summary:M})).check(ng(8))});function qV(e){return O(U(R(KV)))(e)??void 0}function JV(e){return AV(e)}function YV(e){return jV(e)}function XV(e){let t=FV(e);return new G(t.boundary,t.cause,t.message,t.requestId)}var ZV=O(U(P({sessions:F(I([P({sessionId:hg,createdAt:N,lastActivityAt:N,settledAt:k(N),title:M,state:L([`needs_you`,`running`,`errored`,`done`])}),P({sessionId:hg,state:j(`unavailable`)})])),next:A(hg)})));function QV(e){let t=ZV(e);return{sessions:t.sessions,next:t.next}}var $V=O(U(P({sessionId:hg}))),eH=O(U(P({deleted:Gm})));function tH(e){return eH(e).deleted}function nH(e){return $V(e).sessionId}function rH(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:dA(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function iH(e,t){return Kn(e,t).then(e=>{if(Ga(e))return e.value;let t=Gn(Na(e.cause))??ja(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function aH(e){let t=Ir(e);if(Ga(t))return t.value;let n=Gn(Na(t.cause))??ja(t.cause);throw n instanceof Error?n:Error(String(n))}function oH(e){let t=Qb(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 sH(e,t){function n(e){return iH(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>iH(t.withdraw(e)),abort:()=>iH(t.abort),send:(e,n)=>iH(t.send(e,n)),cancel:e=>iH(t.cancel(e)),latestPending:()=>iH(t.latestPending),modelPreference:Object.freeze({read:()=>iH(t.modelPreference.read),set:e=>iH(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>iH(n.call(e,t,r))})},read:e=>iH(t.read(e)),readSettlement:(e,n)=>iH(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>oH(t.subscribe(e)),watch:e=>iH(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:oH(e.changes),close:()=>iH(e.close)}))})}function cH(e,t){let n=t??`local:${Vg()}`;return Object.freeze({createSession:t=>iH(e.createSession(t)),deleteSession:t=>iH(e.deleteSession(t)),listSessions:t=>iH(e.listSessions(t)),extensions:Object.freeze({list:()=>iH(e.extensions.list),resume:t=>iH(e.extensions.resume(t)),call:(t,n,r)=>iH(e.extensions.call(t,n,r))}),session:t=>sH(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>iH(e.close)})}function lH(e){let t=`local:${Vg()}`;return Object.freeze({...cH(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:rH(t.tools)});let r=await iH(e.prepareConfiguration(n));return{commit:()=>{aH(r.commit)},discard:()=>iH(r.discard)}},grants:Object.freeze({deliver:(t,n)=>aH(e.grants.deliver(t,n)),read:t=>aH(e.grants.read(t))}),withMeta:n=>cH(e.withMeta(n),t)})}function uH(e=`Remote Shiitake operation is unavailable`){return new G(`runtime`,`unavailable`,e)}function dH(e){return new G(`runtime`,`invalid`,e)}function fH(){return new G(`runtime`,`closed`,`Shiitake client is closed`)}var pH=2,mH=O(M);function hH(e){if(!(e instanceof MessageEvent))throw dH(`Session stream event is invalid`);return mH(e.data)}function gH(e){return e.kind===`source-error`?y(uH(`Session stream is unavailable`)):e.kind===`snapshot`?li({try:()=>({kind:`snapshot`,value:JV(hH(e.event))}),catch:()=>dH(`Session snapshot is invalid`)}):e.kind===`frame`?li({try:()=>({kind:`frame`,value:YV(hH(e.event))}),catch:()=>dH(`Session frame is invalid`)}):li({try:()=>XV(hH(e.event)),catch:()=>dH(`Session runtime error is invalid`)}).pipe(T(y))}function _H(e,t){return Vn(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function vH(e,t,n,r){return xb(t=>Lr(li({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Sv(t,{kind:e,event:r})||(Tv(t,Da(uH(`Session stream client fell behind`))),yr(_H(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===pH&&a(`source-error`,e)}),n.add(i),i},catch:()=>uH(`Session stream could not open`)}),e=>_H(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(Pb(gH),Lb({duration:ex,orElse:()=>Tb(uH(`Session feed is connected but silent; the service may be busy`))}),Jb(t.await))}function yH(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function bH(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 xH(e,t,n,r){return vH(e,t,n,r).pipe(Pb(e=>e.kind===`frame`?S(e.value):y(dH(`Session subscription received a snapshot`))))}function SH(e,t,n,r,i,a){return b(function*(){yield*n;let o=yield*iy(!1),s=yield*oo();yield*Vn(()=>t.add(s)),yield*uo(s,Vn(()=>{t.delete(s)}));let c=yield*In(vH(e,r,i,a).pipe(Wb(db()),co(s)));if(Ka(c))return yield*mo(s,c),yield*Zt(c.cause);let[l,u]=c.value;if(an(l)||l.value.kind!==`snapshot`){let e=dH(`Session stream did not begin with a snapshot`);return yield*mo(s,Ha(e)),yield*y(e)}let d=u.pipe(Pb(e=>e.kind===`frame`?S(e.value):S({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),Jb(o.await),Gb(e=>o.isOpen()&&ka(e)?Sb:Eb(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(_(mo(s,Wa)))})})}function CH(e,t,n){return fn({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>uH(`${n} request failed`)}).pipe(T(({response:e,body:r})=>e.ok?li({try:()=>t(r),catch:()=>dH(`${n} response is invalid`)}):li({try:()=>XV(r),catch:()=>dH(`${n} error response is invalid`)}).pipe(T(y))))}function wH(e){let t=e.baseUrl.replace(/\/+$/u,``),n=e.fetch??globalThis.fetch,r=new Set,i=new Set,a=ry(!1),o=!1,s=lr(()=>o?y(fH()):ii),c=(e,t,n)=>En(CH(e,t,n),a.await.pipe(_(y(fH())))),l=(e,t)=>s.pipe(_(c(r=>n(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:r}),VV,`Extension command`)));return Object.freeze({createSession:e=>s.pipe(T(()=>{let r=tS({requestId:e});return c(e=>n(`${t}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:r}),signal:e}),nH,`Session creation`)})),deleteSession:e=>s.pipe(T(()=>{let r=$x(e);return c(e=>n(`${t}/sessions/${encodeURIComponent(r)}`,{method:`DELETE`,signal:e}),tH,`Session deletion`)})),listSessions:e=>s.pipe(T(()=>{let r=new URLSearchParams;e!==void 0&&r.set(`after`,eS(e));let i=r.size===0?``:`?${r.toString()}`;return c(e=>n(`${t}/sessions${i}`,{signal:e}),QV,`Session discovery`)})),extensions:Object.freeze({list:s.pipe(_(c(e=>n(`${t}/extensions`,{signal:e}),BV,`Extension list`))),resume:e=>s.pipe(_(c(r=>n(`${t}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:r}),zV,`Extension resume`))),call:(e,n,r)=>l(`${t}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(n)}`,r)}),session:o=>{let u=$x(o),d=yH(t,u),f=`${d}/events`;function p(e){return s.pipe(_(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`?HV:e.type===`cancel`?UV:e.type===`fork`?GV:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>s.pipe(_(c(t=>n(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),DV,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>Vn(()=>t?.requestId??Vg()).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(dt(e=>e.requestId===n?e:new G(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:s.pipe(_(c(e=>n(`${d}/pending/latest`,{signal:e}),WV,`Newest pending prompt`))),modelPreference:Object.freeze({read:s.pipe(_(c(e=>n(`${d}/model-preference`,{signal:e}),px,`Model preference read`))),set:e=>s.pipe(_(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(_(li({try:()=>nS(e),catch:e=>e instanceof G?e:dH(`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}),JV,`Session read`)})),readSettlement:(e,t=0)=>s.pipe(_(c(r=>n(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:r}),qV,`Command settlement`))),subscribe:t=>Mb(s.pipe(_(li({try:()=>rS(t),catch:e=>e instanceof G?e:dH(`Subscribe options are invalid`)})),Te(({after:t,includeSandboxFailures:n})=>xH(bH(f,t,n===!0),a,i,e.eventSource)))),watch:t=>SH(t?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,r,s,a,i,e.eventSource)})},close:lr(()=>o?ii:(o=!0,a.open.pipe(_($r([...r],e=>mo(e,Wa),{discard:!0})),_($r([...i],e=>_H(e,i),{discard:!0})))))})}function TH(e){return cH(wH(e),e.baseUrl.replace(/\/+$/u,``))}D(SA);function EH(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 DH(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 OH=M.pipe(z($h(1)),z(ng(128)),z(vh(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),kH=M.pipe(z($h(1)),z(ng(64)),z(vh(/^(?: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))),AH=OH.pipe(ih(`ExtensionId`)),jH=M.pipe(z(vh(/^sha256:[0-9a-f]{64}$/u)),ih(`ExtensionRevision`)),MH=M.pipe(z(vh(/^sha256:[0-9a-f]{64}$/u)),ih(`ExtensionFingerprint`)),NH=class extends Sa(`ExtensionHookError`){};function PH(e){return lr(()=>{let t=e();return qe(t)?t:fn({try:()=>Promise.resolve(t),catch:e=>new NH({cause:e})})})}var FH=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function IH(e,t){let n=e(t);if(n instanceof Promise||qe(n)&&!vr(n))throw new FH;return n}export{iB as $,Sm as $a,D as $i,MA as $n,Sa as $o,ry as $r,BN as $t,GB as A,Zh as Aa,Um as Ai,eM as An,so as Ao,dx as Ar,cz as At,EB as B,Rh as Ba,Wm as Bi,Lj as Bn,Ga as Bo,zb as Br,pP as Bt,LB as C,Wh as Ca,Ig as Ci,tN as Cn,Xs as Co,Xx as Cr,PL as Ct,gB as D,Xh as Da,Vm as Di,Yj as Dn,mo as Do,rS as Dr,BR as Dt,iV as E,Fh as Ea,Bh as Ei,uM as En,uo as Eo,Dx as Er,LL as Et,AB as F,ug as Fa,P as Fi,Hj as Fn,Qa as Fo,rx as Fr,xP as Ft,eV as G,A as Ga,z as Gi,fj as Gn,Oa as Go,_b as Gr,XN as Gt,qB as H,Ch as Ha,I as Hi,cj as Hn,qa as Ho,Tb as Hr,JN as Ht,NB as I,ig as Ia,Km as Ii,Mj as In,ro as Io,sx as Ir,CP as It,dB as J,nh as Ja,Om as Ji,HA as Jn,Na as Jo,Xb as Jr,oP as Jt,pB as K,k as Ka,hm as Ki,lj as Kn,Da as Ko,Pb as Kr,ZN as Kt,MB as L,$h as La,xg as Li,Rj as Ln,Ya as Lo,$b as Lr,lP as Lt,RB as M,ag as Ma,N as Mi,Xj as Mn,eo as Mo,ux as Mr,YP as Mt,zB as N,ng as Na,Ym as Ni,Qj as Nn,to as No,ix as Nr,JP as Nt,bB as O,Gh as Oa,Qm as Oi,Jj as On,fo as Oo,iS as Or,QR as Ot,KB as P,pg as Pa,M as Pi,Uj as Pn,$a as Po,ax as Pr,QP as Pt,Xz as Q,Mg as Qa,Dm as Qi,KA as Qn,ja as Qo,ay as Qr,UN as Qt,jB as R,fg as Ra,Zm as Ri,Ij as Rn,Va as Ro,ex as Rr,dP as Rt,IB as S,Yh as Sa,Fg as Si,QM as Sn,kc as So,nS as Sr,iR as St,OB as T,zh as Ta,L as Ti,fM as Tn,ao as To,$x as Tr,IL as Tt,CB as U,bh as Ua,Hm as Ui,dj as Un,Ba as Uo,Rb as Ur,YN as Ut,WB as V,vh as Va,th as Vi,uj as Vn,Ja as Vo,Yb as Vr,fP as Vt,SB as W,B as Wa,ih as Wi,oj as Wn,Wa as Wo,Ab as Wr,QN as Wt,aB as X,Pg as Xa,Tm as Xi,zA as Xn,ka as Xo,Qb as Xr,cP as Xt,lB as Y,ph as Ya,km as Yi,JA as Yn,Fa as Yo,Lb as Yr,sP as Yt,Yz as Z,Ng as Za,Em as Zi,qA as Zn,Ia as Zo,Mb as Zr,mP as Zt,mB as _,Dh as _a,qm as _i,DN as _n,Fd as _o,dD as _r,FL as _t,MH as a,Mm as aa,Sv as ai,AN as an,fl as ao,fA as ar,Ji as as,XR as at,xB as b,Uh as ba,Eh as bi,CM as bn,Ec as bo,RE as br,ER as bt,kH as c,wm as ca,rv as ci,zN as cn,ul as co,$O as cr,Di as cs,ZR as ct,TH as d,og as da,b_ as di,EN as dn,pl as do,wO as dr,Zi as ds,ZI as dt,O as ea,Qv as ei,FN as en,uh as eo,jA as er,Li as es,Qz as et,rH as f,qh as fa,x_ as fi,ON as fn,sl as fo,xO as fr,Xi as fs,UI as ft,wB as g,wh as ga,F as gi,SN as gn,Id as go,iO as gr,GI as gt,HV as h,dg as ha,Vg as hi,IN as hn,Pd as ho,uO as hr,sL as ht,AH as i,jm as ia,Cv as ii,NN as in,gl as io,xA as ir,Yi as is,DL as it,PB as j,Kh as ja,R as ji,$j as jn,co as jo,fx as jr,RF as jt,aV as k,Ih as ka,hg as ki,tM as kn,oo as ko,G as kr,kR as kt,DH as l,Lh as la,J_ as li,bN as ln,il as lo,bO as lr,Ti as ls,AR as lt,lH as m,mg as ma,i_ as mi,jN as mn,ml as mo,gO as mr,oL as mt,PH as n,Fm as na,$v as ni,LN as nn,Gf as no,OA as nr,Ci as ns,jz as nt,OH as o,U as oa,Y_ as oi,vN as on,ll as oo,ik as or,$i as os,zR as ot,iH as p,rg as pa,g_ as pi,RN as pn,al as po,hO as pr,FI as pt,uB as q,rh as qa,mm as qi,VA as qn,Pa as qo,jb as qr,$N as qt,IH as r,sh as ra,Ev as ri,CN as rn,mf as ro,SA as rr,Si as rs,iI as rt,jH as s,mh as sa,$_ as si,wN as sn,Bd as so,jk as sr,Ri as ss,KI as st,FH as t,Nm as ta,ey as ti,TN as tn,fh as to,AA as tr,Bi as ts,Sz as tt,EH as u,Qh as ua,S_ as ui,xN as un,cl as uo,TO as ur,wi as us,LR as ut,hB as v,Ph as va,Gm as vi,kN as vn,dd as vo,uD as vr,aL as vt,DB as w,Th as wa,j as wi,$M as wn,bs as wo,tS as wr,kL as wt,FB as x,V as xa,H as xi,nN as xn,Dc as xo,Yx as xr,sz as xt,TB as y,Jh as ya,_g as yi,MN as yn,Xc as yo,vD as yr,nL as yt,nV as z,lg as za,Cg as zi,Aj as zn,Ka as zo,xb as zr,uP as zt};
|