@fungi.computer/grove 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +106 -2
- package/dist/assets/Effect-CxgtVs4O.js +76 -0
- package/dist/assets/MapleMono-VF-CCDrizxw.woff2 +0 -0
- package/dist/assets/Nunito-VF-8c6a9bb-cyrillic-BsWUdSU9.woff2 +0 -0
- package/dist/assets/Nunito-VF-8c6a9bb-cyrillic-ext-Cb1j0nGJ.woff2 +0 -0
- package/dist/assets/Nunito-VF-8c6a9bb-latin-BYs3GYNf.woff2 +0 -0
- package/dist/assets/Nunito-VF-8c6a9bb-latin-ext-0RvtKGDy.woff2 +0 -0
- package/dist/assets/Nunito-VF-8c6a9bb-vietnamese-cS2dauUA.woff2 +0 -0
- package/dist/assets/anthropic-messages-DVt3Yh9K.js +41 -0
- package/dist/assets/azure-openai-responses-QZaJy-8U.js +1 -0
- package/dist/assets/base-face-BaB6vmvy.js +1 -0
- package/dist/assets/burger-CoqBXzRV.js +1 -0
- package/dist/assets/cat-2dRm7fBw.js +1 -0
- package/dist/assets/cloudflare-workers-ai-system-one-Bq-3_D9p.js +1 -0
- package/dist/assets/compat-fz0ZcRJH.js +2 -0
- package/dist/assets/diagnostics-CmW2yJSB.js +1 -0
- package/dist/assets/document-D5hwZS3o.js +1 -0
- package/dist/assets/error-CJ3RHG07.js +1 -0
- package/dist/assets/error-body-pkrba6pf.js +1 -0
- package/dist/assets/extension-hook-0UB2lkEs.js +560 -0
- package/dist/assets/extensions-CAsZR9ky.js +1 -0
- package/dist/assets/github-copilot-headers-DRgtIyTm.js +1 -0
- package/dist/assets/google-generative-ai-DP-8xZvz.js +1 -0
- package/dist/assets/google-shared-Cs5udoZV.js +8 -0
- package/dist/assets/google-vertex-BJiAIGUd.js +1 -0
- package/dist/assets/hash-yQufAZII.js +1 -0
- package/dist/assets/headers-FK4rgixo.js +1 -0
- package/dist/assets/index-Bw6tV9qS.css +1 -0
- package/dist/assets/index-DRDNbHYF.js +171 -0
- package/dist/assets/json-parse-nqKewMRF.js +3 -0
- package/dist/assets/mistral-conversations-mRYg3mWw.js +4 -0
- package/dist/assets/models-CcNnosqL.js +1 -0
- package/dist/assets/mushroom-B9t9hgQE.js +1 -0
- package/dist/assets/node.browser-DFtqp6Hr.js +1 -0
- package/dist/assets/node.browser-hsQQ6fyG.js +1 -0
- package/dist/assets/openai-Cpe0uoXQ.js +19 -0
- package/dist/assets/openai-codex-responses-CA-ivUEd.js +9 -0
- package/dist/assets/openai-completions-BxBCgHHI.js +5 -0
- package/dist/assets/openai-prompt-cache-DXo9f3w5.js +1 -0
- package/dist/assets/openai-responses-cvwOEFWg.js +1 -0
- package/dist/assets/openai-responses-shared-DzD8B6NI.js +10 -0
- package/dist/assets/openrouter-images-DwousKhc.js +1 -0
- package/dist/assets/parakeet-conversation-COndlivb.css +1 -0
- package/dist/assets/parakeet-conversation-w0nznEs9.js +3 -0
- package/dist/assets/pi-messages-CfXPQ4jp.js +7 -0
- package/dist/assets/preload-helper-mbhLTglw.js +8 -0
- package/dist/assets/provider-env-CcCbsTJq.js +1 -0
- package/dist/assets/provider-retry-CSlu6hjs.js +1 -0
- package/dist/assets/renderer-s3PB0XrL.js +1 -0
- package/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
- package/dist/assets/runtime-core-GKyHklNK.js +2 -0
- package/dist/assets/sanitize-unicode-DmIE6hZJ.js +1 -0
- package/dist/assets/system-one-shared-CGF8IYMZ.js +1 -0
- package/dist/assets/transform-messages-CrQEqmfx.js +1 -0
- package/dist/assets/typesafe-system-one-CWcJw-Ys.js +1 -0
- package/dist/index.html +19 -0
- package/package.json +175 -3
|
@@ -0,0 +1,560 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-fz0ZcRJH.js","assets/preload-helper-mbhLTglw.js","assets/provider-env-CcCbsTJq.js","assets/rolldown-runtime-hePW80VL.js","assets/diagnostics-CmW2yJSB.js","assets/models-CcNnosqL.js","assets/json-parse-nqKewMRF.js","assets/openai-codex-responses-CA-ivUEd.js","assets/headers-FK4rgixo.js","assets/transform-messages-CrQEqmfx.js","assets/error-body-pkrba6pf.js","assets/openai-prompt-cache-DXo9f3w5.js","assets/openai-responses-shared-DzD8B6NI.js","assets/sanitize-unicode-DmIE6hZJ.js","assets/hash-yQufAZII.js","assets/runtime-core-GKyHklNK.js","assets/Effect-CxgtVs4O.js","assets/index-DRDNbHYF.js","assets/document-D5hwZS3o.js","assets/base-face-BaB6vmvy.js","assets/index-Bw6tV9qS.css","assets/extensions-CAsZR9ky.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{$ as e,$i as t,$r as n,$t as r,A as i,An as a,Ar as o,At as s,B as c,Bi as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as ee,Cr as te,Ct as ne,D as re,Dn as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Er as ue,Et as de,F as fe,Fr as pe,Ft as me,G as he,Gr as ge,Gt as _e,H as ve,Ha as ye,Hi as be,Hn as xe,Hr as Se,Ht as Ce,I as we,Ir as Te,It as Ee,J as De,Ji as Oe,Jn as ke,Jr as Ae,Jt as je,K as Me,Ki as Ne,Kr as Pe,Kt as Fe,L as Ie,La as Le,Ln as Re,Lr as ze,Lt as Be,M as Ve,Mn as He,Mt as Ue,N as We,Nn as Ge,Nr as h,Nt as Ke,O as qe,Or as Je,Ot as Ye,P as Xe,Pn as Ze,Pr as Qe,Pt as $e,Q as et,Qi as g,Qr as tt,Qt as nt,R as rt,Ri as it,Rn as at,Rr as _,Rt as ot,S as st,Si as ct,Sn as lt,Sr as ut,T as dt,Ti as ft,Tn as pt,Tr as mt,Tt as ht,U as gt,Ui as _t,Un as vt,Ut as yt,V as bt,Vi as xt,Vr as St,Vt as Ct,W as wt,Wi as Tt,Wr as Et,Wt as Dt,Xi as Ot,Xn as kt,Xt as At,Y as jt,Yi as Mt,Yn as Nt,Yr as Pt,Yt as Ft,Z as It,Zi as Lt,Zr as Rt,Zt as zt,_ as Bt,_i as Vt,_r as Ht,_t as Ut,a as Wt,aa as Gt,ai as Kt,an as qt,ar as Jt,at as Yt,b as Xt,br as Zt,bt as Qt,c as $t,ca as en,ci as tn,cn as nn,cr as rn,ct as v,d as an,da as on,di as sn,dn as cn,dr as ln,dt as un,ea as dn,ei as fn,en as pn,er as mn,et as hn,f as gn,fi as _n,fn as vn,g as y,gi as yn,gn as bn,gr as xn,gt as Sn,h as Cn,hi as wn,hn as Tn,hr as En,ht as Dn,i as On,ii as kn,in as An,ir as jn,it as Mn,j as Nn,jr as Pn,jt as Fn,k as In,kn as Ln,kr as Rn,kt as zn,l as Bn,li as Vn,ln as Hn,lr as Un,lt as Wn,m as Gn,mi as Kn,mn as qn,mt as Jn,na as Yn,ni as Xn,nn as Zn,nr as Qn,nt as $n,o as er,oa as tr,oi as nr,on as rr,or as ir,ot as ar,p as or,pi as sr,pn as cr,pr as lr,pt as ur,q as dr,qi as fr,qr as pr,qt as mr,r as hr,ra as gr,ri as _r,rn as vr,s as yr,sa as b,si as br,sn as xr,sr as Sr,st as Cr,t as wr,ta as Tr,ti as Er,tn as Dr,tt as Or,u as kr,ua as Ar,ui as jr,un as Mr,ur as Nr,ut as x,v as Pr,vi as Fr,vr as Ir,vt as Lr,w as Rr,wi as zr,wn as Br,wr as Vr,wt as Hr,x as Ur,xi as Wr,xn as Gr,xr as Kr,xt as qr,y as S,yi as C,yr as Jr,yt as w,z as Yr,zn as Xr,zr as Zr,zt as Qr}from"./Effect-CxgtVs4O.js";import{d as $r,t as ei}from"./preload-helper-mbhLTglw.js";var ti=new WeakMap,ni=`~effect/Redacted`,ri=e=>Xn(e,ni),ii=(e,t)=>{let n=Object.create(ai);return t?.label&&(n.label=t.label),ti.set(n,e),n},ai={[ni]:{_A:e=>e},label:void 0,...En,toJSON(){return this.toString()},toString(){return`<redacted${sr(this.label)?`:`+this.label:``}>`},[Er](){return tt(ti.get(this))},[Pt](e){return ri(e)&&Pe(ti.get(this),ti.get(e))}},oi=e=>e>0?Math.floor(e):0,si=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},ci=`~effect/BigDecimal`,li={[ci]:ci,[Er](){let e=_i(this);return Rt(fn(String(e.value)),n(e.scale))},[Pt](e){return ui(e)&&Si(this,e)===0},toString(){return`BigDecimal(${wi(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[ze](){return this.toJSON()},pipe(){return ce(this,arguments)}},ui=e=>Xn(e,ci),di=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(li);return n.value=e,n.scale=t,n},fi=(e,t)=>{let n=di(e,t);return n.normalized=n,n},pi=BigInt(0),mi=BigInt(1),hi=BigInt(10),gi=fi(pi,0),_i=e=>{if(e.normalized===void 0){if(e.value===pi)e.normalized=gi;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=fi(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},vi=100,yi=[mi],bi=(e,t)=>e===t?0:e<t?-1:1,xi=(e,t)=>{let n=`${e.value<pi?-e.value:e.value}`,r=`${t.value<pi?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==pi)return i<pi?-1:1;let a=Math.max(n.length,r.length);return Sr(n.padEnd(a,`0`),r.padEnd(a,`0`))},Si=(e,t)=>{if(e.scale===t.scale)return bi(e.value,t.value);let n=Ci(e),r=Ci(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>vi)return n===-1?xi(t,e):xi(e,t);let o=yi[a]??=hi**BigInt(a);return i>0?bi(e.value,t.value*o):bi(e.value*o,t.value)},Ci=e=>e.value===pi?0:e.value<pi?-1:1,wi=e=>{let t=_i(e);if(Math.abs(t.scale)>=16)return Ti(t);let n=t.value<pi,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},Ti=e=>{if(Ei(e))return`0e+0`;let t=_i(e),n=`${t.value}`,r=t.value<pi?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Ei=e=>e.value===pi,Di=xn,Oi=`~effect/encoding/EncodingError`,ki=class extends Di(`EncodingError`){[Oi]=Oi},Ai=Rn,ji=Zt,Mi=Ir,Ni=Ft,Pi=oe,Fi=zn,Ii=_e,Li=Fe,Ri=Dt,zi=Ye,Bi=ae,Vi=Kr;lt()(`effect/Cause/StackTrace`),lt()(`effect/Cause/InterruptorStackTrace`);var Hi=ue,Ui=mt,Wi=Vr,Gi=te,Ki=ot,qi=Ee,Ji=me,Yi=Be,Xi=Ke,Zi={"~effect/Deferred":{_A:Wr,_E:Wr},pipe(){return ce(this,arguments)}},Qi=function(){this.resumes=void 0,this.effect=void 0};Qi.prototype=Zi;var $i=()=>new Qi,ea=()=>cr(()=>$i()),ta=e=>ht(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),cr(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),na=C(2,(e,t)=>cr(()=>aa(e,t))),ra=C(2,(e,t)=>na(e,Vr(t))),ia=C(2,(e,t)=>na(e,ue(t))),aa=(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},oa=Hn,sa=xr,ca=nn,la=Dr,ua=An,da=vr,fa=rr,pa=qt,ma=Fn,ha=`~effect/DateTime`,ga=`~effect/DateTime/TimeZone`,_a={[ha]:ha,pipe(){return ce(this,arguments)},[ze](){return this.toString()},toJSON(){return ya(this).toJSON()}};({..._a}),{..._a};var va={[ga]:ga,[ze](){return this.toString()}};({...va}),{...va};var ya=e=>new Date(e.epochMilliseconds);globalThis.Number;var ba=C(2,(e,t)=>{if(!globalThis.Number.isFinite(e)||!globalThis.Number.isFinite(t)||t===0)return NaN;if(globalThis.Number.isInteger(e)&&globalThis.Number.isInteger(t))return e%t;let[n,r]=xa(e),[i,a]=xa(t),o=Math.min(r,a),s=n*BigInt(10)**BigInt(r-o)%(i*BigInt(10)**BigInt(a-o));if(s===BigInt(0))return e<0||Object.is(e,-0)?-0:0;let c=globalThis.Number(`${s}e${o}`);return c===0?Math.sign(e)*globalThis.Number.MIN_VALUE:c});function xa(e){if(globalThis.Number.isInteger(e))return[BigInt(e),0];let t=Math.abs(e).toExponential(),n=t.indexOf(`e`),r=t.slice(0,n).replace(`.`,``);return[BigInt(r)*(e<0?-BigInt(1):BigInt(1)),globalThis.Number(t.slice(n+1))-r.length+1]}globalThis.String;var Sa=e=>e.trim(),Ca=C(2,(e,t)=>de(e,Da,e=>t(e))),wa=e=>e.reasons.some(Ta),Ta=e=>e._tag===`Fail`&&Bi(e.error),Ea=e=>{let t,n=!1;for(let r of e.reasons)Ta(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?Ze(e):n?Ze(ji(e.reasons.filter(e=>!Ta(e)))):xe(t)},Da=e=>{let t=Ea(e);return Re(t)?t:xe(t.success.value)},Oa=e=>{let t=Ea(e);return Re(t)?Ui(t.failure):Hi(t.success.value)},ka=Gr(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),Aa=Gr(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),ja=`~effect/Metric`,Ma=class{[ja]=ja;#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=pt(e,ka);t!==this.#e&&(this.#e=t,this.#t=za(this,Va(this.attributes,t)));let n=pt(e,Aa),r=n.get(this.#t);return wn(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?Va(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return ce(this,arguments)}},Na=BigInt(0),Pa=class extends Ma{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,Ha(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?Na:0,t=this.#t?this.#e?e=>e>=Na:e=>e>=0:e=>!0;return Ba(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},Fa=class extends Ma{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()}},Ia=(e,t)=>new Pa(e,t),La=C(2,(e,t)=>s(n=>cr(()=>e.updateUnsafe(t,n)))),Ra=C(2,(e,t)=>{let n=Ua(t);return new Fa(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function za(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 Ba(e,t,n){return{get:e,update:t,modify:n??t}}function Va(e,t){return{...Ha(e),...Ha(t)}}function Ha(e){return tn(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(h(e,t,n),e),{}):e}function Ua(e){let t,n={};return r=>{let i=pt(r,ka);return i!==t&&(t=i,n=Va(i,e)),ee(r,ka,n)}}lt()(`effect/DateTime/CurrentTimeZone`);var Wa=e=>Ka(typeof e==`string`?qa.encode(e):e),Ga=e=>{let t=Ja(e),n=t.length;if(n%4!=0)return Ze(new ki({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${n}`}));let r=t.indexOf(`=`);if(r!==-1&&(r<n-2||r===n-2&&t[n-1]!==`=`))return Ze(new ki({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),r=new Uint8Array(n/4*3-e);for(let e=0,i=0;e<n;e+=4,i+=3){let n=Za(t.charCodeAt(e))<<18|Za(t.charCodeAt(e+1))<<12|Za(t.charCodeAt(e+2))<<6|Za(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return xe(r)}catch(e){return Ze(new ki({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Ka=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=Ya[e[r-2]>>2],n+=Ya[(e[r-2]&3)<<4|e[r-1]>>4],n+=Ya[(e[r-1]&15)<<2|e[r]>>6],n+=Ya[e[r]&63];return r===t+1&&(n+=Ya[e[r-2]>>2],n+=Ya[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=Ya[e[r-2]>>2],n+=Ya[(e[r-2]&3)<<4|e[r-1]>>4],n+=Ya[(e[r-1]&15)<<2],n+=`=`),n},qa=new TextEncoder,Ja=e=>e.replace(/[\n\r]/g,``),Ya=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Xa=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Xa[Ya.charCodeAt(e)]=e;Xa[61]=0;var Za=e=>{if(e>=Xa.length||Xa[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Xa[e]};Di(`CookiesError`),{...Te},{...Te},{...En};function Qa(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function $a(e){return t=>Qa(t)?.[e]}var eo=`~structural`,to=`~identifier`,no=`~sentinels`,ro=`~constructor`,io=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],ao=$a(`identifier`),oo=$a(to),so=$a(`title`),co=$a(`description`),lo=ct(e=>{let t=Qa(e)?.identifier;return typeof t==`string`?t:e.getExpected(lo)}),uo=new Set([no,eo,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),T=Symbol(),fo=Hi,po=fo(T),mo=fo(T),ho=e=>e===T?mn():Qn(e),go=e=>e._tag===`None`?po:fo(e.value),_o=`~effect/SchemaIssue/Issue`;function vo(e){return Xn(e,_o)&&e[_o]===_o}function yo(e){return Object.hasOwn(e,`input`)}var bo=class{[_o]=_o;constructor(e,t){t?.reportInput===!0&&e!==T&&(this.input=e)}},xo=class extends bo{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},So=class extends bo{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},Co=class extends bo{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},wo=class extends bo{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},To=class extends bo{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Eo=class extends bo{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},Do=class extends bo{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},Oo=class extends bo{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},ko=class extends bo{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},Ao=class extends bo{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},jo=class extends bo{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function Mo(e,t,n){if(vo(e))return e;if(typeof e==`string`)return new Oo({message:e},t,n);let r=typeof e.issue==`string`?new Oo({message:e.issue},t,n):e.issue;return new Co(e.path,r)}function No(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new Oo(void 0,t,n):Mo(e,t,n)}function Po(e,t,n,r){return Array.isArray(t)?a(t)?t.length===1?Mo(t[0],n,r):new Eo(e,He(t,e=>Mo(e,n,r)),n,r):void 0:No(t,n,r)}var Fo=e=>{let t=Ko(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Bo(lo(e.ast),e);case`InvalidValue`:{let t=zo(e);if(t!==void 0)return Bo(t,e);let n=Ro(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=Ro(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=Ro(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Io=e=>Ko(e.issue)??Ko(e);function Lo(e){return t=>({issues:Vo(t,[],e?.leafHook??Fo,e?.checkHook??Io)})}function Ro(e){return yo(e)?_(e.input):void 0}function zo(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Bo(e,t){let n=Ro(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Vo(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 Vo(e.issue,t,n,r);let a=zo(e.issue);return[{path:t,message:a===void 0?Bo(Ho(e.filter),e):Bo(a,e.issue)}]}case`Encoding`:return Vo(e.issue,t,n,r);case`Pointer`:return Vo(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>Vo(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:Ko(e)??Bo(lo(e.ast),e)}]:e.issues.flatMap(e=>Vo(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Ho(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=>Ho(e)).join(` & `)}}function Uo(){return e=>Go(e,``)}var Wo=Uo();function Go(e,t){let n;switch(e._tag){case`Filter`:{let r=Io(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return Go(e.issue,t);let r=zo(e.issue);n=r===void 0?Bo(Ho(e.filter),e):Bo(r,e.issue)}break}case`Encoding`:return Go(e.issue,t);case`Pointer`:return Go(e.issue,t+d(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Go(e,t)).join(`
|
|
3
|
+
`);n=Ko(e)??Bo(lo(e.ast),e);break;default:n=Fo(e)}return t?`${n}\n at ${t}`:n}function Ko(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Ko(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 qo(e){let t;for(let n of e.reasons){if(!Ai(n)||!vo(n.error))return;t??=n.error}return t}function Jo(e,t){let n=qo(e);if(n===void 0)throw Error(t,{cause:e});return n}var Yo=e=>Wa(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Xo=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return Ze(new ki({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 Ze(new ki({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,`/`),Ga(r)},Zo=e=>Object.assign(Object.create(ft),e),Qo=Zo({_tag:`Passthrough`});function $o(){return Qo}function es(){return Qo}function ts(e){return Zo({_tag:`Transform`,transform:e})}function ns(e){return Zo({_tag:`TransformEffect`,transform:e})}function rs(e){return Zo({_tag:`TransformOptional`,transform:e})}function is(e){return Zo({_tag:`TransformOptionalEffect`,transform:e})}function as(){return rs(()=>mn())}function os(e){return is(t=>{let n=vt(t,tn);return kt(n)?v(n):fe(e,Qn)})}function ss(){return ts(globalThis.String)}function cs(){return ts(globalThis.Number)}function ls(){return ts(globalThis.BigInt)}function us(){return ts(e=>new globalThis.Date(e))}function ds(){return ts(Sa)}function fs(e){return ns((t,n)=>Sn({try:()=>JSON.parse(t,e?.reviver),catch:()=>new Oo({expected:`a valid JSON string`},t,n)}))}function ps(e){return ns((t,n)=>Sn({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 Oo({expected:`a JSON-serializable value`},t,n)}))}function ms(){return ts(Wa)}function hs(){return ns((e,t)=>Ie(In(Ga(e)),()=>new Oo({expected:`a valid Base64 string`},e,t)))}var gs=class extends zr{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new gs(this.encode,this.decode)}},_s=`~effect/SchemaTransformation/Transformation`,vs=class extends zr{[_s]=_s;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new vs(this.encode,this.decode)}};function ys(e){return Xn(e,_s)&&e[_s]===_s}var bs=e=>ys(e)?e:new vs(e.decode,e.encode);function xs(){return new vs(ds(),$o())}var Ss=new vs($o(),$o());function Cs(){return Ss}var ws=new vs(cs(),ss()),Ts=new vs(ls(),ss()),Es=new vs(us(),ts(Zr)),Ds=new vs(hs(),ms());function Os(e){return new vs(fs(e??{}),ps(e))}function ks(e){return t=>t._tag===e}var As=ks(`Declaration`),js=ks(`Null`),Ms=ks(`Undefined`),Ns=ks(`Never`),Ps=ks(`String`),Fs=ks(`Number`),Is=ks(`Boolean`),Ls=ks(`Literal`),Rs=ks(`UniqueSymbol`),zs=ks(`Arrays`),Bs=ks(`Objects`),Vs=ks(`Union`),Hs=ks(`Suspend`),Us=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Ws={},Gs=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}},Ks=`~effect/Schema`,qs=class{[Ks]=Ks;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}>`}},Js=class extends qs{_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===T?po:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=xl(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Js(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>`}},Ys=new class extends qs{_tag=`Null`;getParser(){return Hl(this,null)}getExpected(){return`null`}},Xs=class extends qs{_tag=`Undefined`;getParser(){return Hl(this,void 0)}toCodecJson(){return ll(this,[Zs])}getExpected(){return`undefined`}},Zs=new Us(Ys,new vs(ts(()=>void 0),ts(()=>null))),Qs=new Xs,$s=new class extends qs{_tag=`Never`;getParser(){return Ul(this,nr)}getExpected(){return`never`}},ec=new class extends qs{_tag=`Unknown`;getParser(){return Ul(this,yn)}getExpected(){return`unknown`}},tc=class extends qs{_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 ${_(e)}`);this.literal=e}getParser(){return Hl(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?nc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:nc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function nc(e){let t=globalThis.String(e.literal);return ll(e,[new Us(new tc(t),new vs(ts(()=>e.literal),ts(()=>t)))])}var rc=new class extends qs{_tag=`String`;getParser(){return Ul(this,sr)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&au(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},ic=class extends qs{_tag=`Number`;getParser(){return Ul(this,Vn)}matchKey(e,t){return this._match(Jl,e,t)}matchPart(e,t){return this._match(ql,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:au(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(ac(this.checks,`effect/schema/isFinite`)||ac(this.checks,`effect/schema/isInt`))?this:ll(this,[il])}toCodecStringTree(){return this.toCodecJson()===this?ll(this,[Zl]):ll(this,[Ql])}getExpected(){return`number`}};function ac(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&ac(e.checks,t))}var oc=new ic,sc=new class extends qs{_tag=`Boolean`;getParser(){return Ul(this,kn)}getExpected(){return`boolean`}},cc=new class extends qs{_tag=`Symbol`;getParser(){return Ul(this,Kn)}matchKey(e,t){return t.disableChecks||!this.checks?e:au(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return ll(this,[ru])}getExpected(){return`symbol`}},lc=new class extends qs{_tag=`BigInt`;getParser(){return Ul(this,_r)}matchPart(e,t){if(!$l.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:au(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return ll(this,[tu])}getExpected(){return`bigint`}},uc=class extends qs{_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(Ml(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(Ml(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 To(n,t[o],i),a=new Co([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return y(new Eo(n,[a],t,i))}return e.issues?y(new Eo(n,e.issues,t,i)):fo(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:Zn(t.concurrency),f=d===1?pc(i,e,0,u):mc(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Ue(f))return Xt(f,()=>c(i));let p=!0;return Wn(()=>p?(p=!1,S(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===T)return po;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 Do(n,e,a))}catch(e){return or(e)}}}_rebuild(e,t,n){let r=xl(this.elements,e),i=xl(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new uc(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 dc(e,t,n,r){if(n._tag===`Failure`)return hc(e,e.ast,r,n);let i=n===mo?t:n[Ht];if(i!==T)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Ml(t.ast))return;let n=new Co([r],new wo(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return Wi(new Eo(e.ast,[n],e.input,e.options))}}var fc={onItem(e,t,n){let r=n<e.len?t:T;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:dc},pc=zt()(fc),mc=At()(fc),hc=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=qo(r.cause);if(i===void 0)return Ui(Pi(r.cause,r=>new Eo(t,[new Co([n],r)],e.input,e.options)));let a=new Co([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return Wi(new Eo(t,[a],e.input,e.options))},gc=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function _c(e,t,n=Ws){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(Wl(Rl(t)))}var vc=class{name;type;constructor(e,t){this.name=e,this.type=t}};function yc(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(yc);default:return!1}}function bc(e){let t=dl(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(bc);default:return!1}}function xc(e){return yc(e)&&bc(e)}var Sc=class{parameter;type;constructor(e,t){if(!xc(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Ml(t)&&!Vl(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},Cc=class extends qs{_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 Ul(n,br);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(Wl(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 hc(t,n,i,s)??Ki;let c=s===mo?o:s[Ht];if(a!==T&&c!==T){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return Ki;h(t.out,a,c)}return Ki},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Ue(t))return S(Cn(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return hc(e,n,r,a)??Ki;let o=a===mo?r:a[Ht],s=e.input[r],l=i.parserValue(s,e.options);return Ue(l)?t(e,r,o,s,l):S(Cn(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Ue(a)?t(e,n,n,i,a):S(Cn(a),r=>t(e,n,n,i,r))},u=i?At()({onItem:(e,[t,n])=>n.is.parameter===rc?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===T)return T;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*y(new Do(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:Zn(d.concurrency),re=i&&te?n.indexSignatures.map(e=>_c(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 To(n,f[a],d),r=new Co([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*y(new Eo(n,[r],t,d))}}}if(r){let e=ne===1?Ec(m,a):Dc(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===rc?l:c,r=re?.[e]??(t.is.parameter===rc?Object.keys(f):_c(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Ue(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=ie();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===rc?Object.keys(f):_c(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 Eo(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return S(Cn(n),n=>{let i=wc(e,r,n);if(i)return i;let o=()=>fo(e.out),s=Ec(e,a.slice(t+1));return s?Xt(s,o):o()})};return(e,t)=>{if(e===T)return po;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Zn(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return y(new Do(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=Bc(i,s),l=c?i[s]:T,d=n.parser(l,t);if(!Ue(d))return u(o,e,d);if(d===mo){c&&h(a,s,l);continue}let f=wc(o,n,d);if(f)return f}}catch(e){return or(e)}return fo(a)}}_rebuild(e,t,n,r){let i=xl(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new vc(t.name,n)}),a=xl(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new Sc(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new Cc(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 wc(e,t,n){if(n._tag===`Failure`)return hc(e,e.ast,t.name,n);if(n===mo)return;let r=n[Ht];if(r!==T){h(e.out,t.name,r);return}if(delete e.out[t.name],!Ml(t.type)){let n=new Co([t.name],new wo(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return Wi(new Eo(e.ast,[n],e.input,e.options))}}var Tc={onItem(e,t){if(!Bc(e.input,t.name))return t.parser(T,e.options);let n=e.input[t.name];return h(e.out,t.name,n),t.parser(n,e.options)},step:wc},Ec=zt()(Tc),Dc=At()(Tc);function Oc(e,t){return e?t?[...e,...t]:e:t}function kc(e,t,n){return new Cc(Reflect.ownKeys(e).map(t=>new vc(t,e[t].ast)),[],n,t)}function Ac(e){return e.ast}function jc(e,t=void 0){return new uc(!1,e.map(e=>e.ast),[],void 0,t)}function Mc(e,t,n){return new Hc(e.map(Ac),t,void 0,n)}function Nc(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new uc(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var Pc=m(e=>{for(;;){if(Hs(e))return ec;let t=e.encoding;if(!t)return e.recur?.(Pc,Wr)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==Wr))return ec;e=t[t.length-1].to}});function Fc(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(Fc)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function Ic(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[no];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Ml(t)){if(Ls(t))return[{key:e.name,literal:t.literal}];if(Rs(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Ml(e)){if(Ls(e))return[{key:t,literal:e.literal}];if(Rs(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>Ic(Pc(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return Ic(e.thunk())}}var Lc=new WeakMap,Rc=Object.freeze([]),zc=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Bc=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Vc(e){let t=Lc.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=Pc(c);if(Ns(l))continue;if(Ls(l)||Rs(l)){a??=new Map;let e=Ls(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=Ic(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=Fc(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Rc);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Rc;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(sn(e)){let n=Bc(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Rc;if(t)return o}return Rc}}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=zc(t);if(!sn(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Bc(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=Bc(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=Bc(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(zc(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Lc.set(e,t),t}var Hc=class extends qs{_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===T)return po;let i=(o??=Vc(n.types))(e,r);if(i.length===0)return y(new Ao(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Ue(r)?Uc(n,r.cause,e,t):Wc(n,r,e,t)}return Gc(n,a,i,e,t)}}_rebuild(e,t,n){let r=xl(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Hc(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=Rl(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Ls);if(t.length>0)return`${Yc(n.isMutable)}[ ${t.map(t=>e(t)+Xc(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Ls(e.type));if(t.length>0)return`{ ${t.map(t=>`${Yc(t.type.context?.isMutable)}${St(t.name)}${Xc(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Uc(e,t,n,r){let i=qo(t);return i?Wi(new Ao(e,[i],n,r)):Ui(t)}function Wc(e,t,n,r){return kr(t,t=>Uc(e,t,n,r))}function Gc(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=qc(a,n);if(!o)return a.out?a.out:y(new Ao(e,a.issues??[],r,i));if(Ue(o))return Kc(o,a);let s=!0;return Wn(()=>s?(s=!1,Kc(o,a)):Gc(e,t,n,r,i))}function Kc(e,t){return Xt(e,e=>t.out===mo?v(t.input):t.out?t.out:y(new Ao(t.ast,t.issues??[],t.input,t.options)))}var qc=zt()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=qo(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]),Wi(new jo(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return Ki}}}),Jc=new Hc([new tc(`Infinity`),new tc(`-Infinity`),new tc(`NaN`)]);function Yc(e){return e?``:`readonly `}function Xc(e){return e?`?`:``}var Zc=class extends qs{_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 Zc(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Qc=class extends zr{_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 Qc(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Qc(this.run,this.annotations,!0)}and(e,t){return new $c([this,e],t)}},$c=class extends zr{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new $c(this.checks,{...this.annotations,...e})}and(e,t){return new $c([this,e],t)}};function el(e,t,n=!1){return new Qc((t,n,r)=>Po(n,e(t,n,r),t,r),t,n)}function tl(e,t){return new Qc((t,n,r)=>e(t)?void 0:new Oo(void 0,t,r),t,!0)}function nl(e){return el(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 rl=ml(oc,[nl()]),il=new Us(new Hc([rl,Jc]),new vs(cs(),ts(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function al(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return el(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 ol=new WeakMap;function sl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&ol.set(n,cl(e)),n}function cl(e){let t=ol.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 ol.set(e,n),n}function ll(e,t){return e.encoding===t?e:sl(e,{encoding:t})}function ul(e,t){if(e.context===t)return e;let n=cl(e);return n.context===t&&n.encoding===e.encoding?n:sl(e,{context:t})}function dl(e){return e.encoding?dl(e.encoding[e.encoding.length-1].to):e}function fl(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return pl(e,le(e.checks.slice(0,-1),n.annotate(t)))}return sl(e,{annotations:{...e.annotations,...t}})}function pl(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:sl(e,{checks:t})}function ml(e,t){return pl(e,Oc(e.checks,t))}function hl(e,t){let n=t(e.to);return n===e.to?e:new Us(n,e.transformation)}function gl(e,t){let n=e,r=n[n.length-1],i=hl(r,t);return i===r?e:le(e.slice(0,e.length-1),i)}function _l(e){return t=>t.encoding?ll(t,gl(t.encoding,e)):t}function vl(e,t){return _l(e=>ul(e,t))(e)}function yl(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:ll(r,gl(r.encoding,n))}return e(r)}return m(n)}function bl(e,t,n){let r=new Us(e,t);return ll(n,n.encoding?[...n.encoding,r]:[r])}function xl(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 Sl(e,t){return ul(e,e.context?new Gs(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Gs(!1,!1,void 0,t))}var Cl=m(e=>wl(ul(e,e.context?e.context.isOptional===!1?new Gs(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Gs(!0,!1)))),wl=_l(Cl),Tl=ct(e=>Cl(new Hc([e,Qs]))),El=m(e=>Dl(ul(e,e.context?e.context.isMutable===!1?new Gs(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new Gs(!1,!0)))),Dl=_l(El);function Ol(e,t){return ul(e,e.context?new Gs(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Gs(!1,!1,t))}function kl(e,t,n){return bl(e,n,t)}function Al(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:_n(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 jl(e,t){let{literals:n,parameters:r}=Al(e);return new Cc(n.map(e=>new vc(e,t)),r.map(e=>new Sc(e,t)))}function Ml(e){return e.context?.isOptional??!1}function Nl(e){return e.context?.isMutable??!1}function Pl(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(Pl)}function Fl(e){function t(e){return Pl(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Ln(n)?n:void 0}function Il(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Hs(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var Ll=m(e=>{let t=cl(e);if(t!==e){let n=Ll(t);return n===t&&e.encoding===void 0?e:ul(n,e.context)}let n=`recur`in e?e.recur(Ll):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Il(e)?n.encodingChecks:zs(n)||Bs(n)||As(n)&&n.typeParameters.length>0?Fl(n.encodingChecks):void 0;return sl(n,{encodingChecks:void 0,checks:Oc(n.checks,t)})}return n}),Rl=m(e=>Ll(Bl(e)));function zl(e,t){let n=t,r=n.length,i=n[r-1],a=[new Us(Bl(ll(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Us(Bl(n[e-1].to),n[e].transformation.flip()));let o=Bl(i.to);return o.encoding?ll(o,[...o.encoding,...a]):ll(o,a)}var Bl=ct(e=>{if(e.encoding)return zl(e,e.encoding);let t=cl(e);if(t!==e){let n=Bl(t);return n===t?e:ul(n,e.context)}return`flip`in e?e.flip(Bl):`recur`in e?e.recur(Bl):e});function Vl(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Vl);default:return!1}}function Hl(e,t){let n=t===0?mo:fo(t);return(r,i)=>r===T?po:r===t?n:y(new Do(e,r,i))}function Ul(e,t){return(n,r)=>n===T?po:t(n)?mo:y(new Do(e,n,r))}var Wl=yl(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Wl)}}),Gl=yl(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Gl)}}),Kl=`[\\s\\S]*?`,ql=new globalThis.RegExp(`^${gc}$`),Jl=new globalThis.RegExp(`^(?:${gc}|Infinity|-Infinity|NaN)$`);function Yl(e){return al(ql,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:ql.source}),...e})}var Xl=ml(rc,[Yl()]),Zl=new Us(Xl,ws),Ql=new Us(new Hc([Xl,Jc]),ws),$l=new globalThis.RegExp(`^-?\\d+$`);function eu(e){return al($l,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:$l.source}),...e})}var tu=new Us(ml(rc,[eu({expected:`a string representing a bigint`})]),Ts),nu=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),ru=new Us(ml(rc,[iu()]),new vs(ts(e=>globalThis.Symbol.for(nu.exec(e)[1])),ns((e,t)=>globalThis.Symbol.keyFor(e)===void 0?y(new ko({message:`cannot serialize to string, Symbol is not registered`},e,t)):v(globalThis.String(e)))));function iu(e){return al(nu,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:nu.source}),...e})}function au(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=au(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 xo(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function ou(e){if(!As(e))return;let t=e.annotations?.[ro];return Kt(t)?t(e.typeParameters):void 0}var su=Qa,cu=so,lu=co;function uu(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function du(e){return e===void 0||typeof e==`string`}function fu(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 pu(e){return fu(e,uu)}var mu=new Js([],()=>(e,t,n)=>pu(e)?mo:y(new Do(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>vu}),hu=new Us(mu,Cs()),gu=new Us(new Hc([new uc(!1,[],[mu]),new Cc([],[new Sc(rc,mu)])]),Cs());function _u(e){return fu(e,du)}var vu=new Us(new Js([],()=>(e,t,n)=>_u(e)?mo:y(new Do(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),Cs()),yu=(e,t,n)=>e===mo?n(t):Xt(e,n);function bu(e){if(e._tag===`Middleware`)return(t,n,r)=>xu(t===mo?e.decode(fo(ho(n)),r):e.decode(fe(t,ho),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===mo?fo(t):e;case`Transform`:{let e=e=>e===T?po:fo(t.transform(e));return(t,n)=>yu(t,n,e)}case`TransformOptional`:{let e=e=>go(t.transform(ho(e)));return(t,n)=>yu(t,n,e)}case`TransformEffect`:return(e,n,r)=>yu(e,n,e=>e===T?po:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>yu(e,n,e=>xu(t.transform(ho(e),r)))}}var xu=e=>Xt(e,go),Su=(e,t,n,r)=>kr(r,r=>Pr(()=>Pi(r,r=>new So(e,r,t,n))));function Cu(e,t){let n=bu(e.link.transformation),r;return(i,a)=>{if(i===T)return po;if(e.isConstructed(i))return mo;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function wu(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==T&&r!==void 0)return t(r,i);let a=n;if(Ue(a)&&a._tag===`Success`){let e=t(a[Ht],i);return e===mo?a:e}return Xt(Su(e,r,i,a),e=>{let n=t(e,i);return n===mo?fo(e):n})}}function Tu(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:wu(e,n)}function Eu(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?ou(e):void 0,o=a?Cu(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>bu(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(Ue(r)){if(r._tag===`Success`){let i=r===mo?t:r[Ht];if(t!==T&&i!==T){let i=au(u,t,void 0,e,n);i&&(r=y(new Eo(e,i,t,n)))}}}else r=S(r,r=>{if(t!==T&&r!==T){let r=au(u,t,void 0,e,n);if(r)return y(new Eo(e,r,t,n))}return v(r)})}if(s&&!n.disableChecks){if(Ue(r)){if(r._tag===`Success`){let i=r===mo?t:r[Ht];if(i===T)return r;let a=au(s,i,void 0,e,n);a&&(r=y(new Eo(e,a,i,n)))}}else r=S(r,t=>{if(t!==T){let r=au(s,t,void 0,e,n);if(r)return y(new Eo(e,r,t,n))}return v(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[Ht],o=t(a,r)):o=Xt(o,e=>{let n=t(e,r);return n===mo?fo(e):n})}if(o._tag===`Success`){let e=o[Ht],t=p(e,r);return t===mo?o:t}return o=Su(e,n,r,o),Xt(o,e=>{let t=p(e,r);return t===mo?fo(e):t})}:p}var Du=Symbol(),Ou=new WeakMap,ku=e=>Nu(e).parser,Au=e=>Nu(e).makeEffect,ju=e=>Tu(e,Au),Mu=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=Eu(this.ast,ku)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=Eu(this.ast,Au,ju)}};function Nu(e){let t=Ou.get(e);if(t!==void 0)return t;let n=new Mu(e);return Ou.set(e,n),n}function Pu(e){let t=e.ast,n;return(e,r)=>(n??=Zu(id,Ll(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Fu(e){let t=Pu(e);return(e,n)=>{let r=Mn(t(e,n));return qi(r)?Qn(r.value):(Jo(r.cause,`Option adapter can only return none for schema issues`),mn())}}function Iu(e){return nd(Ll(e.ast))}function Lu(e){return zu(e.ast)}function Ru(e){{let t=Qu(Yu(e));return e=>{let n=t(e,Ws);return qi(n)?!0:(Jo(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function zu(e){let t=Ll(e),n=e=>(n=Ru(t),n(e));return e=>n(e)}function Bu(e,t){let n=Yu(e.ast);return t===void 0?n:(e,r)=>n(e,qu(t,r))}function Vu(e,t){return Qu(Bu(e,t))}function Hu(e,t){return $u(Bu(e,t))}function Uu(e,t){return ed(Bu(e,t))}function Wu(e,t){let n=Yu(Bl(e.ast));return t===void 0?n:(e,r)=>n(e,qu(t,r))}function Gu(e,t){return Qu(Wu(e,t))}function Ku(e,t){return ed(Wu(e,t))}var qu=(e,t)=>t?{...e,...t}:e,Ju=e=>e===T?y(new Oo):v(e);function Yu(e){return Zu(rd,e)}function Xu(e,t){return e===mo?v(t):Ue(e)?e[Ht]===T?Ju(T):e:Xt(e,Ju)}function Zu(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Ws);return a===mo?v(r):Ue(a)?a[Ht]===T?Ju(T):a:Xt(a,Ju)}}function Qu(e){return(t,n)=>Mn(e(t,n))}function $u(e){let t=Qu(e);return(e,n)=>{let r=t(e,n);return qi(r)?Qn(r.value):(Jo(r.cause,`Option adapter can only return none for schema issues`),mn())}}function ed(e){let t=Qu(e);return(e,n)=>{let r=t(e,n);return qi(r)?xe(r.value):Ze(Jo(r.cause,`Result adapter can only return schema issues`))}}function td(e,t){let n=Mn(e);if(qi(n))return n.value;let r=Jo(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function nd(e){let t,n;return(r,i)=>{t??=Nu(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Ws,o=t.make;if(o!==void 0&&r!==T){let e;try{e=o(r,a)}catch(e){throw Jo(Mi(e),`Constructor adapter can only throw schema issues`),e}if(e!==Du&&e!==T)return e}return td(Xu((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var rd=e=>Nu(e).parser,id=e=>Nu(e).makeEffect,ad=`~effect/Schema/Schema`,od=Symbol(),sd={[ad]:ad,get make(){let e=Iu(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=Pu(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Fu(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return ce(this,arguments)},annotate(e){return this.rebuild(fl(this.ast,e))},annotateKey(e){return this.rebuild(Sl(this.ast,e))},check(...e){return this.rebuild(ml(this.ast,e))},rebuild(e){return cd(e,this[od])}};function cd(e,t){function n(){}let r=Object.setPrototypeOf(n,sd);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[od]=t,r.ast=e,r}function ld(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ud(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function dd(e){return encodeURI(ld(e)).replace(/#/g,`%23`)}function fd(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 pd(e){let t=fd(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(ud)}function md(e){return e.reduce((e,t)=>`${e}/${dd(t)}`,`#`)}var hd=`http://json-schema.org/draft-07/schema#`;function gd(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function _d(e){return{dialect:`draft-07`,...kd(e,Vd)}}function vd(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!jr(e))return e;let a=r||!i&&Od(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=xd(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 yd(e,t){return vd(e,e=>{bd(e,t)})}function bd(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 xd(e,t){if(!jr(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function Sd(e,t,n){let r=new Map,i=[],a=Cd;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=Td(jr(e)?u(e):void 0,Cd)??Cd),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=wd(t,n);if(a!==void 0){let e=pd(a.hash);if(a.hash=``,e!==void 0){let n=r.get(Dd(a.href,e));n!==void 0&&(i=Ed(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(!jr(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&Od(c)){let e=Td(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 jr(e)?xd(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(Dd(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var Cd=`https://effect.invalid/.json-schema/`;function wd(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function Td(e,t){if(typeof e!=`string`)return;let n=wd(e,t);if(n!==void 0)return n.hash=``,n.href}function Ed(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${md(t)}`}function Dd(e,t){return`${e}\u0000${JSON.stringify(t)}`}function Od(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function kd(e,t,n){return Sd(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:xd(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var Ad=new Set([`properties`,`patternProperties`]),jd=new Set([`allOf`,`anyOf`,`oneOf`]),Md=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function Nd(e,t,n,r,i,a=Ad){let o;if(a.has(t))o=r.schemaMap(n,t);else if(jd.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 Pd=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Pd],[...Pd];var Fd=/^[A-Za-z_][-A-Za-z0-9._]*$/,Id=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Ld(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Rd(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Ld(i,n,`it is not active in ${r} but would become active in the target`)}var zd=[`additionalItems`,`definitions`,`dependencies`];function Bd(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,gd(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):gd(t,`https://json-schema.org/draft/2020-12/schema`)||Ld(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Vd(e,t){Rd(e,zd,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!Nd(n,o,s,t,Md))switch(o){case`$ref`:r=s;break;case`$schema`:Bd(n,s,t,hd,`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`:Ld(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(Hd(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Ld(`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 Wd(e,n,t,`draft-07`),Kd(e,n,`$id`,`Draft-07`),Ud(n,r,t),n}function Hd(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 Ud(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),Gd(e,r)}else n.reference(e,t)}}function Wd(e,t,n,r){let i=jr(e.dependentRequired)?e.dependentRequired:void 0,a=jr(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 Gd(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function Kd(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`||!Fd.test(a))&&Ld(`$anchor`,r,`the anchor is not valid`),Id.test(a)||Ld(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):Ld(`$anchor`,r,`it cannot be combined with the schema $id`)}function qd(e){return cd(Jd(e.ast),{schema:e})}var Jd=yl(e=>{let t=$d(e,Jd),n=e.context;return t===e||n===void 0?t:vl(t,Yd(n))});function Yd(e){return e.constructorDefault===void 0?e:new Gs(e.isOptional,e.isMutable,void 0,e.annotations)}function Xd(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Zd(e){return t=>{let n=[...t].sort((t,n)=>e(Rl(t))-e(Rl(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Qd=Zd(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function $d(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Kt(n))return ll(e,[hu]);let r=n(e.typeParameters.map(e=>cd(Rl(e))));return r===void 0?e:ll(e,[hl(r,t)])}case`Unknown`:return ll(e,[hu]);case`ObjectKeyword`:return ll(e,[gu]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Xd(e),e.recur(t,Gl);case`Union`:{let n=Qd(e.types);return n===e.types?e.recur(t):new Hc(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 ef=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function tf(e,t){return t.length>0&&(e+=`\n at ${d(t)}`),Error(e)}function nf(e){return`#/$defs/${dd(e)}`}var rf=new Set([...uo,to,...io]);function af(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;pu(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&pu(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(pu(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))rf.has(r)||!t.includeAnnotationKey(r)||pu(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function of(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=of(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 sf(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 cf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function lf(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function uf(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var df=`|title|description|default|examples|readOnly|writeOnly|`,ff=cf+df;function pf(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=sf(e);if(i!==void 0||a){let r=of(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:lf(r.schema,df)&&uf(o,s)?{...o,...r.schema}:pf(o,r.schema,n)}}if(n&&uf(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 mf(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>mf(e,t)))}function hf(e){return Array.isArray(e)}function gf(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=He(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!mf(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=>Pe(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=He(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 tf(`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 yd(e,e=>{let t=fd(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(ud(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,nf(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[to]: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=hf(s);c&&i.push(!1);let l=c?s[0]:s,u=af(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?cf:ff;return[d,e._tag===`Filter`&&lf(d,f)&&(u===void 0||lf(u,df))?!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=af(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:nf(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=af(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&_f(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=pf(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 tf(`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(yf).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw tf(`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=af(e.annotations,r);return s===void 0?o:p(pf(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 tf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=af(s.annotations,r);h(a,c,u===void 0?l:p(pf(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);Pe(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(pf(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=vf(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 tf(`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 mf(n)&&r.type===`string`&&typeof r.pattern==`string`&&lf(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(yf).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 tf(`Invalid schema representation document`,t)}}}function _f(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function vf(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 yf(e){switch(e._tag){case`Literal`:return ef(globalThis.String(e.literal));case`String`:return Kl;case`Number`:return gc;case`TemplateLiteral`:return e.parts.map(yf).join(``);case`Union`:return`(?:${e.types.map(yf).join(`|`)})`;default:throw tf(`Invalid schema representation document`,[])}}function bf(e,t){let n=gf([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var xf=({identifier:e})=>e;function Sf(e){return e===void 0?void 0:{annotations:e}}function Cf(e,t){let{references:n,representations:r}=wf([e],t);return{representation:r[0],references:n}}function wf(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??xf;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:He(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:fl(e,{identifier:n}):oo(e)===r?e:fl(e,{[to]: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=dl(e),n=cl(t),r=ao(t),i=r===void 0?(t===e?void 0:ao(e))??oo(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(Ll(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,...Sf(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...Sf(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...Sf(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...Sf(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...Sf(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=dl(e),n=t.context?.annotations;return{isOptional:Ml(t),type:m(e),...Sf(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...Sf(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=dl(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Ml(t),isMutable:Nl(t),...Sf(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...Sf(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...Sf(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...Sf(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:He(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(Ll(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function Tf(e){return qi(e)?e.value:{issues:[{message:zi(e.cause)}]}}function Ef(t,n){let r=Bu(t),i={errors:`all`,...n?.parseOptions},a=Lo(n),o=t=>{let n=new bn(`sync`),o=e(rt(r(t,i),{onFailure:a,onSuccess:e=>({value:e})}),{scheduler:n});o.currentDispatcher?.flush();let s=o.pollUnsafe();return s?Tf(s):new Promise(e=>{o.addObserver(t=>{e(Tf(t))})})};if(Object.hasOwn(t,`~standard`)){let e=t;return`validate`in e[`~standard`]||Object.assign(e[`~standard`],{validate:o}),e}return Object.assign(t,{"~standard":{version:1,vendor:`effect`,validate:o}})}function Df(e){return bf(Cf(Jd(e)))}function Of(e,t){let n=Df(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=_d(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function kf(e){let t={input(t){return Of(e.ast,t.target)},output(t){return Of(Ll(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 Af=ct(e=>jf(e));function jf(e){let t=Qa(e)?.toEquivalence;if(t)return t(As(e)?e.typeParameters.map(jf):[]);switch(e._tag){case`Never`:return ge();case`Declaration`:return Mf(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 Pe;case`Arrays`:{let t=e.elements.map(jf),n=e.rest.map(jf),[r,...i]=n,a=i.length;return Et((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 Pe;let t=e.propertySignatures.map(e=>jf(e.type)),n=e.indexSignatures.map(e=>jf(e.type));return Et((r,i)=>{if(!jr(r)||!jr(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(Ml(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=_c(r,a.parameter),s=_c(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=Ll(e).types,n=Vc(t),r=t.map((t,n)=>[zu(t),jf(e.types[n])]);return Et((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 Et((n,r)=>(t??=Af(e.thunk()))(n,r))}}}function Mf(e){let t=e.annotations?.representation;if(t===void 0)return Pe;switch(t.id){case`effect/schema/Option`:{let[t]=Nf(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=Nf(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]=Nf(e);return Pf(t,n)}case`effect/schema/Cause`:{let[t,n]=Nf(e);return Ff(t,n)}case`effect/schema/Exit`:{let[t,n,r]=Nf(e),i=Ff(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]=Nf(e);return pr(t,n)}case`effect/schema/ReadonlySet`:return Ae(Nf(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 Pe}}function Nf(e){return e.typeParameters.map(jf)}function Pf(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 Ff(e,t){let n=Se(Pf(e,t));return(e,t)=>n(e.reasons,t.reasons)}var If=C(2,(e,t)=>({...e,...t})),Lf=e=>e,Rf=`~effect/Schema/SchemaError`;function zf(e){return Xn(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var Bf=ad;function Vf(){return(e,t,n)=>D(new Js(e.map(Ac),e=>t(e.map(e=>D(e))),n))}function Hf(e,t){return Vf()([],()=>(t,n,r)=>e(t)?v(t):y(new Do(n,t,r)),t)}var Uf=class extends Di(`SchemaError`){[Rf]=Rf;constructor(e){let t=Qe();pe(0);try{super({issue:e})}finally{pe(t)}}get message(){return Wo(this.issue)}toString(){return`SchemaError(${this.message})`}};function Wf(e){return zf(e)}function Gf(e){return Ue(e)?Kf(e):kr(e,e=>Pr(()=>Pi(e,e=>new Uf(e))))}function Kf(e){return qi(e)?e:Ui(Pi(e.cause,e=>new Uf(e)))}function qf(e,t){let n;for(let r of e.reasons){if(!Ai(r)||!Wf(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 Jf(e){let t=Mn(e);if(qi(t))return t.value;throw qf(t.cause,`Sync adapter can only throw schema errors`)}function Yf(e,t){return Ef(e,t)}function Xf(e){return kf(e)}var Zf=Lu;function Qf(e,t){let n=Bu(e,t);return(e,t)=>Gf(n(e,t))}function $f(e,t){let n=Vu(e,t);return(e,t)=>Kf(n(e,t))}var ep=Hu;function E(e,t){let n=Uu(e,t);return(e,t)=>u(n(e,t),e=>new Uf(e))}var tp=E;function np(e,t){let n=Qf(e,t);return(e,t)=>Jf(n(e,t))}var rp=np;function ip(e,t){let n=Wu(e,t);return(e,t)=>Gf(n(e,t))}function ap(e,t){let n=Gu(e,t);return(e,t)=>Kf(n(e,t))}function op(e,t){let n=Ku(e,t);return(e,t)=>u(n(e,t),e=>new Uf(e))}var sp=op;function cp(e,t){let n=ip(e,t);return(e,t)=>Jf(n(e,t))}var lp=cp,D=cd;function up(e){return Xn(e,Bf)&&e[Bf]===Bf}var O=Lf(e=>D(Cl(e.ast),{schema:e})),k=Lf(e=>{let t=kp(e);return D(Tl(e.ast),{schema:t})}),dp=Lf(e=>D(El(e.ast),{schema:e})),fp=Lf(e=>D(Ll(e.ast),{schema:e})),pp=Lf(e=>D(Rl(e.ast),{schema:e}));function A(e){let t=D(new tc(e),{literal:e,transform(n){return t.pipe(Np(A(n),{decode:ts(()=>n),encode:ts(()=>e)}))}});return t}var mp=D($s),hp=D(ec),gp=D(Ys),_p=D(Qs),j=D(rc),M=D(oc),vp=D(sc),yp=D(cc),bp=D(lc);function xp(e,t){return D(e,{fields:t,mapFields(e,t){let n=e(this.fields);return xp(kc(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function N(e){return xp(kc(e,void 0),e)}function Sp(e,t){return D(jl(e.ast,t.ast),{key:e,value:t})}function Cp(e,t){return D(e,{elements:t,mapElements(e,t){let n=e(this.elements);return Cp(jc(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function wp(e){return Cp(jc(e),e)}var Tp=Lf(e=>D(new uc(!1,[],[e.ast]),{value:e})),Ep=Lf(e=>D(new uc(!1,[e.ast],[e.ast]),{value:e})),Dp=Lf(e=>D(Nc(e.ast),{schema:e}));function Op(e,t){return D(e,{members:t,mapMembers(e,t){let n=e(this.members);return Op(Mc(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e,t){return Op(Mc(e,t,void 0),e)}function F(e){let t=e.map(A);return D(Mc(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return P(e(this.members))},pick(e){return F(e)},transform(e){return P(t.map((t,n)=>t.transform(e[n])))}})}var I=Lf(e=>P([e,gp])),kp=Lf(e=>P([e,_p]));function Ap(e){return D(new Zc(()=>e().ast))}function L(...e){return t=>t.check(...e)}function jp(e,t){return n=>D(ml(n.ast,[tl(e,t)]),{schema:n})}function Mp(e){return t=>D(t.ast,{schema:t,identifier:e})}function Np(e,t){return n=>D(kl(n.ast,e.ast,t?bs(t):Cs()),{from:n,to:e})}function Pp(e,t){return n=>t?Np(n,t)(e):Np(n)(e)}function Fp(e){return t=>D(Ol(t.ast,e),{schema:t})}function Ip(e){return kr(e,e=>Pr(()=>Pi(e,e=>e.issue)))}function Lp(e,t){let n=t?.encodingStrategy===`omit`?as():$o();return t=>k(pp(t)).pipe(Np(t,{decode:os(Ip(e)),encode:n}))}function Rp(e,t){return n=>fp(n).pipe(Lp(e,t),Pp(k(n)))}function zp(e){return A(e).pipe(Fp(v(e)))}function Bp(e,t){return Hf(t=>t instanceof e,t)}function Vp(){return(e,t)=>new Us(e.ast,bs(t))}var R=el,Hp=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Up(e){let t=new globalThis.RegExp(Hp);return R(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:Hp,flags:``}]},...e})}function Wp(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${_(n)})`:`new RegExp(${_(n)}, ${_(r)})`;return al(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var Gp=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 Kp(e,t){let n=Gp(e);return Wp(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 qp(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Wp(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Jp(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 Yp(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${ef(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return R(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>Jp(i,e,`^${ef(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Xp(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${ef(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return R(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>Jp(i,e,`${ef(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Zp(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(ef(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return R(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>Jp(i,e,ef(i)),toCode:()=>({runtime:`Schema.isIncluding(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Qp=D(rl),$p=nl;function em(e){let t=rn(e.order),n=e.formatter??_;return(r,i)=>R(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function tm(e){let t=Un(e.order),n=e.formatter??_;return(r,i)=>R(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 nm(e){let t=Nr(e.order),n=e.formatter??_;return(r,i)=>R(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function rm(e){let t=ln(e.order),n=e.formatter??_;return(r,i)=>R(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 im(e){let t=Un(e.order),n=rn(e.order),r=ln(e.order),i=Nr(e.order),a=e.formatter??_;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return R(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 am(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${_(e)}`);return e}var om=em({order:ir,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:am(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${_(e)})`})})}),sm=tm({order:ir,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:am(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${_(e)})`})})}),cm=nm({order:ir,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:am(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${_(e)})`})})}),lm=rm({order:ir,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:am(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${_(e)})`})})}),um=im({order:ir,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:am(e.minimum),maximum:am(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${_(e.minimum)}, maximum: ${_(e.maximum)}, exclusiveMinimum: ${_(t)}, exclusiveMaximum: ${_(n)} })`})}}});function dm(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),R(t=>ba(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(${_(e)})`}),...t})}function fm(e){return R(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 z=M.check(fm()),pm=z.check(sm(0));function mm(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${_(e)}`);return e.toISOString()}function hm(e){return`new Date(${_(e.getTime())})`}var gm=em({order:Jt,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:mm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${hm(e)})`})})}),_m=tm({order:Jt,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:mm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${hm(e)})`})})}),vm=nm({order:Jt,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:mm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${hm(e)})`})})}),ym=rm({order:Jt,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:mm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${hm(e)})`})})}),bm=im({order:Jt,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:mm(e.minimum),maximum:mm(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${hm(e.minimum)}, maximum: ${hm(e.maximum)}, exclusiveMinimum: ${_(t)}, exclusiveMaximum: ${_(n)} })`})}}}),xm=em({order:jn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${_(e)})`})})}),Sm=tm({order:jn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${_(e)})`})})}),Cm=nm({order:jn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${_(e)})`})})}),wm=rm({order:jn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${_(e)})`})})}),Tm=im({order:jn,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: ${_(e.minimum)}, maximum: ${_(e.maximum)}, exclusiveMinimum: ${_(t)}, exclusiveMaximum: ${_(n)} })`})}}});function Em(e,t){return e=Pm(e),Dm(e,Math.ceil(e/2),t)}function Dm(e,t,n){return R(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})`}),[eo]:!0,arbitraryConstraint:{minLength:e},...n})}function Om(e){return Dm(1,1,e)}function B(e,t){return e=Pm(e),R(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})`}),[eo]:!0,arbitraryConstraint:{maxLength:e},...t})}function km(e,t,n){return e=Pm(e),t=Pm(t),R(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})`}),[eo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function Am(e,t){return e=Pm(e),R(t=>Nm(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 jm(e,t){return e=Pm(e),R(t=>Nm(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 Mm(e,t,n){return e=Pm(e),t=Pm(t),R(n=>{let r=Nm(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 Nm(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function Pm(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Fm(e,t){return e=Pm(e),R(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})`}),[eo]:!0,arbitraryConstraint:{minSize:e},...t})}function Im(e,t){return e=Pm(e),R(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})`}),[eo]:!0,arbitraryConstraint:{maxSize:e},...t})}function Lm(e,t,n){return e=Pm(e),t=Pm(t),R(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})`}),[eo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function Rm(e,t){return e=Pm(e),R(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})`}),[eo]:!0,arbitraryConstraint:{minProperties:e},...t})}function zm(e,t){return e=Pm(e),R(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})`}),[eo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function Bm(e,t,n){return e=Pm(e),t=Pm(t),R(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})`}),[eo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var Vm=j.check(Om());globalThis.RegExp,globalThis.URL;var Hm=j.annotate({expected:`a string that will be decoded as a Date`}),Um=Hf(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:()=>Vp()(Hm,Es)}),Wm=j.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function Gm(e,t){return Wm.pipe(Np(e,Os(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var Km=j.annotate({expected:`a string that will be decoded as a number`}).pipe(Np(M,ws)),qm=j.check(Up()),Jm=j.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(Np(qm,xs())),Ym=j.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),Xm=Bp(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>Vp()(Ym,Ds)});function Zm(e){return Af(e.ast)}function Qm(e,t){return Cf(e.ast,t)}var $m=qd,eh=D(fl(mu,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),th=Sp(j,eh),nh=e=>crypto.getRandomValues(new Uint8Array(e)),rh=(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}}},ih=(e,t=21)=>rh(e,t|0,nh),ah=`abcdefghijklmnopqrstuvwxyz0123456789`;function oh(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return ih(ah,e)()}var sh=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ch=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,lh=b().min(1).max(64).regex(sh),uh=b().min(1).max(64).regex(sh),dh=b().min(1).max(32).regex(ch),fh=gr({prefix:dh}),ph=gr({family:lh,version:t(1),kinds:Gt(uh,fh)}).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)}}),mh=b(),hh=/^[a-z0-9]+$/,gh=new TextEncoder;function _h(e){return e===32||e>=9&&e<=13}function vh(e){let t=0,n=e.length;for(;t<n&&_h(e.charCodeAt(t));)t+=1;for(;n>t&&_h(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function yh(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&hh.test(n)}let r=g(()=>Mt(e=>{let t=mh.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=gh.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(vh(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=g(()=>mh.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),ye)}));function o(){let n;try{n=oh(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 bh=Gt(b(),gr({family:b(),kind:b(),version:t(1),generate:xt(),schema:be(it),parse:xt(),is:xt()})),xh=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},Sh=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 Ch(e){let t;try{t=ph.safeParse(e)}catch{throw new xh}if(!t.success)throw new xh;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=yh({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new Sh({family:n.family,kind:t})})}let i=Mt(e=>{let t=bh.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 xh;return i.data}var wh=Symbol.for(`effect/MutableList/Empty`),Th=()=>({head:void 0,tail:void 0,length:0}),Eh=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})},Dh=()=>({array:[],mutable:!0,offset:0,next:void 0}),Oh=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=Dh(),e.tail=e.tail.next):e.head=e.tail=Dh(),e.tail.array.push(t),e.length++},kh=e=>{e.head=e.tail=void 0,e.length=0},Ah=(e,t)=>{if(t=oi(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 kh(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?kh(e):Eh(e),n;i=i.next}return kh(e),n},jh=e=>{if(!e.head)return wh;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:kh(e):Eh(e),t},Mh=`~effect/Queue`,Nh=`~effect/Queue/Enqueue`,Ph=`~effect/Queue/Dequeue`,Fh={_A:Wr,_E:Wr},Ih={[Mh]:Fh,[Nh]:Fh,[Ph]:Fh,...En,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:Zh(this)}}},Lh=e=>Pn(t=>{let n=Object.create(Ih);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=Th(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},Mr(n)}),Rh=e=>Lh({capacity:e}),zh=C(2,(e,t)=>vn(()=>Bh(e,t)?$h:e.state._tag===`Open`&&e.strategy===`suspend`?cg(e,t):Qh)),Bh=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(jh(e.messages),Oh(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(Oh(e.messages,t),ng(e),!0):(Oh(e.messages,t),rg(e),!0):!1,Vh=C(2,(e,t)=>Hh(e,Jr(t))),Hh=C(2,(e,t)=>cr(()=>Uh(e,t))),Uh=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=mt(t),r=Qr(n,eg);return e.state.offers.size===0&&e.messages.length===0?(pg(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},rg(e),!0)},Wh=e=>Uh(e,Jr(lr())),Gh=e=>cr(()=>Kh(e)),Kh=e=>{if(e.state._tag===`Done`)return!1;kh(e.messages);let t=e.state.offers;pg(e,e.state._tag===`Open`?tg:e.state.exit);for(let e of t)ug(e);return!0},qh=e=>Jh(e,1,1/0),Jh=C(3,(e,t,n)=>(t=oi(t),n=oi(n),ag(()=>ig(e,t,n)??ne(sg(e,()=>og(e,t)),Jh(e,t,n))))),Yh=e=>ag(()=>Xh(e)??ne(sg(e,()=>og(e,1)),Yh(e))),Xh=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=jh(e.messages);return fg(e),ue(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=dg(e.state.offers);return fg(e),ue(t)}},Zh=e=>e.state._tag===`Done`?0:e.messages.length,Qh=ue(!1),$h=ue(!0),eg=Vr(lr()),tg=$e(),ng=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(ot),e.messages.length===0))break}},rg=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,ng(e)},0))},ig=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return ue([]);if(!og(e,t))return;let r=e.messages.length>0?Ah(e.messages,n):[dg(e.state.offers)];return fg(e),ue(r)},ag=o({op:`QueueTake`,[ut](e){let t=this[Ht]();return Je(t)?t[ut](e):t}}),og=(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,sg=(e,t)=>ht(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(ot);let r={ready:t,resume:n};return e.state.takers.add(r),cr(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),cg=(e,t)=>ht(n=>Bh(e,t)?n($h):lg(e,{_tag:`Single`,message:t,resume:n})),lg=(e,t)=>{if(e.state._tag!==`Open`)return ug(t);let n=e.state.offers;return n.add(t),cr(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&pg(e,e.state.exit))})},ug=e=>e._tag===`Single`?e.resume(Qh):e.resume(ue(e.remaining.slice(e.offset))),dg=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume($h),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(ue([]))),n},fg=e=>{if(e.state._tag===`Done`)return wa(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(pg(e,e.state.exit),wa(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`)Oh(e.messages,t.message),e.state.offers.delete(t),t.resume($h);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;Oh(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(ue([]))}let r=e.state;if(r._tag===`Done`)return wa(r.exit.cause)}return!1},pg=(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()},mg=f,hg=Ce,gg=Ct,_g=yt,vg=r,yg=nt,bg=e=>new Sg(e),xg=(e,t,n)=>ht(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),cr(()=>{e.waiters.delete(i)})}),Sg=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=vn(()=>this.free<e?xg(this,e,t):(this.taken+=e,Mr(e)));return t}takeIfAvailable(e){return vn(()=>this.free<e?Mr(!1):(this.taken+=e,Mr(!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 Pn(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),Tn))}release(e){return Pn(t=>Mr(this.releaseUnsafe(t,e)))}get releaseAll(){return Pn(e=>Mr(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>qn(n=>{let r=vn(()=>{if(this.free<e){let t=xg(this,e,Tn);return mr(n(t),()=>r)}return this.taken+=e,pn(n(t),()=>{this.releaseUnsafe(je(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>qn(n=>this.free<e?cn:(this.taken+=e,pn(n(Hr(t)),()=>{this.releaseUnsafe(je(),e)},!0)))}},Cg=e=>cr(()=>new Sg(e)),wg=`~effect/Channel`,Tg=e=>Xn(e,wg),Eg={[wg]:{_Env:Wr,_InErr:Wr,_InElem:Wr,_OutErr:Wr,_OutElem:Wr},pipe(){return ce(this,arguments)}},Dg=e=>{let t=Object.create(Eg);return t.transform=(t,n)=>kr(e(t,n),e=>v(Bt(e))),t},Og=(e,t)=>Dg((n,r)=>S(jg(e)(n,r),e=>t(e,r))),kg=e=>Dg((t,n)=>e),Ag=e=>Dg(st(function*(t,n){let r=fa(n),i=e=>pa(r,Oa(e)),a=yield*gt(e(t,n,r),i);return gt(a,i)})),jg=e=>e.transform,Mg=(e,t,n)=>Lh({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(un(t=>da(e,Gh(t))),un(n=>la(t(n),e).pipe(kr(e=>Hh(n,e)),qe(e)))),Ng=(e,t)=>Dg((n,r)=>Xe(Mg(r,e,t),qh)),Pg=e=>Dg((t,n)=>Wn(()=>jg(e())(t,n))),Fg=e=>kg(x(()=>{let t=e();return Wn(()=>{let e=t.next();return e.done?Vi(e.value):v(e.value)})})),Ig=e=>zg(v(e)),Lg=kg(v(Vi())),Rg=e=>kg(Bt(e)),zg=e=>kg(x(()=>{let t=!1;return Wn(()=>t?Vi():(t=!0,e))})),Bg=C(2,(e,t)=>Og(e,e=>x(()=>{let n=0;return Xe(e,e=>t(e,n++))}))),Vg=e=>e===void 0||e!==`unbounded`&&e<=1,Hg=C(e=>Tg(e[0]),(e,t,n)=>Vg(n?.concurrency)?Ug(e,t):Wg(e,t,n)),Ug=(e,t)=>Dg((n,r)=>{let i=0;return Xe(jg(e)(n,r),S(e=>t(e,i++)))}),Wg=(e,t,n)=>Ag(st(function*(r,i,a){let o=0,s=yield*jg(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Rh(0);yield*da(a,Gh(l));let u=hn(yield*gn()),d=_g(a);if(n.unordered){let e=bg(c),n=Fr(e.release(1)),r=Yr({onFailure:e=>S(Hh(l,e),n),onSuccess:e=>S(zh(l,e),n)});yield*e.take(1).pipe(S(()=>s),S(e=>{let n=o++;return d(u(r(Wn(()=>t(e,n))))),w}),dt({disableYield:!0}),kr(t=>e.withPermits(c-1)(Hh(l,t))),qe(a))}else{let e=yield*Rh(c-2);yield*da(a,Gh(e)),yield*Yh(e).pipe(Ur,S(e=>zh(l,e)),dt({disableYield:!0}),kr(e=>Hh(l,e)),qe(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,Uh(l,e.cause))};yield*s.pipe(S(i=>{if(n)return Bt(n);let a=o++,s=u(Wn(()=>t(i,a)));return d(s),s.addObserver(r),zh(e,hg(s))}),dt({disableYield:!0}),kr(t=>zh(e,Ui(t)).pipe(Wt(Hh(e,t)))),qe(a))}return Yh(l)})),Gg=C(e=>Tg(e[0]),(e,t,n)=>Vg(n?.concurrency)?Kg(e,t):qg(e,t,n)),Kg=(e,t)=>Dg((n,r)=>Xe(jg(e)(n,r),e=>{let i,a,o=S(e,e=>(a??=fa(r),Xt(jg(t(e))(n,a),e=>(i=s(e),i)))),s=Ca(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=pa(a,Ki);return a=void 0,S(t,()=>o)});return Wn(()=>i??o)})),qg=(e,t,n)=>e.pipe(Bg(t),$g(n)),Jg=e=>Gg(e,Wr),Yg=e=>Og(e,e=>{let t,n=0,r=Wn(function r(){if(t===void 0)return S(e,e=>{switch(e.length){case 0:return r();case 1:return v(e[0]);default:return t=e,v(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),v(i)});return v(r)}),Xg=C(2,(e,t)=>Dg((n,r)=>{let i=fa(r);return Xe(jg(e)(n,i),e=>{let a=e.pipe(kr(e=>{if(wa(e))return Bt(e);let o=i;return i=fa(r),pa(o,Ui(e)).pipe(Wt(jg(t(e))(n,i)),S(e=>(a=e,e)))}));return Wn(()=>a)})})),Zg=C(3,(e,t,n)=>Xg(e,e=>{let r=t(e);return Re(r)?Rg(r.failure):n(r.success,e)})),Qg=C(2,(e,t)=>Zg(e,Ii,e=>t(e))),$g=C(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>Ag(st(function*(a,o,s){let c=n===`unbounded`?2**53-1:Math.max(1,n),l=r?void 0:bg(c),u=yield*yg(!0),d=new Set,f=yield*Rh(t);yield*da(s,Gh(f));let p=yield*jg(e)(a,o);return yield*i(function*(){for(;;){let e;l&&(d.size<c?yield*l.take(1):(e=yield*se(p),yield*It(l.take(1),Wt(hg(e),ve))));let t=e===void 0?yield*p:yield*hg(e),n=fa(s),r=yield*jg(t)(a,n);for(;d.size>=c;){let e=si(d);d.delete(e),d.size===0&&(yield*u.open),yield*gg(e)}let i=yield*r.pipe(un(()=>qr),S(e=>zh(f,e)),dt({disableYield:!0}),gt(st(function*(e){let t=Oa(e),r=yield*Cn(pa(n,t));if(!d.has(i))return;let a=Xi([t,r]);Ji(a)&&(yield*Hh(f,a.cause)),d.delete(i),l&&(yield*l.release(1)),d.size===0&&(yield*u.open)})),se);u.closeUnsafe(),d.add(i)}}).pipe(kr(e=>{let t=Ea(e);return at(t)?u.whenOpen(Hh(f,e)):Hh(f,e)}),qe(s)),Yh(f)}))),e_=C(e=>Tg(e[0])&&Tg(e[1]),(e,t,n)=>Ag(st(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Rh(0);yield*da(a,Gh(s));let c=0;function l(e,t){if(c++,!wa(t))return Hh(s,t);switch(o){case`both`:return c===2?Hh(s,t):w;case`left`:case`right`:return e===o?Hh(s,t):w;case`either`:return Hh(s,t)}}let u=(e,t,n)=>jg(t)(r,n).pipe(S(e=>e.pipe(S(e=>zh(s,e)),dt)),gt(t=>he(Oa(t),e=>pa(n,e)).pipe(Yr({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),qe(a));return yield*u(`left`,e,fa(a)),yield*u(`right`,t,fa(a)),Yh(s)}))),t_=e=>Dg((t,n)=>{let r;return v(Wn(()=>r||e.pipe(la(n),S(e=>jg(e)(t,n)),S(e=>r=e))))}),n_=C(2,(e,t)=>e_(e,kg(v(S(t,Vi))),{haltStrategy:`either`})),r_=C(2,(e,t)=>Ag((n,r,i)=>ua(i,t).pipe(Wt(jg(e)(n,r))))),i_=C(2,(e,t)=>r_(e,e=>t)),a_=(e,t,n)=>Wn(()=>{let r=ca(),i=jg(e)(Vi(),r);return Ca(S(i,t),n||v).pipe(wt(e=>pa(r,e)))}),o_=C(2,(e,t)=>a_(e,e=>dt(S(e,t),{disableYield:!0}))),s_=st(function*(e){let t=bg(1),n=yield*gn(),r=pt(n,oa);return(yield*jg(e)(Vi(),r)).pipe(jt(n),t.withPermits(1))},kr(e=>v(Bt(e)))),c_=(e,t)=>jg(e)(Vi(),t),l_=`~effect/Stream`,u_={_R:Wr,_E:Wr,_A:Wr},d_=function(e){this.channel=e};d_.prototype={[l_]:u_,pipe(){return ce(this,arguments)}};var f_=e=>new d_(e),p_=`~effect/Stream`,m_=e=>Xn(e,p_),h_=f_,g_=e=>h_(zg(Xe(e,Ge))),__=e=>h_(kg(e)),v_=e=>e.channel,y_=(e,t)=>h_(Ng(e,t)),b_=h_(Lg),x_=e=>h_(Ig(Ge(e))),S_=e=>h_(Pg(()=>e().channel)),C_=e=>h_(Rg(e)),w_=e=>a(e)?h_(Ig(e)):b_,T_=(e,t)=>__(x(()=>{let n=e,r=!1;return Wn(function e(){return r?Vi():S(t(n),([t,i])=>(ke(i)?r=!0:n=i.value,a(t)?v(t):e()))})})),E_=e=>h_(t_(Xe(e,v_))),D_=C(2,(e,t)=>S_(()=>{let n=0;return h_(Bg(e.channel,He(e=>t(e,n++))))})),O_=C(e=>m_(e[0]),(e,t,n)=>e.channel.pipe(Yg,Hg(t,n),Bg(Ge),h_)),k_=e=>e.pipe(D_(xe),F_(e=>x_(Ze(e)))),A_=C(2,(e,t)=>{let n=h_(Jg(Fg(()=>M_(e,t))));return j_.set(n,[e,t]),n}),j_=new WeakMap;function*M_(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=j_.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var N_=C(2,st(function*(e,t){let n,r=yield*s_(e.channel),i=kr(r,e=>(n=e,Bt(e))),[a,o]=yield*ar(e=>t.transform(i,e)),s=n?b_:__(v(r));return o&&(s=A_(w_(o),s)),[a,s]})),P_=C(2,(e,t)=>e.channel.pipe(Xg(e=>t(e).channel),h_)),F_=C(2,(e,t)=>h_(Qg(e.channel,e=>t(e).channel))),I_=C(2,(e,t)=>h_(n_(e.channel,t))),L_=C(2,(e,t)=>h_(i_(e.channel,t))),R_=C(2,(e,t)=>o_(e.channel,e=>{let n=0;return Qt({while:()=>n<e.length,body:()=>t(e[n++]),step:Vt})})),z_=C(2,(e,t)=>({[Symbol.asyncIterator](){let n=$n(t),r=hn(t),i=ca(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(yr(Wt(t?gg(t):w,pa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(We(`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??S(c_(e.channel,i),e=>(a=e,e)));s=t;let d=await n(mg(t));if(s===t&&(s=void 0),qi(d))return o=d.value[Symbol.iterator](),o.next();if(wa(d.cause))return l(Ki);if(c&&Ni(d.cause))return c;throw await u(d),Fi(d.cause)},return(){return l(Ki)},async throw(e){throw await u(Gi(e)),e}}}})),B_=e=>z_(e,Br()),V_=Vm.check(B(256)),H_=z.check(sm(0)),U_=N({id:V_,kind:Vm.check(B(64)),summary:Vm.check(B(200)),since:H_,expiresAt:k(H_)}),W_=U_.mapFields(e=>({...e,extensionId:V_})),G_=4096,K_=Tp(W_).check(B(64)),q_=j.pipe(L(Em(1)),L(B(256))),J_=N({providerId:q_,modelId:q_,reasoning:k(F([`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]))}),Y_=np(I(J_)),X_=np(Gm(I(J_))),Z_=F([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),Q_=F([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`storage_pressure`,`context_too_large`]),$_=j.pipe(L(Em(1)),L(B(256))),ev=N({_tag:A(`ShiitakeError`),boundary:Z_,cause:Q_,message:j,requestId:O($_)}),V=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}},tv=new TextEncoder;function nv(e){return j.check(Em(1),B(e),R(t=>tv.encode(t).byteLength<=e))}var rv=nv(256),iv=nv(262144),av=N({type:A(`image`),data:j.check(Em(1),B(1048576),qp()),mimeType:j.check(R(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),ov=Tp(av).check(Em(1),B(8)),sv=F([`steer`,`followUp`]),cv=rv,lv=E(nv(512)),uv=N({requestId:rv}),dv=N({delivery:sv,requestId:rv,type:A(`prompt`),text:j.check(B(262144),R(e=>tv.encode(e).byteLength<=262144)),images:O(ov)}).check(R(e=>(e.text.length>0||(e.images?.length??0)>0)&&tv.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),fv=N({type:A(`abort`)}),pv=N({commandId:rv,onlyIfPending:k(vp),type:A(`cancel`)}),mv=N({type:A(`operator`),requestId:rv,author:F([`operator`,`party`]),text:iv}),hv=N({type:A(`branch`),entryId:rv}),gv=N({type:A(`fork`),entryId:rv}),_v=j.check(Em(1),B(4096)),vv=N({type:A(`compact`),requestId:rv,instructions:O(_v)}),yv=P([dv,vv]),bv=j.check(R(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),xv=P([dv,fv,pv,hv,gv,mv,vv,N({type:A(`title`),title:I(bv)})]),Sv=N({command:xv}),Cv=N({includeSandboxFailures:k(vp),limit:k(z.check(um({minimum:1,maximum:200}))),before:k(nv(512))}),wv=N({includeSandboxFailures:k(A(`true`)),limit:k(Km.check(fm(),um({minimum:1,maximum:200}))),before:k(nv(512))}),Tv=N({includeSandboxFailures:k(vp),after:k(j)}),Ev=N({includeSandboxFailures:k(A(`true`)),mode:k(A(`subscribe`)),after:k(j),limit:k(Km.check(fm(),um({minimum:1,maximum:200})))}),Dv={onExcessProperty:`error`},Ov=E(cv,Dv),kv=E(uv,Dv),Av=E(yv,Dv);E(rv);var jv=E(xv,Dv);E(Sv,Dv);var Mv=E(P([Cv,_p]),Dv);E(wv,Dv);var Nv=E(Tv,Dv);E(Ev,Dv);function Pv(e){let t=Ov(e);if(t._tag===`Failure`)throw new V(`contract`,`invalid`,`Session id is invalid`);return t.success}function Fv(e){let t=lv(e);if(t._tag===`Failure`)throw new V(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function Iv(e){let t=kv(e);if(t._tag===`Failure`)throw new V(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function Lv(e){let t=Mv(e);if(t._tag===`Failure`)throw new V(`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 Rv(e){let t=Nv(e);if(t._tag===`Failure`)throw new V(`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 zv(e,t){if(Re(e))throw new V(`contract`,`invalid`,t);return e.success}var Bv=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,Vv=1e3,Hv=221;function Uv(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Uv(r,t+1));return n}if(e===null)return t;let n=Gt(b(),Lt()).safeParse(e);if(!n.success)return t;let r=t;for(let e of Object.values(n.data))r=Math.max(r,Uv(e,t+1));return r}var Wv=g(()=>Gt(b(),Lt()).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`}),Uv(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Gv=g(()=>gr({query:b().max(200),maxResults:Yn().int().min(1).max(50).default(50)})),Kv=g(()=>gr({path:b().max(160),detail:l([`index`,`full`]).default(`full`),methods:Ne(b().max(80)).max(50).optional()})),qv=gr({cursor:b().max(400).optional(),limit:Yn().int().min(1).max(50).default(50),namespace:b().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),Jv=g(()=>gr({path:b().max(160),capabilityNotes:b().max(500).optional()})),Yv=gr({path:b().max(160),description:b().max(1e3).optional(),score:Yn().min(0).max(Hv),matchReason:b().max(500).optional(),sample:Wv.optional(),capabilityNotes:b().max(500).optional(),peers:Ne(Jv).max(1e3).optional()}),Xv=g(()=>gr({results:Ne(Yv).max(50),total:Yn().int().min(0).max(Vv),truncated:Oe(),topScore:Yn().min(0).max(Hv),margin:Yn().min(0).max(Hv),catalogStamp:b().length(16).regex(/^[0-9a-f]{16}$/)})),Zv=gr({results:Ne(Yv).max(50),total:Yn().int().min(0).max(Vv),nextCursor:b().max(400).nullable(),catalogStamp:b().length(16).regex(/^[0-9a-f]{16}$/)}),Qv=g(()=>gr({path:b().max(160),description:b().max(1e3).optional(),types:b().max(2e4),inputSchema:Lt().refine(e=>JSON.stringify(e).length<=2e4&&Uv(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:l([`module`,`operation`]),usage:b().max(300).optional()}));g(()=>gr({code:l([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:b().max(1e3)}));var $v=g(()=>gr({"~standard":gr({jsonSchema:gr({input:be(Function),output:be(Function)})})})),ey=g(()=>Mt(e=>$v.safeParse(e).success,`Expected a Standard JSON Schema`)),ty=g(()=>gr({path:b().min(3).max(160).regex(Bv),description:b().max(1e3).optional(),input:ey,output:ey.optional(),capabilityNotes:b().max(500).optional(),instructions:b().max(1e3).optional()})),ny=g(()=>gr({revision:b().min(1).max(160),operations:Ne(ty).max(Vv)})),H=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}}},ry=Lt(),iy=g(()=>Ar([b(),Yn(),Oe()]));function ay(e){return e!==null&&!Array.isArray(e)&&!iy.safeParse(e).success}function oy(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 sy(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 cy(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var ly=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function uy(e){return ly.has(e)}function dy(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(`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 fy(e){if(e===null)return`null`;let t=iy.safeParse(e);return t.success?JSON.stringify(t.data):Array.isArray(e)?`[${e.map(e=>fy(e)).join(`,`)}]`:ay(e)?`{${Object.entries(e).sort(([e],[t])=>oy(e,t)).map(([e,t])=>`${JSON.stringify(e)}:${fy(t)}`).join(`,`)}}`:`null`}function py(e){let t=14695981039346656037n,n=(1n<<64n)-1n;for(let r=0;r<e.length;r+=1)t^=BigInt(e.charCodeAt(r)),t=t*1099511628211n&n;return t.toString(16).padStart(16,`0`)}function my(e){return e.slice(e.indexOf(`.`)+1)}function hy(e){return e.slice(0,e.indexOf(`.`))}var gy=g(()=>Ar([Oe(),dn({$ref:b().optional(),$defs:Gt(b(),gy).optional(),definitions:Gt(b(),gy).optional(),const:on().optional(),enum:Ne(on()).optional(),oneOf:Ne(gy).optional(),anyOf:Ne(gy).optional(),allOf:Ne(gy).optional(),type:Ar([b(),Ne(b())]).optional(),properties:Gt(b(),gy).optional(),additionalProperties:gy.optional(),required:Ne(b()).optional(),prefixItems:Ne(gy).optional(),items:Ar([gy,Ne(gy)]).optional(),examples:Ne(on()).optional(),default:on().optional()})])),_y=new WeakMap;function vy(e,t){let n=_y.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=gy.parse(e[`~standard`].jsonSchema[t]({target:`draft-2020-12`}))}catch{throw new H(`invalid_input`,`Schema cannot be projected to JSON Schema`)}let a=ry.safeParse(i),o={node:i,json:a.success?a.data:void 0};return n===void 0&&(n={},_y.set(e,n)),n[t]=o,o}function yy(e,t){return vy(e,t).node}function by(e){return Array.isArray(e)}var xy=256,Sy=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function Cy(e,t,n){let r=Sy.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>xy)throw new H(`invalid_input`,`Schema references expand more than ${String(xy)} times; flatten its shared definitions`);return Ty(i,t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function wy(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=Sy.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&wy(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 Ty(e,t,n){if(e===void 0||e===!0||e===!1||t>12)return`unknown`;if(e.$ref)return Cy(e.$ref,t,n);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=>Ty(e,t+1,n)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>Ty(e,t+1,n)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let r=Ty(e,t+1,n);return wy(e,n)?`(${r})`:r}).join(` & `);if(e.type===`object`||e.properties){let r=Object.entries(e.properties??{}).sort(([e],[t])=>oy(e,t));if(r.length===0){let r=e.additionalProperties;return r===!1?`Record<string, never>`:r&&r!==!0?`Record<string, ${Ty(r,t+1,n)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
4
|
+
${r.map(([e,r])=>{let a=Ty(r,t+1,n),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 r=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>Ty(e,t+1,n));return r!==void 0&&r!==!0&&!by(r)&&i.push(`...${Ty(r,t+1,n)}[]`),`[${i.join(`, `)}]`}if(r!==void 0&&by(r))return`[${r.map(e=>Ty(e,t+1,n)).join(`, `)}][]`;let i=Ty(r,t+1,n);return`${r!==void 0&&r!==!0&&r!==!1&&(r.oneOf!==void 0||r.anyOf!==void 0||r.allOf!==void 0)?`(${i})`:i}[]`}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 Ey(e,t=`input`){let n=yy(e,t);return Ty(n,0,{definitions:n===!0||n===!1?{}:{...n.definitions,...n.$defs},expanding:new Set,budget:{expansions:0}})}function Dy(e){return e.replace(/[^A-Za-z0-9_$]/g,`_`)}function Oy(e,t,n){let r=`(input: ${t}) => Promise<${n}>`;for(let t of e.split(`.`).reverse())r=`{ [${JSON.stringify(t)}]: ${r} }`;return r}function ky(e){return e.length===0?``:`export declare const env: ${e.map(e=>e.indexEnvironment).join(` & `)};`}function Ay(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(` & `)};`}function jy(e){let t=Dy(e.path.replace(/\./g,`$`)),n=Ey(e.input,`input`),r=e.output?Ey(e.output,`output`):`unknown`;return Object.freeze({indexEnvironment:Oy(e.path,n,r),environment:Oy(e.path,`${t}_Input`,`${t}_Output`),types:`export type ${t}_Input = ${n};\nexport type ${t}_Output = ${r};`})}function My(e){let t=yy(e,`input`);if(t===!0||t===!1||!t.properties)return;let n=t.properties,r={},i=!1,a=Object.entries(n).sort(([e],[t])=>oy(e,t));for(let[e,t]of a){if(t===!0||t===!1)continue;let n=t,a=n.examples;if(a&&a.length>0){let t=ry.safeParse(a[0]);t.success&&(r[e]=t.data,i=!0)}else if(n.default!==void 0){let t=ry.safeParse(n.default);t.success&&(r[e]=t.data,i=!0)}}return i?r:void 0}function Ny(e){let t=vy(e,`input`).json;if(t===void 0)throw new H(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t}function Py(e,t=`input`){let n=vy(e,t);return n.fingerprint??=fy(n.json??null),n.fingerprint}function Fy(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Fy(r,t+1));return n}if(!ay(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Fy(r,t+1));return n}function Iy(e,t){let n=vy(e,t);return n.size??={bytes:Ly(e,t,n.json)},n.size.bytes}function Ly(e,t,n){if(!n)return;let r=JSON.stringify(n);if(r.length>2e4||Fy(n,0)>16)return;if(t===`output`)return r.length;let i=My(e);if(!i)return r.length;if(Object.keys(i).length>100||Fy(i,0)>16)return;let a;try{a=JSON.stringify(i)}catch{throw new H(`invalid_input`,`Derived schema sample cannot be serialized`)}if(!(!a||a.length>4e3))return r.length+a.length}function Ry(e){return e&&e.length>0?e:void 0}function zy(e){let t=Qv.safeParse(e);if(!t.success)throw new H(`invalid_input`,`Description output exceeded its bounds`);return t.data}function By(e,t){let n=e.find(e=>e.path===t.path);if(n){let e=`env.${n.path}`,t={path:n.path,description:Ry(n.description),types:Ay([n.rendered]),kind:`operation`,inputSchema:n.inputSchema,usage:`await ${e}({ ... })`};if(t.types.length>2e4)throw new H(`invalid_input`,`Description types exceed the bounded output`);return zy(t)}let r=`${t.path}.`,i=e.filter(e=>e.path.startsWith(r)).sort((e,t)=>oy(e.path,t.path));if(i.length===0)throw new H(`unknown_target`,`Unknown target: ${t.path}`);let a=i[0];if(!a)throw new H(`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?ky(i.map(e=>e.rendered)):Ay((o.length>0?o:i).map(e=>e.rendered)),s.length>2e4)throw new H(`invalid_input`,`Description types exceed the bounded output`);return zy({path:t.path,description:Ry(a.instructions),types:s,kind:`module`})}function Vy(e){return Object.freeze({...e,fingerprint:Py(e.input),inputSchema:Ny(e.input),sample:My(e.input),rendered:jy(e)})}var Hy={exact:14,startsWith:9,phrase:6,token:4,prefix:2,substring:2,includes:1};function Uy(e){switch(e){case`path`:return 12;case`namespace`:return 8;case`method`:return 10;case`description`:return 5;default:return 5}}function Wy(e){return py([...e].sort((e,t)=>oy(e.path,t.path)).map(e=>fy([e.path,e.description??null,e.capabilityNotes??null,e.instructions??null,e.fingerprint,e.output===void 0?null:Py(e.output,`output`)])).join(`
|
|
9
|
+
`))}function Gy(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=cy(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 Ky(e,t,n){let r=sy(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...dy(e)],s=`none`;for(let e of n){let t=Gy(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=Hy[s]*Uy(t);c>a?(i=s,a=c,o=[e]):c===a&&!o.includes(e)&&o.push(e)}return{level:i,score:a,matchedTokens:o}}function qy(e,t){let n=sy(e);return[t,...dy(t)].some(e=>n.includes(e))}function Jy(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 Yy(e){let t=Xv.safeParse(e);if(!t.success)throw new H(`invalid_input`,`Search output exceeded its bounds`);return t.data}function Xy(e){return[my(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Zy(e){return Yy({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Qy(e,t,n,r,i){let a=hy(e.path),o=my(e.path),s=e.description??``,c=[e.path,a,o,s],l=Ky(e.path,`path`,n),u=Ky(a,`namespace`,n),d=Ky(o,`method`,n),f=Ky(s,`description`,n),p=r.filter(e=>c.some(t=>qy(t,e))).length,m=p/r.length,ee=sy(`${e.path} ${s}`).includes(t);if(m<i&&!ee)return;let te=Math.max(l.score,u.score,d.score,f.score);if(te===0)return;let ne=p===r.length?25:m*10,re=r[0];re&&c.some(e=>qy(e,re))&&(ne+=8),(l.level===`exact`||d.level===`exact`)&&(ne+=20);let ie={path:e.path,score:te+ne};s&&(ie.description=s);let ae=Jy([[`method`,d],[`description`,f],[`path`,l],[`namespace`,u]]);return ae&&(ie.matchReason=ae),e.sample&&(ie.sample=e.sample),e.capabilityNotes&&(ie.capabilityNotes=e.capabilityNotes),{result:ie,cluster:Xy(e),pathScore:l.score}}function $y(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||oy(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>oy(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||oy(e.path,t.path))}function eb(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return Yy({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function tb(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=sy(t),o=cy(a),s=o.filter(e=>!uy(e));if(s.length===0)return Zy(r);let c=s.length<=2?1:.6,l=[];for(let t of e){let e=Qy(t,a,o,s,c);e&&l.push(e)}return eb($y(l),i,r)}var nb=tr({catalogStamp:Zv.shape.catalogStamp,namespace:qv.shape.namespace.unwrap().nullable(),after:Yv.shape.path});function rb(e,t,n){let r=qv.safeParse(n);if(!r.success)throw new H(`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)=>oy(hy(e.path),hy(t.path))||oy(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=nb.parse(JSON.parse(i.cursor))}catch(e){throw new H(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new H(`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 H(`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 Zv.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 ib=1e6;function ab(e){let t=ny.safeParse(e);if(!t.success)throw new H(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new H(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>oy(e.path,t.path)),r=new Set,i=0;for(let e of n){if(r.has(e.path))throw new H(`duplicate_operation`,`Duplicate operation path: ${e.path}`);r.add(e.path);let t=Iy(e.input,`input`);if(t===void 0)throw new H(`invalid_input`,`Schema projection is too large: ${e.path}`);let n=e.output?Iy(e.output,`output`):0;if(n===void 0)throw new H(`invalid_input`,`Schema output projection is too large: ${e.path}`);if(i+=t+n+e.path.length,i+=e.description?.length??0,i+=e.capabilityNotes?.length??0,i+=e.instructions?.length??0,i>ib)throw new H(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}let a=n.map(e=>Vy(e)),o=new Map;for(let e of a){let t=e.path.slice(0,e.path.lastIndexOf(`.`)),n=o.get(t)??[];n.push(e),o.set(t,n)}for(let[e,t]of o){let n=t.map(e=>e.rendered),r=ky(n),i=Ay(n);if(r.length>2e4||i.length>2e4)throw new H(`invalid_input`,`Namespace description exceeds the bounded output: ${e}`)}return{revision:t.data.revision,operations:a}}function ob(e){let t=ab(e),n=Object.freeze(t.operations),r=Wy(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=Gv.safeParse(e);if(!t.success)throw new H(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new H(`empty_query`,`Search query must not be empty`);return tb(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Kv.safeParse(e);if(!t.success)throw new H(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new H(`empty_query`,`Description target must not be empty`);return By(n,t.data)},list:e=>rb(i,r,e),stamp:()=>r})}var sb=g(()=>b().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/));g(()=>Ar([Gt(b(),Lt()),Oe()]));var cb=g(()=>gr({tool:sb,title:b().max(120),description:b().max(1e3),input:Gt(b(),Lt()),output:Gt(b(),Lt()),call:Gt(b(),Lt())}).catchall(Lt()));g(()=>Ot(`kind`,[tr({kind:t(`unindexed`)}),tr({kind:t(`ready`),tools:Ne(cb).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var lb=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:Gv,output:Xv}),ub=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Kv,output:Qv}),db=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:qv,output:Zv});Object.freeze({createCatalog:ob,forageSearchDefinition:lb,forageDescribeDefinition:ub,forageListDefinition:db});var fb=`invalid_definition`,pb=`runtime_closed`,mb=`source_failure`,U=class extends Error{code=fb;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},hb=class extends Error{code=pb;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},gb=class extends Error{sourceId;phase;code=mb;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`}},_b=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},vb=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},yb=class extends Di(`SourceInvalid`){},bb=class extends Di(`GuestThrew`){},xb=class extends Di(`DeadlineExceeded`){},Sb=class extends Di(`Cancelled`){},Cb=class extends Di(`DispatchLost`){},wb=class extends Di(`SandboxCrashed`){},Tb=class extends Di(`BadResponse`){},Eb=class extends Di(`ResultTooLarge`){},Db=class extends Di(`ResultNotJson`){},Ob=class extends Di(`CapabilityFailed`){constructor(e){super(e),this.message=jb(this)}},kb=class extends Di(`Unknown`){};function Ab(e,t){switch(e._tag){case`SourceInvalid`:return new yb({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new bb({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new xb({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`Cancelled`:return new Sb({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new Cb({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new wb({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new Tb({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new Eb({size:e.size,ref:t});case`ResultNotJson`:return new Db({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new Ob({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new kb({rawCause:e.rawCause,ref:t})}}function jb(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`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 Mb=g(()=>Ar([be(yb),be(bb),be(xb),be(Sb),be(Cb),be(wb),be(Tb),be(Eb),be(Db),be(Ob),be(kb)])),Nb=g(()=>on().pipe(Ar([be(Error).transform(e=>({kind:`error`,value:e})),_t().transform(e=>({kind:`null`,value:e})),Tt().transform(e=>({kind:`undefined`,value:e})),b().transform(e=>({kind:`string`,value:e})),Oe().transform(e=>({kind:`boolean`,value:e})),Ar([Yn(),Tr(),t(1/0),t(-1/0)]).transform(e=>({kind:`number`,value:e})),fr().transform(e=>({kind:`bigint`,value:e})),en().transform(e=>({kind:`symbol`,value:e})),be(Function).transform(e=>({kind:`function`,value:e})),Ne(on()).transform(e=>({kind:`array`,value:e})),Ar([be(Object),Gt(b(),on())]).transform(e=>({kind:`object`,value:e})),on().transform(()=>({kind:`opaque`}))])));function Pb(e){return Mb.safeParse(e).success}function Fb(e){let t=Mb.safeParse(e);return t.success?t.data:new kb({rawCause:e})}function Ib(e){let t=Nb.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}g(()=>Lt().optional());function Lb(e){return Rb(e,new Set)}function Rb(e,t){let n=Nb.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=>Rb(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,Rb(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=Rb(r.cause,t)),r instanceof AggregateError&&(e.errors=Rb(r.errors,t))}return e}finally{t.delete(e)}}}}var zb=g(()=>gr({name:t(`ReferenceError`),message:b().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));g(()=>Ar([zb,gr({name:b(),message:b()})]).and(gr({transportMessage:b().max(512).optional()})));var Bb=g(()=>tr({v:t(1),kind:t(`sandbox_failure`),tag:l([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:b().min(1).max(32),message:b().max(160)})),Vb=E(Gm(hp)),Hb=g(()=>b().transform((e,t)=>{let n=Vb(e);return Re(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),ye):n.success})).pipe(Bb);tr({error:Hb}),g(()=>on().pipe(Ar([t(`Execution timed out`).transform(()=>({kind:`deadline`})),on().transform(e=>({kind:`bad_response`,rawCause:e}))])));var Ub=[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],Wb=[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],Gb=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,Kb=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,qb={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`},Jb=`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`,Yb={5:Jb,"5module":Jb+` export import`,6:Jb+` const class extends export import super`},Xb=/^in(stanceof)?$/,Zb=RegExp(`[`+Kb+`]`),Qb=RegExp(`[`+Kb+Gb+`]`);function $b(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 ex(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&Zb.test(String.fromCharCode(e)):t!==!1&&$b(e,Wb)}function tx(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&&Qb.test(String.fromCharCode(e)):t===!1?!1:$b(e,Wb)||$b(e,Ub)}var W=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 nx(e,t){return new W(e,{beforeExpr:!0,binop:t})}var rx={beforeExpr:!0},ix={startsExpr:!0},ax={};function G(e,t){return t===void 0&&(t={}),t.keyword=e,ax[e]=new W(e,t)}var K={num:new W(`num`,ix),regexp:new W(`regexp`,ix),string:new W(`string`,ix),name:new W(`name`,ix),privateId:new W(`privateId`,ix),eof:new W(`eof`),bracketL:new W(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new W(`]`),braceL:new W(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new W(`}`),parenL:new W(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new W(`)`),comma:new W(`,`,rx),semi:new W(`;`,rx),colon:new W(`:`,rx),dot:new W(`.`),question:new W(`?`,rx),questionDot:new W(`?.`),arrow:new W(`=>`,rx),template:new W(`template`),invalidTemplate:new W(`invalidTemplate`),ellipsis:new W(`...`,rx),backQuote:new W("`",ix),dollarBraceL:new W("${",{beforeExpr:!0,startsExpr:!0}),eq:new W(`=`,{beforeExpr:!0,isAssign:!0}),assign:new W(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new W(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new W(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:nx(`||`,1),logicalAND:nx(`&&`,2),bitwiseOR:nx(`|`,3),bitwiseXOR:nx(`^`,4),bitwiseAND:nx(`&`,5),equality:nx(`==/!=/===/!==`,6),relational:nx(`</>/<=/>=`,7),bitShift:nx(`<</>>/>>>`,8),plusMin:new W(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:nx(`%`,10),star:nx(`*`,10),slash:nx(`/`,10),starstar:new W(`**`,{beforeExpr:!0}),coalesce:nx(`??`,1),_break:G(`break`),_case:G(`case`,rx),_catch:G(`catch`),_continue:G(`continue`),_debugger:G(`debugger`),_default:G(`default`,rx),_do:G(`do`,{isLoop:!0,beforeExpr:!0}),_else:G(`else`,rx),_finally:G(`finally`),_for:G(`for`,{isLoop:!0}),_function:G(`function`,ix),_if:G(`if`),_return:G(`return`,rx),_switch:G(`switch`),_throw:G(`throw`,rx),_try:G(`try`),_var:G(`var`),_const:G(`const`),_while:G(`while`,{isLoop:!0}),_with:G(`with`),_new:G(`new`,{beforeExpr:!0,startsExpr:!0}),_this:G(`this`,ix),_super:G(`super`,ix),_class:G(`class`,ix),_extends:G(`extends`,rx),_export:G(`export`),_import:G(`import`,ix),_null:G(`null`,ix),_true:G(`true`,ix),_false:G(`false`,ix),_in:G(`in`,{beforeExpr:!0,binop:7}),_instanceof:G(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:G(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:G(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:G(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},ox=/\r\n?|\n|\u2028|\u2029/,sx=new RegExp(ox.source,`g`);function cx(e){return e===10||e===13||e===8232||e===8233}function lx(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(cx(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var ux=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,dx=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,fx=Object.prototype,px=fx.hasOwnProperty,mx=fx.toString,hx=Object.hasOwn||(function(e,t){return px.call(e,t)}),gx=Array.isArray||(function(e){return mx.call(e)===`[object Array]`}),_x=Object.create(null);function vx(e){return _x[e]||(_x[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function yx(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var bx=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,xx=function(e,t){this.line=e,this.column=t};xx.prototype.offset=function(e){return new xx(this.line,this.column+e)};var Sx=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function Cx(e,t){for(var n=1,r=0;;){var i=lx(e,r,t);if(i<0)return new xx(n,t-r);++n,r=i}}var wx={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},Tx=!1;function Ex(e){var t={};for(var n in wx)t[n]=e&&hx(e,n)?e[n]:wx[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!Tx&&typeof console==`object`&&console.warn&&(Tx=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
10
|
+
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),gx(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}if(gx(t.onComment)&&(t.onComment=Dx(t,t.onComment)),t.sourceType===`commonjs`&&t.allowAwaitOutsideFunction)throw Error(`Cannot use allowAwaitOutsideFunction with sourceType: commonjs`);return t}function Dx(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 Sx(this,o,s)),e.ranges&&(c.range=[i,a]),t.push(c)}}var Ox=1,kx=2,Ax=4,jx=8,Mx=16,Nx=32,Px=64,Fx=128,Ix=256,Lx=512,Rx=1024,zx=Ox|kx|Ix;function Bx(e,t){return kx|(e?Ax:0)|(t?jx:0)}var Vx=0,Hx=1,Ux=2,Wx=3,Gx=4,Kx=5,qx=function(e,t,n){this.options=e=Ex(e),this.sourceFile=e.sourceFile,this.keywords=vx(Yb[e.ecmaVersion>=6?6:e.sourceType===`module`?`5module`:5]);var r=``;e.allowReserved!==!0&&(r=qb[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType===`module`&&(r+=` await`)),this.reservedWords=vx(r);var i=(r?r+` `:``)+qb.strict;this.reservedWordsStrict=vx(i),this.reservedWordsStrictBind=vx(i+` `+qb.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(`
|
|
11
|
+
`,n-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(ox).length)):this.lineStart=0,this.type=K.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`?kx:Ox),this.regexpState=null,this.privateNameStack=[]},Jx={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}};qx.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},Jx.inFunction.get=function(){return(this.currentVarScope().flags&kx)>0},Jx.inGenerator.get=function(){return(this.currentVarScope().flags&jx)>0},Jx.inAsync.get=function(){return(this.currentVarScope().flags&Ax)>0},Jx.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(Ix|Lx))return!1;if(t&kx)return(t&Ax)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},Jx.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&Ox)},Jx.allowSuper.get=function(){return(this.currentThisScope().flags&Px)>0||this.options.allowSuperOutsideMethod},Jx.allowDirectSuper.get=function(){return(this.currentThisScope().flags&Fx)>0},Jx.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},Jx.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(Ix|Lx)||t&kx&&!(t&Mx))return!0}return!1},Jx.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&Rx||!this.inModule&&e&Ox)},Jx.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&Ix)>0},qx.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},qx.parse=function(e,t){return new this(t,e).parse()},qx.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},qx.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(qx.prototype,Jx);var Yx=qx.prototype,Xx=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;Yx.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){dx.lastIndex=e,e+=dx.exec(this.input)[0].length;var t=Xx.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){dx.lastIndex=e+t[0].length;var n=dx.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||ox.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,dx.lastIndex=e,e+=dx.exec(this.input)[0].length,this.input[e]===`;`&&e++}},Yx.eat=function(e){return this.type===e&&(this.next(),!0)},Yx.isContextual=function(e){return this.type===K.name&&this.value===e&&!this.containsEsc},Yx.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},Yx.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}},Yx.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},Yx.canInsertSemicolon=function(){return this.type===K.eof||this.type===K.braceR||ox.test(this.input.slice(this.lastTokEnd,this.start))},Yx.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},Yx.semicolon=function(){!this.eat(K.semi)&&!this.insertSemicolon()&&this.unexpected()},Yx.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},Yx.expect=function(e){this.eat(e)||this.unexpected()},Yx.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var Zx=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};Yx.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`)}},Yx.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`)},Yx.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`)},Yx.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var q=qx.prototype;q.parseTopLevel=function(e){var t=Object.create(null);for(e.body||=[];this.type!==K.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 Qx={kind:`loop`},$x={kind:`switch`};q.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;dx.lastIndex=this.pos;var t=dx.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(ex(r)){var i=n;do n+=r<=65535?1:2;while(tx(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!Xb.test(a))return!0}return!1},q.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;dx.lastIndex=this.pos;var e=dx.exec(this.input),t=this.pos+e[0].length,n;return!ox.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(tx(n=this.fullCharCodeAt(t+8))||n===92))},q.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;dx.lastIndex=this.pos;var n=dx.exec(this.input),r=this.pos+n[0].length;if(ox.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||tx(a=this.fullCharCodeAt(i))||a===92)return!1;dx.lastIndex=i;var o=dx.exec(this.input);if(r=i+o[0].length,o&&ox.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!ex(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(tx(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(Xb.test(l))return!1;if(t&&!e&&l===`of`){dx.lastIndex=r;var u=dx.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},q.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},q.isUsing=function(e){return this.isUsingKeyword(!1,e)},q.parseStatement=function(e,t,n){var r=this.type,i=this.startNode(),a;switch(this.isLet(e)&&(r=K._var,a=`let`),r){case K._break:case K._continue:return this.parseBreakContinueStatement(i,r.keyword);case K._debugger:return this.parseDebuggerStatement(i);case K._do:return this.parseDoStatement(i);case K._for:return this.parseForStatement(i);case K._function:return e&&(this.strict||e!==`if`&&e!==`label`)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case K._class:return e&&this.unexpected(),this.parseClass(i,!0);case K._if:return this.parseIfStatement(i);case K._return:return this.parseReturnStatement(i);case K._switch:return this.parseSwitchStatement(i);case K._throw:return this.parseThrowStatement(i);case K._try:return this.parseTryStatement(i);case K._const:case K._var:return a||=this.value,e&&a!==`var`&&this.unexpected(),this.parseVarStatement(i,a);case K._while:return this.parseWhileStatement(i);case K._with:return this.parseWithStatement(i);case K.braceL:return this.parseBlock(!0,i);case K.semi:return this.parseEmptyStatement(i);case K._export:case K._import:if(this.options.ecmaVersion>10&&r===K._import){dx.lastIndex=this.pos;var o=dx.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===K._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===K.name&&d.type===`Identifier`&&this.eat(K.colon)?this.parseLabeledStatement(i,u,d,e):this.parseExpressionStatement(i,d)}},q.parseBreakContinueStatement=function(e,t){var n=t===`break`;this.next(),this.eat(K.semi)||this.insertSemicolon()?e.label=null:this.type===K.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`)},q.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,`DebuggerStatement`)},q.parseDoStatement=function(e){return this.next(),this.labels.push(Qx),e.body=this.parseStatement(`do`),this.labels.pop(),this.expect(K._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(K.semi):this.semicolon(),this.finishNode(e,`DoWhileStatement`)},q.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual(`await`)?this.lastTokStart:-1;if(this.labels.push(Qx),this.enterScope(0),this.expect(K.parenL),this.type===K.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var n=this.isLet();if(this.type===K._var||this.type===K._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 Zx,d=this.start,f=t>-1?this.parseExprSubscripts(u,`await`):this.parseExpression(!0,u);return this.type===K._in||(o=this.options.ecmaVersion>=6&&this.isContextual(`of`))?(t>-1?(this.type===K._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))},q.parseForAfterInit=function(e,t,n){return(this.type===K._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))&&t.declarations.length===1?(this.type===K._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))},q.parseFunctionStatement=function(e,t,n){return this.next(),this.parseFunction(e,tS|(n?0:nS),!1,t)},q.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(`if`),e.alternate=this.eat(K._else)?this.parseStatement(`if`):null,this.finishNode(e,`IfStatement`)},q.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,`'return' outside of function`),this.next(),this.eat(K.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,`ReturnStatement`)},q.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(K.braceL),this.labels.push($x),this.enterScope(Rx);for(var t,n=!1;this.type!==K.braceR;)if(this.type===K._case||this.type===K._default){var r=this.type===K._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(K.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`)},q.parseThrowStatement=function(e){return this.next(),ox.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 eS=[];q.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?Nx:0),this.checkLValPattern(e,t?Gx:Ux),this.expect(K.parenR),e},q.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===K._catch){var t=this.startNode();this.next(),this.eat(K.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(K._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,`Missing catch or finally clause`),this.finishNode(e,`TryStatement`)},q.parseVarStatement=function(e,t,n){return this.next(),this.parseVar(e,!1,t,n),this.semicolon(),this.finishNode(e,`VariableDeclaration`)},q.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(Qx),e.body=this.parseStatement(`while`),this.labels.pop(),this.finishNode(e,`WhileStatement`)},q.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`)},q.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,`EmptyStatement`)},q.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===K._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`)},q.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,`ExpressionStatement`)},q.parseBlock=function(e,t,n){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(K.braceL),e&&this.enterScope(0);this.type!==K.braceR;){var r=this.parseStatement(null);t.body.push(r)}return n&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,`BlockStatement`)},q.parseFor=function(e,t){return e.init=t,this.expect(K.semi),e.test=this.type===K.semi?null:this.parseExpression(),this.expect(K.semi),e.update=this.type===K.parenR?null:this.parseExpression(),this.expect(K.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,`ForStatement`)},q.parseForIn=function(e,t){var n=this.type===K._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(K.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,n?`ForInStatement`:`ForOfStatement`)},q.parseVar=function(e,t,n,r){for(e.declarations=[],e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(K.eq)?i.init=this.parseMaybeAssign(t):!r&&n===`const`&&!(this.type===K._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))?this.unexpected():!r&&(n===`using`||n===`await using`)&&this.options.ecmaVersion>=17&&this.type!==K._in&&!this.isContextual(`of`)?this.raise(this.lastTokEnd,`Missing initializer in `+n+` declaration`):!r&&i.id.type!==`Identifier`&&!(t&&(this.type===K._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(K.comma))break}return e},q.parseVarId=function(e,t){e.id=t===`using`||t===`await using`?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t===`var`?Hx:Ux,!1)};var tS=1,nS=2,rS=4;q.parseFunction=function(e,t,n,r,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===K.star&&t&nS&&this.unexpected(),e.generator=this.eat(K.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&tS&&(e.id=t&rS&&this.type!==K.name?null:this.parseIdent(),e.id&&!(t&nS)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?Hx:Ux:Wx));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(Bx(e.async,e.generator)),t&tS||(e.id=this.type===K.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&tS?`FunctionDeclaration`:`FunctionExpression`)},q.parseFunctionParams=function(e){this.expect(K.parenL),e.params=this.parseBindingList(K.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},q.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(K.braceL);this.type!==K.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`&&iS(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`)},q.parseClassElement=function(e){if(this.eat(K.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(K.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===K.star?s=!0:r=`static`}if(n.static=s,!r&&t>=8&&this.eatContextual(`async`)&&((this.isClassElementNameStart()||this.type===K.star)&&!this.canInsertSemicolon()?a=!0:r=`async`),!r&&(t>=9||!a)&&this.eat(K.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===K.parenL||o!==`method`||i||a){var l=!n.static&&aS(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},q.isClassElementNameStart=function(){return this.type===K.name||this.type===K.privateId||this.type===K.num||this.type===K.string||this.type===K.bracketL||this.type.keyword},q.parseClassElementName=function(e){this.type===K.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)},q.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&&aS(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`)},q.parseClassField=function(e){return aS(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&aS(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(K.eq)?(this.enterScope(Lx|Px),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,`PropertyDefinition`)},q.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(Ix|Px);this.type!==K.braceR;){var n=this.parseStatement(null);e.body.push(n)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,`StaticBlock`)},q.parseClassId=function(e,t){this.type===K.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,Ux,!1)):(t===!0&&this.unexpected(),e.id=null)},q.parseClassSuper=function(e){e.superClass=this.eat(K._extends)?this.parseExprSubscripts(null,!1):null},q.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},q.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];hx(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function iS(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 aS(e,t){var n=e.computed,r=e.key;return!n&&(r.type===`Identifier`&&r.name===t||r.type===`Literal`&&r.value===t)}q.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!==K.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ExportAllDeclaration`)},q.parseExport=function(e,t){if(this.next(),this.eat(K.star))return this.parseExportAllDeclaration(e,t);if(this.eat(K._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!==K.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`)},q.parseExportDeclaration=function(e){return this.parseStatement(null)},q.parseExportDefaultDeclaration=function(){var e;if(this.type===K._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,tS|rS,!1,e)}if(this.type===K._class){var n=this.startNode();return this.parseClass(n,`nullableID`)}var r=this.parseMaybeAssign();return this.semicolon(),r},q.checkExport=function(e,t,n){e&&(typeof t!=`string`&&(t=t.type===`Identifier`?t.name:t.value),hx(e,t)&&this.raiseRecoverable(n,`Duplicate export '`+t+`'`),e[t]=!0)},q.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)},q.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)}},q.shouldParseExportStatement=function(){return this.type.keyword===`var`||this.type.keyword===`const`||this.type.keyword===`class`||this.type.keyword===`function`||this.isLet()||this.isAsyncFunction()},q.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`)},q.parseExportSpecifiers=function(e){var t=[],n=!0;for(this.expect(K.braceL);!this.eat(K.braceR);){if(n)n=!1;else if(this.expect(K.comma),this.afterTrailingComma(K.braceR))break;t.push(this.parseExportSpecifier(e))}return t},q.parseImport=function(e){return this.next(),this.type===K.string?(e.specifiers=eS,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual(`from`),e.source=this.type===K.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ImportDeclaration`)},q.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,Ux),this.finishNode(e,`ImportSpecifier`)},q.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,Ux),this.finishNode(e,`ImportDefaultSpecifier`)},q.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual(`as`),e.local=this.parseIdent(),this.checkLValSimple(e.local,Ux),this.finishNode(e,`ImportNamespaceSpecifier`)},q.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===K.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(K.comma)))return e;if(this.type===K.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(K.braceL);!this.eat(K.braceR);){if(t)t=!1;else if(this.expect(K.comma),this.afterTrailingComma(K.braceR))break;e.push(this.parseImportSpecifier())}return e},q.parseWithClause=function(){var e=[];if(!this.eat(K._with))return e;this.expect(K.braceL);for(var t={},n=!0;!this.eat(K.braceR);){if(n)n=!1;else if(this.expect(K.comma),this.afterTrailingComma(K.braceR))break;var r=this.parseImportAttribute(),i=r.key.type===`Identifier`?r.key.name:r.key.value;hx(t,i)&&this.raiseRecoverable(r.key.start,`Duplicate attribute key '`+i+`'`),t[i]=!0,e.push(r)}return e},q.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===K.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`),this.expect(K.colon),this.type!==K.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,`ImportAttribute`)},q.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===K.string){var e=this.parseLiteral(this.value);return bx.test(e.value)&&this.raise(e.start,`An export name cannot include a lone surrogate.`),e}return this.parseIdent(!0)},q.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)},q.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 oS=qx.prototype;oS.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},oS.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},oS.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},oS.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==K.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,`RestElement`)},oS.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case K.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(K.bracketR,!0,!0),this.finishNode(e,`ArrayPattern`);case K.braceL:return this.parseObj(!0)}return this.parseIdent()},oS.parseBindingList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);)if(a?a=!1:this.expect(K.comma),t&&this.type===K.comma)i.push(null);else if(n&&this.afterTrailingComma(e))break;else if(this.type===K.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===K.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},oS.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},oS.parseBindingListItem=function(e){return e},oS.parseMaybeDefault=function(e,t,n){if(n||=this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(K.eq))return n;var r=this.startNodeAt(e,t);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,`AssignmentPattern`)},oS.checkLValSimple=function(e,t,n){t===void 0&&(t=Vx);var r=t!==Vx;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===Ux&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(hx(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==Kx&&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`)}},oS.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=Vx),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)}},oS.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=Vx),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 sS=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},cS={b_stat:new sS(`{`,!1),b_expr:new sS(`{`,!0),b_tmpl:new sS("${",!1),p_stat:new sS(`(`,!1),p_expr:new sS(`(`,!0),q_tmpl:new sS("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new sS(`function`,!1),f_expr:new sS(`function`,!0),f_expr_gen:new sS(`function`,!0,!1,null,!0),f_gen:new sS(`function`,!1,!1,null,!0)},lS=qx.prototype;lS.initialContext=function(){return[cS.b_stat]},lS.curContext=function(){return this.context[this.context.length-1]},lS.braceIsBlock=function(e){var t=this.curContext();return t===cS.f_expr||t===cS.f_stat?!0:e===K.colon&&(t===cS.b_stat||t===cS.b_expr)?!t.isExpr:e===K._return||e===K.name&&this.exprAllowed?ox.test(this.input.slice(this.lastTokEnd,this.start)):e===K._else||e===K.semi||e===K.eof||e===K.parenR||e===K.arrow?!0:e===K.braceL?t===cS.b_stat:e===K._var||e===K._const||e===K.name?!1:!this.exprAllowed},lS.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},lS.updateContext=function(e){var t,n=this.type;n.keyword&&e===K.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},lS.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},K.parenR.updateContext=K.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===cS.b_stat&&this.curContext().token===`function`&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},K.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?cS.b_stat:cS.b_expr),this.exprAllowed=!0},K.dollarBraceL.updateContext=function(){this.context.push(cS.b_tmpl),this.exprAllowed=!0},K.parenL.updateContext=function(e){var t=e===K._if||e===K._for||e===K._with||e===K._while;this.context.push(t?cS.p_stat:cS.p_expr),this.exprAllowed=!0},K.incDec.updateContext=function(){},K._function.updateContext=K._class.updateContext=function(e){e.beforeExpr&&e!==K._else&&(e!==K.semi||this.curContext()===cS.p_stat)&&!(e===K._return&&ox.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==K.colon&&e!==K.braceL||this.curContext()!==cS.b_stat)?this.context.push(cS.f_expr):this.context.push(cS.f_stat),this.exprAllowed=!1},K.colon.updateContext=function(){this.curContext().token===`function`&&this.context.pop(),this.exprAllowed=!0},K.backQuote.updateContext=function(){this.curContext()===cS.q_tmpl?this.context.pop():this.context.push(cS.q_tmpl),this.exprAllowed=!1},K.star.updateContext=function(e){if(e===K._function){var t=this.context.length-1;this.context[t]===cS.f_expr?this.context[t]=cS.f_expr_gen:this.context[t]=cS.f_gen}this.exprAllowed=!0},K.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==K.dot&&(this.value===`of`&&!this.exprAllowed||this.value===`yield`&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var J=qx.prototype;J.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}},J.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===K.comma){var o=n.startNodeAt(r,i);for(o.expressions=[a];n.eat(K.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return n.finishNode(o,`SequenceExpression`)}return a})},J.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 Zx,r=!0);var s=this.start,c=this.startLoc;(this.type===K.parenL||this.type===K.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===K.eq&&(l=this.toAssignable(l,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=l.start&&(t.shorthandAssign=-1),this.type===K.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},J.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(K.question)){var a=this.startNodeAt(n,r);return a.test=i,a.consequent=this.parseMaybeAssign(),this.expect(K.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,`ConditionalExpression`)}return i},J.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)},J.parseExprOp=function(e,t,n,r,i){var a=this.type.binop;if(a!=null&&(!i||this.type!==K._in)&&a>r){var o=this.type===K.logicalOR||this.type===K.logicalAND,s=this.type===K.coalesce;s&&(a=K.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===K.coalesce||s&&(this.type===K.logicalOR||this.type===K.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},J.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`)},J.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===K.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`&&uS(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&dS(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===K.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==K._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(K.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 uS(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&&uS(e.expression)}function dS(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&dS(e.expression)||e.type===`ParenthesizedExpression`&&dS(e.expression)}J.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},J.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}},J.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(K.arrow)},J.parseSubscriptAsyncArrow=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!0,r)},J.parseSubscript=function(e,t,n,r,i,a,o){var s=this.options.ecmaVersion>=11,c=s&&this.eat(K.questionDot);r&&c&&this.raise(this.lastTokStart,`Optional chaining cannot appear in the callee of new expressions`);var l=this.eat(K.bracketL);if(l||c&&this.type!==K.parenL&&this.type!==K.backQuote||this.eat(K.dot)){var u=this.startNodeAt(t,n);u.object=e,l?(u.property=this.parseExpression(),this.expect(K.bracketR)):u.property=this.type===K.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(K.parenL)){var d=new Zx,f=this.yieldPos,p=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var ee=this.parseExprList(K.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===K.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},J.parseExprAtom=function(e,t,n){this.type===K.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case K._super:return this.allowSuper||this.raise(this.start,`'super' keyword outside a method`),r=this.startNode(),this.next(),this.type===K.parenL&&!this.allowDirectSuper&&this.raise(r.start,`super() call outside constructor of a subclass`),this.type!==K.dot&&this.type!==K.bracketL&&this.type!==K.parenL&&this.unexpected(),this.finishNode(r,`Super`);case K._this:return r=this.startNode(),this.next(),this.finishNode(r,`ThisExpression`);case K.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(K._function))return this.overrideContext(cS.f_expr),this.parseFunction(this.startNodeAt(a,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(K.arrow))return this.parseArrowExpression(this.startNodeAt(a,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name===`async`&&this.type===K.name&&!s&&(!this.potentialArrowInForAwait||this.value!==`of`||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(K.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,o),[c],!0,t)}return c;case K.regexp:var l=this.value;return r=this.parseLiteral(l.value),r.regex={pattern:l.pattern,flags:l.flags},r;case K.num:case K.string:return this.parseLiteral(this.value);case K._null:case K._true:case K._false:return r=this.startNode(),r.value=this.type===K._null?null:this.type===K._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,`Literal`);case K.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 K.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(K.bracketR,!0,!0,e),this.finishNode(r,`ArrayExpression`);case K.braceL:return this.overrideContext(cS.b_expr),this.parseObj(!1,e);case K._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case K._class:return this.parseClass(this.startNode(),!1);case K._new:return this.parseNew();case K.backQuote:return this.parseTemplate();case K._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}},J.parseExprAtomDefault=function(){this.unexpected()},J.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword import`),this.next(),this.type===K.parenL&&!e)return this.parseDynamicImport(t);if(this.type===K.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()},J.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(K.parenR)?e.options=null:(this.expect(K.comma),this.afterTrailingComma(K.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(K.parenR)||(this.expect(K.comma),this.afterTrailingComma(K.parenR)||this.unexpected())));else if(!this.eat(K.parenR)){var t=this.start;this.eat(K.comma)&&this.eat(K.parenR)?this.raiseRecoverable(t,`Trailing comma is not allowed in import()`):this.unexpected(t)}return this.finishNode(e,`ImportExpression`)},J.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`)},J.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`)},J.parseParenExpression=function(){this.expect(K.parenL);var e=this.parseExpression();return this.expect(K.parenR),e},J.shouldParseArrow=function(e){return!this.canInsertSemicolon()},J.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 Zx,f=this.yieldPos,p=this.awaitPos,m;for(this.yieldPos=0,this.awaitPos=0;this.type!==K.parenR;){if(l?l=!1:this.expect(K.comma),a&&this.afterTrailingComma(K.parenR,!0)){u=!0;break}if(this.type===K.ellipsis){m=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===K.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(K.parenR),e&&this.shouldParseArrow(c)&&this.eat(K.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},J.parseParenItem=function(e){return e},J.parseParenArrowList=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!1,r)};var fS=[];J.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===K.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(K.parenL)?this.parseExprList(K.parenR,this.options.ecmaVersion>=8,!1):fS,this.finishNode(e,`NewExpression`)},J.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===K.invalidTemplate?(t||this.raiseRecoverable(this.start,`Bad escape sequence in untagged template literal`),n.value={raw:this.value.replace(/\r\n?/g,`
|
|
12
|
+
`),cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
|
|
13
|
+
`),cooked:this.value},this.next(),n.tail=this.type===K.backQuote,this.finishNode(n,`TemplateElement`)},J.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===K.eof&&this.raise(this.pos,`Unterminated template literal`),this.expect(K.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(K.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,`TemplateLiteral`)},J.isAsyncProp=function(e){return!e.computed&&e.key.type===`Identifier`&&e.key.name===`async`&&(this.type===K.name||this.type===K.num||this.type===K.string||this.type===K.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===K.star)&&!ox.test(this.input.slice(this.lastTokEnd,this.start))},J.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(K.braceR);){if(r)r=!1;else if(this.expect(K.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(K.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`)},J.parseProperty=function(e,t){var n=this.startNode(),r,i,a,o;if(this.options.ecmaVersion>=9&&this.eat(K.ellipsis))return e?(n.argument=this.parseIdent(!1),this.type===K.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===K.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(K.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(K.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,e,r,i,a,o,t,s),this.finishNode(n,`Property`)},J.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`)},J.parsePropertyValue=function(e,t,n,r,i,a,o,s){(n||r)&&this.type===K.colon&&this.unexpected(),this.eat(K.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind=`init`):this.options.ecmaVersion>=6&&this.type===K.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!==K.comma&&this.type!==K.braceR&&this.type!==K.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===K.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()},J.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(K.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(K.bracketR),e.key;e.computed=!1}return e.key=this.type===K.num||this.type===K.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`)},J.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},J.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(Bx(t,r.generator)|Px|(n?Fx:0)),this.expect(K.parenL),r.params=this.parseBindingList(K.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`)},J.parseArrowExpression=function(e,t,n,r){var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(Bx(n,!1)|Mx),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`)},J.parseFunctionBody=function(e,t,n,r){var i=t&&this.type!==K.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,Kx),e.body=this.parseBlock(!1,void 0,o&&!a),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()},J.isSimpleParamList=function(e){for(var t=0,n=e;t<n.length;t+=1)if(n[t].type!==`Identifier`)return!1;return!0},J.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,Hx,t?null:n)}},J.parseExprList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);){if(a)a=!1;else if(this.expect(K.comma),t&&this.afterTrailingComma(e))break;var o=void 0;n&&this.type===K.comma?o=null:this.type===K.ellipsis?(o=this.parseSpread(r),r&&this.type===K.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):o=this.parseMaybeAssign(!1,r),i.push(o)}return i},J.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&zx)&&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`))},J.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},J.parseIdentNode=function(){var e=this.startNode();return this.type===K.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=K.name):this.unexpected(),e},J.parsePrivateIdent=function(){var e=this.startNode();return this.type===K.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},J.parseYield=function(e){this.yieldPos||=this.start;var t=this.startNode();return this.next(),this.type===K.semi||this.canInsertSemicolon()||this.type!==K.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(K.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,`YieldExpression`)},J.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 pS=qx.prototype;pS.raise=function(e,t){var n=Cx(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},pS.raiseRecoverable=pS.raise,pS.curPosition=function(){if(this.options.locations)return new xx(this.curLine,this.pos-this.lineStart)};var mS=qx.prototype,hS=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};mS.enterScope=function(e){this.scopeStack.push(new hS(e))},mS.exitScope=function(){this.scopeStack.pop()},mS.treatFunctionsAsVarInScope=function(e){return e.flags&kx||!this.inModule&&e.flags&Ox},mS.declareName=function(e,t,n){var r=!1;if(t===Ux){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&Ox&&delete this.undefinedExports[e]}else if(t===Gx)this.currentScope().lexical.push(e);else if(t===Wx){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&Nx&&s.lexical[0]===e)||!this.treatFunctionsAsVarInScope(s)&&s.functions.indexOf(e)>-1){r=!0;break}if(s.var.push(e),this.inModule&&s.flags&Ox&&delete this.undefinedExports[e],s.flags&zx)break}r&&this.raiseRecoverable(n,`Identifier '`+e+`' has already been declared`)},mS.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)},mS.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},mS.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(zx|Lx|Ix))return t}},mS.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(zx|Lx|Ix)&&!(t.flags&Mx))return t}};var gS=function(e,t,n){this.type=``,this.start=t,this.end=0,e.options.locations&&(this.loc=new Sx(e,n)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},_S=qx.prototype;_S.startNode=function(){return new gS(this,this.start,this.startLoc)},_S.startNodeAt=function(e,t){return new gS(this,e,t)};function vS(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}_S.finishNode=function(e,t){return vS.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},_S.finishNodeAt=function(e,t,n,r){return vS.call(this,e,t,n,r)},_S.copyNode=function(e){var t=new gS(this,e.start,this.startLoc);for(var n in e)t[n]=e[n];return t};var yS=`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`,bS=`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`,xS=bS+` Extended_Pictographic`,SS=xS,CS=SS+` EBase EComp EMod EPres ExtPict`,wS=CS,TS={9:bS,10:xS,11:SS,12:CS,13:wS,14:wS},ES={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`},DS=`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`,OS=`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`,kS=OS+` Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd`,AS=kS+` Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho`,jS=AS+` Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi`,MS=jS+` Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith`,NS={9:OS,10:kS,11:AS,12:jS,13:MS,14:MS+` `+yS},PS={};function FS(e){var t=PS[e]={binary:vx(TS[e]+` `+DS),binaryOfStrings:vx(ES[e]),nonBinary:{General_Category:vx(DS),Script:vx(NS[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 IS=0,LS=[9,10,11,12,13,14];IS<LS.length;IS+=1){var RS=LS[IS];FS(RS)}var Y=qx.prototype,zS=function(e,t){this.parent=e,this.base=t||this};zS.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},zS.prototype.sibling=function(){return new zS(this.parent,this.base)};var BS=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=PS[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};BS.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)},BS.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,`Invalid regular expression: /`+this.source+`/: `+e)},BS.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},BS.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},BS.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)},BS.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},BS.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)},BS.prototype.eat=function(e,t){return t===void 0&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},BS.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},Y.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 VS(e){for(var t in e)return!0;return!1}Y.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&VS(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Y.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`)}},Y.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new zS(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`)},Y.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},Y.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},Y.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},Y.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1},Y.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Y.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},Y.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)},Y.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},Y.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},Y.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},Y.regexp_eatModifiers=function(e){for(var t=``,n=0;(n=e.current())!==-1&&HS(n);)t+=yx(n),e.advance();return t};function HS(e){return e===105||e===109||e===115}Y.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)},Y.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise(`Nothing to repeat`),!1},Y.regexp_eatSyntaxCharacter=function(e){var t=e.current();return US(t)?(e.lastIntValue=t,e.advance(),!0):!1};function US(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Y.regexp_eatPatternCharacters=function(e){for(var t=e.pos,n=0;(n=e.current())!==-1&&!US(n);)e.advance();return e.pos!==t},Y.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)},Y.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}},Y.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},Y.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue=``,this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=yx(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=yx(e.lastIntValue);return!0}return!1},Y.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),WS(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function WS(e){return ex(e,!0)||e===36||e===95}Y.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),GS(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function GS(e){return tx(e,!0)||e===36||e===95||e===8204||e===8205}Y.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)},Y.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},Y.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},Y.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)},Y.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Y.regexp_eatZero=function(e){return e.current()===48&&!rC(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Y.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)},Y.regexp_eatControlLetter=function(e){var t=e.current();return KS(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function KS(e){return e>=65&&e<=90||e>=97&&e<=122}Y.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)&&qS(e.lastIntValue))return!0;r&&e.raise(`Invalid unicode escape`),e.pos=n}return!1};function qS(e){return e>=0&&e<=1114111}Y.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)},Y.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 JS=0,YS=1,XS=2;Y.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(ZS(t))return e.lastIntValue=-1,e.advance(),YS;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===XS&&e.raise(`Invalid property name`),r;e.raise(`Invalid property name`)}return JS};function ZS(e){return e===100||e===68||e===115||e===83||e===119||e===87}Y.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),YS}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return JS},Y.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){hx(e.unicodeProperties.nonBinary,t)||e.raise(`Invalid property name`),e.unicodeProperties.nonBinary[t].test(n)||e.raise(`Invalid property value`)},Y.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return YS;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return XS;e.raise(`Invalid property name`)},Y.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue=``;QS(t=e.current());)e.lastStringValue+=yx(t),e.advance();return e.lastStringValue!==``};function QS(e){return KS(e)||e===95}Y.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue=``;$S(t=e.current());)e.lastStringValue+=yx(t),e.advance();return e.lastStringValue!==``};function $S(e){return QS(e)||rC(e)}Y.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Y.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===XS&&e.raise(`Negated character class may contain strings`),!0}return!1},Y.regexp_classContents=function(e){return e.current()===93?YS:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),YS)},Y.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`)}}},Y.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||oC(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)},Y.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)},Y.regexp_classSetExpression=function(e){var t=YS,n;if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e)){n===XS&&(t=XS);for(var r=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(n=this.regexp_eatClassSetOperand(e))){n!==XS&&(t=YS);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===XS&&(t=XS)}},Y.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},Y.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?YS:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Y.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===XS&&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},Y.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},Y.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===XS&&(t=XS);return t},Y.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?YS:XS},Y.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()&&eC(n)||tC(n)?!1:(e.advance(),e.lastIntValue=n,!0)};function eC(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 tC(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}Y.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return nC(t)?(e.lastIntValue=t,e.advance(),!0):!1};function nC(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}Y.regexp_eatClassControlLetter=function(e){var t=e.current();return rC(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1},Y.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},Y.regexp_eatDecimalDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;rC(n=e.current());)e.lastIntValue=10*e.lastIntValue+(n-48),e.advance();return e.pos!==t};function rC(e){return e>=48&&e<=57}Y.regexp_eatHexDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;iC(n=e.current());)e.lastIntValue=16*e.lastIntValue+aC(n),e.advance();return e.pos!==t};function iC(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function aC(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}Y.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},Y.regexp_eatOctalDigit=function(e){var t=e.current();return oC(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function oC(e){return e>=48&&e<=55}Y.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var r=0;r<t;++r){var i=e.current();if(!iC(i))return e.pos=n,!1;e.lastIntValue=16*e.lastIntValue+aC(i),e.advance()}return!0};var sC=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new Sx(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},X=qx.prototype;X.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 sC(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},X.getToken=function(){return this.next(),new sC(this)},typeof Symbol<`u`&&(X[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===K.eof,value:t}}}}),X.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(K.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())},X.readToken=function(e){return ex(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)},X.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},X.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},X.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=lx(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())},X.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&&!cx(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())},X.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&&ux.test(String.fromCharCode(e)))++this.pos;else break loop}}},X.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)},X.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(K.ellipsis)):(++this.pos,this.finishToken(K.dot))},X.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(K.assign,2):this.finishOp(K.slash,1)},X.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=e===42?K.star:K.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++n,r=K.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(K.assign,n+1):this.finishOp(r,n)},X.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(K.assign,3):this.finishOp(e===124?K.logicalOR:K.logicalAND,2):t===61?this.finishOp(K.assign,2):this.finishOp(e===124?K.bitwiseOR:K.bitwiseAND,1)},X.readToken_caret=function(){return this.input.charCodeAt(this.pos+1)===61?this.finishOp(K.assign,2):this.finishOp(K.bitwiseXOR,1)},X.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||ox.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(K.incDec,2):t===61?this.finishOp(K.assign,2):this.finishOp(K.plusMin,1)},X.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(K.assign,n+1):this.finishOp(K.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(K.relational,n))},X.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(K.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(K.arrow)):this.finishOp(e===61?K.eq:K.prefix,1)},X.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(K.questionDot,2)}if(t===63)return e>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(K.assign,3):this.finishOp(K.coalesce,2)}return this.finishOp(K.question,1)},X.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),ex(t,!0)||t===92))return this.finishToken(K.privateId,this.readWord1());this.raise(this.pos,`Unexpected character '`+yx(t)+`'`)},X.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(K.parenL);case 41:return++this.pos,this.finishToken(K.parenR);case 59:return++this.pos,this.finishToken(K.semi);case 44:return++this.pos,this.finishToken(K.comma);case 91:return++this.pos,this.finishToken(K.bracketL);case 93:return++this.pos,this.finishToken(K.bracketR);case 123:return++this.pos,this.finishToken(K.braceL);case 125:return++this.pos,this.finishToken(K.braceR);case 58:return++this.pos,this.finishToken(K.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(K.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(K.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,`Unexpected character '`+yx(e)+`'`)},X.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)},X.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(ox.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 BS(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(K.regexp,{pattern:i,flags:o,value:c})},X.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 cC(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,``))}function lC(e){return typeof BigInt==`function`?BigInt(e.replace(/_/g,``)):null}X.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=lC(this.input.slice(t,this.pos)),++this.pos):ex(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(K.num,n)},X.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=lC(this.input.slice(t,this.pos));return++this.pos,ex(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(K.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`)),ex(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`);var a=cC(this.input.slice(t,this.pos),n);return this.finishToken(K.num,a)},X.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},X.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)):(cx(r)&&this.raise(this.start,`Unterminated string constant`),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(K.string,t)};var uC={};X.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===uC)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},X.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw uC;this.raise(e,t)},X.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===K.template||this.type===K.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(K.dollarBraceL)):(++this.pos,this.finishToken(K.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(K.template,e));if(n===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(cx(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=`
|
|
14
|
+
`;break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},X.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(K.invalidTemplate,this.input.slice(this.start,this.pos));case`\r`:this.input[this.pos+1]===`
|
|
15
|
+
`&&++this.pos;case`
|
|
16
|
+
`:case`\u2028`:case`\u2029`:++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,`Unterminated template`)},X.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
|
|
17
|
+
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return yx(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 cx(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},X.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},X.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(tx(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?ex:tx)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=yx(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},X.readWord=function(){var e=this.readWord1(),t=K.name;return this.keywords.test(e)&&(t=ax[e]),this.finishToken(t,e)},qx.acorn={Parser:qx,version:`8.18.0`,defaultOptions:wx,Position:xx,SourceLocation:Sx,getLineInfo:Cx,Node:gS,TokenType:W,tokTypes:K,keywordTypes:ax,TokContext:sS,tokContexts:cS,isIdentifierChar:tx,isIdentifierStart:ex,Token:sC,isNewLine:cx,lineBreak:ox,lineBreakG:sx,nonASCIIwhitespace:ux};function dC(e,t){return qx.parse(e,t)}g(()=>Ot(`ok`,[tr({ok:t(!0),value:on()}),tr({ok:t(!1),error:tr({kind:t(`guest_threw`),name:b().max(80),message:b().max(512),transportMessage:b().max(512).optional()})})]));var fC=g(()=>b().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),pC=fC.refine(e=>{if(e===`env`)return!1;try{return dC(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);g(()=>Gt(pC,Ne(fC).min(1))),g(()=>Gt(pC,Ne(b().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var mC=F([`read`,`write`]),hC=vp,gC=N({access:k(mC),confirm:k(hC)}),_C=F([`none`,`read`,`write`]),vC=E(gC),yC=E(_C);function bC(e){let t=vC({access:e.access,confirm:e.confirm});if(Re(t))throw new U(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function xC(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 SC(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:xC(e,t)})}function CC(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=yC(i[n]);return at(a)?a.success:`none`}async function wC(e,t,n,r,i){let a=await TC(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function TC(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=EC(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`))&&!(!n.confirm&&e.approvedWrites?.(t).includes(n.module)===!0))return e.confirm===void 0?SC(`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(),EC(e,t,n)):SC(`declined`,n)}function EC(e,t,n){let r=CC(e,t,n.module);if(r===`none`)return SC(`not-granted`,n);if(r===`read`&&n.access!==`read`)return SC(`read-only`,n)}function DC(e,t,n){let r={module:e.module,operation:e.descriptor.name,...bC(e)};return{...e,prepare:i=>Dn({try:e=>wC(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(S(t=>t===void 0?e.prepare(i):v({execute:()=>x_({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var OC=Lo();async function kC(e){let t=await Or(e);if(qi(t))return{value:t.value};let n=Ii(t.cause);if(Re(n))throw Fi(t.cause);return{issues:OC(n.success.issue).issues}}function AC(e){let t=$m(e),n=Xf(t)[`~standard`].jsonSchema,r=Qf(t),i=ip(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>kC(r(e)),encode:e=>kC(i(e))})}function jC(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function MC(e){return up(e)?AC(e):jC(e)}var NC=Symbol(`mycelium.operation`),PC=Symbol(`mycelium.module`),FC=new WeakMap,IC=new WeakMap;function LC(e){let t=Object.freeze({[NC]:!0}),n=MC(e.input),r=e.output===void 0?void 0:MC(e.output),i={replay:e.replay??`unsafe`,...bC(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new _b(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 Tb({reason:`Capability output failed its declared schema`,rawCause:new vb(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 FC.set(t,a),t}function RC(e){let t=Ne(fC).safeParse(e.namespace??[]);if(!t.success)throw new U(`Invalid module namespace`);let n=Object.freeze({[PC]:!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 IC.set(n,i),n}function zC(e){return IC.has(e)}function BC(e){return FC.get(e)}function VC(e){return IC.get(e)}function HC(e,t,n){let r=VC(e);if(r===void 0)throw new U(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(zC(a)){let n=VC(a);if(n===void 0)throw new U(`Unknown child module registration`);i[e]=HC(a,t,[r,...n.namespace].join(`.`));continue}let o=BC(a);if(o===void 0)throw new U(`Unknown operation registration: ${e}`);let s=Object.freeze({[NC]:!0});FC.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 UC(RC(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 UC(e,t){let n=VC(e);if(n===void 0)throw new U(`Unknown module registration`);let r=Object.freeze({[PC]:!0});return IC.set(r,Object.freeze({...n,grantKey:t})),r}function WC(e,t){if(t.length===0||t.length>160)throw new U(`Grant key must be non-empty and bounded`);return UC(e,t)}function GC(e,t){return HC(e,t,``)}function KC(e,t){return e<t?-1:+(e>t)}function qC(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var JC=160;function YC(e){if(e.length===0||e.length>JC)throw new U(`Module id must be non-empty and bounded`)}function XC(e){if(!e.split(`.`).every(e=>fC.safeParse(e).success))throw new U(`Operation key must be a path segment or a dotted relative path`)}function ZC(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function QC(e){let t=ZC(e);return pC.safeParse(t).success?t:`module_${t}`}function $C(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`?ZC(i.name):QC(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 ew=14695981039346656037n,tw=1099511628211n,nw=18446744073709551615n;function rw(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*tw&nw,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*tw&nw,n=(n^BigInt(r>>>8&255))*tw&nw}return n}function iw(e,t,n){let r=rw(ew,e),i=[...t.entries()].sort(([e],[t])=>KC(e,t));for(let[e,t]of i)r=rw(r,e),r=rw(r,t);let a=[...n].sort((e,t)=>KC(e.id,t.id));for(let e of a)r=rw(r,e.id),r=rw(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function aw(){return[ub,lb,db]}function ow(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(XC(t),zC(o)){let s=VC(o);if(s===void 0)throw new U(`Unknown child module registration`);return ow(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=BC(o);if(s===void 0)throw new U(`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 sw(e,t=[]){let n=e.map(e=>{let t=VC(e);if(t===void 0)throw new U(`Unknown module registration`);return YC(t.id),t}).sort((e,t)=>KC(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new U(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=$C(n,`transport`),a=$C(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new U(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new U(`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 U(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new U(`Missing namespace path: ${e.id}`);return ow(e.grantKey,e,t,n,e.description)}).sort((e,t)=>KC(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new U(`Duplicate operation path`);for(let e of aw()){if(c.has(e.path))throw new U(`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 U(`Operation conflicts with namespace: ${e}`)}let l;try{l=ob({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}),...aw()]})}catch(e){throw new U(qC(e))}let u=iw(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 cw(){return null}var lw=Lt(),uw=g(()=>Ar([_t(),b(),Oe(),Yn()])),dw=g(()=>Gt(b(),on())),fw=g(()=>gr({timeoutMs:Yn().int().min(1).max(9e5).optional(),abortGraceMs:Yn().int().min(1).max(3e4).optional()}).strict().optional()),pw=64,mw=262144,hw=8,gw=new TextEncoder,_w=e=>{e(v(void 0))};function vw(e){let t=fw.safeParse(e);if(!t.success)throw new U(`Execution policy is invalid`);return Object.freeze({timeoutMs:t.data?.timeoutMs??18e4,abortGraceMs:t.data?.abortGraceMs??5e3})}function yw(){let e=0;return Object.freeze({createGroup:()=>{let t=0,n=new Set,r=Bn(e=>t===0?(e(v(void 0)),x(()=>void 0)):(n.add(e),x(()=>n.delete(e))));return Object.freeze({start:r=>Lr(i=>x(()=>e>=hw?!1:(e+=1,t+=1,!0)).pipe(S(a=>a?re(i(r).pipe(Gn(x(()=>{if(--e,--t,t===0){let e=[...n];n.clear(),e.forEach(_w)}})))):y(new Ob({namespace:`execute`,operation:`admission`,cause:{kind:`Unavailable`,message:`Sandbox execution capacity unavailable`}}))))),awaitIdle:r})}})}function bw(e,t=0){if(t>pw)throw Error(`JSON value exceeds the nesting bound`);let n=uw.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>bw(e,t+1));let r=dw.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,bw(n,t+1)]))}function xw(e){return lw.parse(bw(e))}function Sw(e){let t=JSON.stringify(xw(e)),n=gw.encode(t).byteLength;if(n>mw)throw new Eb({size:n});return Object.freeze({text:t})}function Cw(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 xw(await r(i))}catch(t){throw Pb(t)?t:t instanceof H?new Ob({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof _b?new Ob({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Le({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function ww(e){return Bn(t=>{let n=t.bind(void 0,w);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),x(e.removeEventListener.bind(e,`abort`,n))})}function Tw(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 Ew(e,t,n){return e===`deadline_exceeded`?new xb({limitMs:t,elapsedMs:n??0}):new Sb({by:`caller`})}function Dw(e){return ma.pipe(Xe(t=>t-e))}function Ow(e){return ma.pipe(S(t=>Wn(()=>{let n=e.executionId,r=new AbortController,a,o=e=>{a===void 0&&(a=e,r.abort())},s=()=>{if(r.signal.aborted)throw Ew(a,e.policy.timeoutMs)},l=Tw(e.callerSignal,()=>{o(`cancelled`)}),u={executionId:n,deadlineAt:t+e.policy.timeoutMs,signal:r.signal,images:e.images};e.toolCallId!==void 0&&Object.assign(u,{toolCallId:e.toolCallId});let d=Object.freeze(u),f=Wn(()=>r.signal.aborted?Dw(t).pipe(S(t=>y(Ew(a,e.policy.timeoutMs,t)))):e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:Cw(e.createBindings(d),s),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(kr(e=>Ni(e)?Bt(e):y(Fb(Fi(e)))))),p=t=>gg(t).pipe(Jn({duration:e.policy.abortGraceMs,orElse:()=>y(a===`deadline_exceeded`?new xb({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new Sb({by:`caller`,acknowledged:!1}))})),m,ee=!1,te=r=>(ee=!0,Dw(t).pipe(S(t=>{let i=Fb(r),a=i instanceof xb?new xb({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=Ab(a,n),s=Gt(b(),Lt()).parse(Lb(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??cw(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=Wn(()=>e.sandbox.onFailure?.(c)??w);return We(`sandbox_failure`,c).pipe(er({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),Wt(o._tag===`Unknown`?La(Ra(Ia(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(Wt(We(`sandbox_health_alert`).pipe(er({ref:n,adapter:c.adapter})))):w),Wt(l.pipe(kr(e=>We(`sandbox_failure_record_failed`,e)))),yr(o))})));return i(function*(){if(r.signal.aborted){let n=yield*Dw(t);return yield*y(Ew(a,e.policy.timeoutMs,n))}m=yield*e.backingWork.start(f);let n=yield*It(mg(m).pipe(Xe(e=>Object.freeze({kind:`settled`,exit:e}))),It(Cr(e.policy.timeoutMs).pipe(yr(Object.freeze({kind:`deadline`}))),ww(r.signal).pipe(yr(Object.freeze({kind:`cancelled`})))));if(n.kind===`settled`)return yield*c(n.exit,{onFailure:n=>a===void 0?Bt(n):Dw(t).pipe(S(t=>y(Ew(a,e.policy.timeoutMs,t)))),onSuccess:e=>Sn({try:()=>Sw(e),catch:t=>Pb(t)?t:new Db({kind:Ib(e),rawCause:t})})});n.kind===`deadline`&&o(`deadline_exceeded`);let i=yield*Dw(t);return yield*p(m).pipe(Wt(y(Ew(a,e.policy.timeoutMs,i))))}).pipe(Me(()=>(o(`cancelled`),(m===void 0?w:gg(m).pipe(ur(e.policy.abortGraceMs),$t)).pipe(Wt(Wn(()=>ee?w:te(new Sb({by:`operator`})).pipe($t))))))).pipe(an(e=>te(e).pipe(S(y))),Gn(x(l)))})))}var kw=[/prompt (?:is )?too long/i,/prompt exceeds max length/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \(\d+ tokens\)/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/model_context_window_exceeded/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i],Aw=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,jw=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function Mw(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!jw.some(t=>t.test(e.errorMessage))&&(kw.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&Aw.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 Nw(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function Pw(e){return new RegExp(e.join(`|`),`i`)}var Fw=Pw([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`]),Iw=Pw(`overloaded,currently experiencing high demand,rate.?limit,too many requests,429,500,502,503,504,520,524,service.?unavailable,server.?error,internal.?error,provider.?returned.?error,exceeded request buffer limit while retrying upstream,network.?error,connection.?error,connection.?refused,connection.?lost,other side closed,fetch failed,getaddrinfo,ENOTFOUND,EAI_AGAIN,upstream.?connect,reset before headers,socket hang up,socket connection was closed,timed? out,timeout,terminated,websocket.?closed,websocket.?error,ended without,stream ended before message_stop,stream ended before a terminal response event,http2 request did not get a response,retry delay,you can retry your request,try your request again,please retry your request,ResourceExhausted,subscription_sharing_usage_unavailable,subscription_sharing_user_unavailable`.split(`,`)),Lw=6e4;function Rw(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 zw=class extends Error{constructor(){super(`Aborted`)}};function Bw(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new zw);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new zw)},{once:!0})})}async function Vw(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||!Hw(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=Rw(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await Bw(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof zw){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function Hw(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!Fw.test(t)&&Iw.test(t)}var Uw={assign:0,create:0,clone:0,discard:0,update:0};function Ww(e){return Kw(e,null)}function Gw(e){return Kw(typeof e,`object`)&&!Ww(e)}function Kw(e,t){return e===t}function qw(e){return Kw(e,`__proto__`)||Kw(e,`constructor`)||Kw(e,`prototype`)}function Jw(e,t){return qw(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function Yw(e){return Object.getOwnPropertyNames(e)}var Xw={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function Zw(){return Xw}function Qw(e){return Zw().immutableTypes?Object.freeze(e):e}function $w(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 eT(e,t){return{...e,...t}}function tT(e,t,n={}){Uw.create+=1;let r=eT(t,n);return Qw(Zw().enumerableKind?eT(r,e):$w(r,e))}function nT(e){return Gw(e)}function rT(e){return nT(e)&&Jw(e,`~optional`)}function iT(e){return Yw(e).filter(t=>!rT(e[t]))}function aT(e,t={}){let n=iT(e);return tT({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var oT;(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`})(oT||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var sT=new Float64Array(1);new DataView(sT.buffer),new Uint8Array(sT.buffer),new TextEncoder;var cT=`-?(?:0|[1-9][0-9]*)`,lT=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function uT(e){return tT({"~kind":`String`},{type:`string`},e)}var dT=`^${cT}$`;`${lT}`;function fT(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var pT=[...fT(97,122),...fT(65,90)],mT=[`0`,...fT(49,57)];[...mT],[...pT,...mT],[...mT],new RegExp(dT);var hT={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},gT=3e5,_T=1e3;function vT(e,t){return Mw(e,t)}var yT=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),bT=N({_tag:A(`MuleError`),phase:F([`model`,`tool`,`control`,`listener`]),message:j,cause:O(hp)}),xT=e=>Zf(bT)(e),ST=(e,t)=>({kind:e,value:`mule_${e}_${oh()}`,parent:t}),CT=()=>w;function wT(e,t){let n={role:`toolResult`,toolCallId:e.id,toolName:e.name,content:t.content,isError:t.isError,timestamp:Date.now()};return t.details!==void 0&&(n.details=t.details),t.usage!==void 0&&(n.usage=t.usage),n}var TT=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function ET(e,t){return e.find(e=>e.descriptor.name===t.name)}function DT(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function OT(e,t,n,r,a){let o=ST(`tool_call`,r);return i(function*(){if(yield*a({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:o,call:t}),e===void 0){let e=TT(`Tool "${t.name}" not found`),i={call:t,identity:o,result:e};return yield*DT(i,n,r,a),{kind:`finalized`,value:i}}let i=yield*et(e.prepare(t));if(Re(i)){let e=TT(i.failure.message,i.failure.terminate),s={call:t,identity:o,result:e};return yield*DT(s,n,r,a),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:o,tool:i.success}})}function kT(e,t,n,r){return i(function*(){let i,a;yield*R_(k_(e.tool.execute()),o=>Re(o)?(a=o.failure,w):i===void 0?o.success.type===`result`?(i=o.success.result,w):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):w);let o=a===void 0?i??TT(`Tool "${e.call.name}" returned no result`):TT(a.message),s={call:e.call,identity:e.identity,result:o};return yield*DT(s,t,n,r),s})}function AT(e,t,n,r){let a=wT(e.call,e.result),o=ST(`tool_result`,e.identity);return i(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:o,value:a}),yield*r({type:`message_end`,run:t,turn:n,message:o,value:a}),a})}function jT(e,t,n,r,a){let o=t.tools??[],s=t.toolExecution===`sequential`||e.some(e=>ET(o,e)?.executionMode===`sequential`);return i(function*(){let t=e=>e.kind===`finalized`?v(e.value):kT(e,n,r,a),c=s?yield*Rr(e,e=>S(OT(ET(o,e),e,n,r,a),t)):yield*i(function*(){let i=yield*Rr(e,e=>OT(ET(o,e),e,n,r,a));return yield*On(i.map(t),{concurrency:`unbounded`})});return{messages:yield*Rr(c,e=>AT(e,n,r,a)),terminate:c.length>0&&c.every(e=>e.result.terminate===!0)}})}var MT=e=>TT(`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 NT(e,t,n,r){return i(function*(){let a=yield*Rr(e,e=>i(function*(){let i=ST(`tool_call`,n),a={call:e,identity:i,result:MT(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*DT(a,t,n,r),a}));return yield*Rr(a,e=>AT(e,t,n,r))})}function PT(e,t){return Dn({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=>yT(`model`,`Pi model stream failed`,e)})}function FT(e,t){return t===void 0?e:e.pipe(Jn({duration:t,orElse:()=>y(yT(`model`,`Model stream was idle for ${String(t)} ms; the provider connection stopped responding. Retry the run.`))}))}function IT(e,t,n,r,a,o){let s=ST(`message`,r);return Yt(i(function*(){let i=new AbortController;yield*hr(()=>x(()=>{i.abort(`Mule model scope closed`)}));let c=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,l={...e.streamOptions,signal:i.signal};c!==void 0&&(l.apiKey=c);let u=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*a({type:`model_prompt`,run:n,turn:r,attempt:o,systemPrompt:u}));let d={systemPrompt:u,messages:t},f=(e.tools??[]).map(e=>e.descriptor);f.length>0&&(d.tools=f);let p=yield*FT(Dn({try:async()=>(e.stream??(await ei(async()=>{let{streamSimple:e}=await import(`./compat-fz0ZcRJH.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,19,20,21]))).streamSimple)(e.model,$r(d),l),catch:e=>yT(`model`,`Pi model stream could not start`,e)}),e.modelStreamIdleTimeoutMs),m={started:!1,terminal:void 0},ee=yield*wr(x(()=>p[Symbol.asyncIterator]()),e=>Dn({try:()=>(i.abort(`Mule model stream closed`),new Promise(t=>{let n=setTimeout(t,_T);Promise.resolve(e.return?.()).then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})),catch:e=>yT(`model`,`Pi model stream failed`,e)}).pipe(Nn)),te=e=>{switch(e.type){case`start`:return t.push(e.partial),m.started=!0,a({type:`message_start`,run:n,turn:r,message:s,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 m.started&&(t[t.length-1]=e.partial),a({type:`message_update`,run:n,turn:r,message:s,value:e.partial,event:e});case`done`:return m.terminal=e.message,w;case`error`:return m.terminal=e.error,w}},ne=()=>FT(PT(ee,i),e.modelStreamIdleTimeoutMs),re=yield*ne();for(;!re.done;)yield*te(re.value),re=yield*ne();let ie=m.terminal??(yield*FT(Dn({try:()=>p.result(),catch:e=>yT(`model`,`Pi model stream did not settle`,e)}),e.modelStreamIdleTimeoutMs));return m.started?t[t.length-1]=ie:(t.push(ie),yield*a({type:`message_start`,run:n,turn:r,message:s,value:ie})),yield*a({type:`message_end`,run:n,turn:r,message:s,value:ie}),{identity:s,message:ie}}))}function LT(e,t,n,r,a){return i(function*(){let i=yield*gn(),o=hn(i),s=$n(i),c,l=0,u,d=t=>e.onRetry===void 0?void 0:s(e.onRetry(t)),f={onRetryScheduled:async(t,i,a,o)=>{let s=c===void 0?void 0:e.retryAfterMs?.(c.message),l=s!==void 0&&Number.isSafeInteger(s)&&s>=0&&s<=6e4?Math.max(0,s-a):0;await d({type:`retry_scheduled`,run:n,turn:r,attempt:t,maxAttempts:i,delayMs:a+l,errorMessage:o}),l>0&&await new Promise(e=>{let t=setTimeout(()=>{u?.removeEventListener(`abort`,n),e()},l),n=()=>{clearTimeout(t),e()};u?.addEventListener(`abort`,n,{once:!0}),u?.aborted&&n()})},onRetryAttemptStart:()=>d({type:`retry_attempt_started`,run:n,turn:r,attempt:l}),onRetryFinished:(e,t,i)=>d(i===void 0?{type:`retry_finished`,run:n,turn:r,attempt:t,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:t,success:e,finalError:i})},p=yield*Dn({try:i=>(u=i,Vw(async()=>{if(c!==void 0){let e=t.indexOf(c.message);e!==-1&&t.splice(e,1)}let u=o(IT(e,t,n,r,a,++l)),d=()=>{o(gg(u))};i.aborted?d():i.addEventListener(`abort`,d,{once:!0});let f=await s(mg(u));if(i.removeEventListener(`abort`,d),Ji(f)){let e=Li(f.cause);throw kt(e)?e.value:Fi(f.cause)}return c=f.value,c.message},e.retry,i,f)),catch:e=>xT(e)?e:yT(`model`,`Pi retry loop failed`,e)});if(c===void 0)return yield*or(`streamTurnWithRetry: retryAssistantCall settled without calling produce`);let m=c;if(p!==m.message){let e=t.indexOf(m.message);e!==-1&&(t[e]=p)}return{identity:m.identity,message:p}})}var RT=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function zT(e,t,n,r,a,o){return Rr(e,e=>i(function*(){let i=ST(`message`,a);t.push(e),n.push(e),yield*o({type:`message_start`,run:r,turn:a,message:i,value:e}),yield*o({type:`message_end`,run:r,turn:a,message:i,value:e})})).pipe($t)}function BT(e,t,n,r,a,o,s){return i(function*(){yield*s({type:`turn_start`,run:r,turn:a}),yield*zT(o,t,n,r,a,s);let i=yield*LT(e,t,r,a,s),c=RT(i.message)!==`completed`,l=i.message.content.filter(e=>e.type===`toolCall`),u=l.length===0||c?{messages:[],terminate:!1}:i.message.stopReason===`length`?{messages:yield*NT(l,r,a,s),terminate:!1}:yield*jT(l,e,r,a,s);return t.push(...u.messages),n.push(i.message,...u.messages),yield*s({type:`turn_end`,run:r,turn:a,message:i.message,toolResults:u.messages}),{message:i.message,toolResults:u.messages,terminate:u.terminate}})}function VT(e,t,n,r,a,o){let s=ST(`turn`,a);return i(function*(){if(RT(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let c=yield*Rr(t.tools,n=>i(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=ET(e.tools??[],n.call),i;if(t.message.stopReason!==`length`&&(n.state===`pending`||n.state===`started`&&n.replay===`safe`&&r?.replay===`safe`)){let e=yield*OT(r,n.call,a,s,o);i=e.kind===`finalized`?e.value:yield*kT(e,a,s,o)}else i={call:n.call,identity:ST(`tool_call`,s),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?MT(n.call):TT(`Interrupted by a restart; it may or may not have completed; check before retrying.`)},yield*o({type:`tool_execution_start`,replay:`unsafe`,run:a,turn:s,toolCall:i.identity,call:i.call}),yield*DT(i,a,s,o);return{message:yield*AT(i,a,s,o),terminate:i.result.terminate===!0,recorded:!1}})),l=c.filter(({recorded:e})=>!e).map(({message:e})=>e);return n.push(...l),r.push(...l),{message:t.message,toolResults:c.map(({message:e})=>e),terminate:c.length>0&&c.every(({terminate:e})=>e)}})}function HT(e,t,n,r){return i(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 UT(e,t,n,r,a,o){return i(function*(){return yield*o({type:`run_end`,run:e,terminal:t,outcome:a}),{status:a,run:e,terminal:t,message:n,messages:r}})}function WT(e,t=CT){return i(function*(){let n=yield*Cg(1),r={started:!1,ended:!1},i=e=>Wn(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(un(()=>x(()=>{e.type===`run_start`&&(r.started=!0)}))),a=ST(`run`),o=ST(`terminal`,a);return yield*KT(e,i,a,o).pipe(wt(e=>{let t=GT(e);return!r.started||r.ended||t===void 0?w:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Nn)}))})}function GT(e){if(qi(e))return;if(Ni(e.cause))return`cancelled`;let t=Li(e.cause);if(!(kt(t)&&t.value.phase===`listener`))return`failed`}function KT(e,t,n,r){return i(function*(){let i=[...e.messages],a=[],o=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()],s,c;if(yield*t({type:`run_start`,run:n}),e.resume!==void 0){let s=yield*VT(e,e.resume,i,a,n,t),c=RT(s.message),l=c===`completed`?yield*HT(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*UT(n,r,s.message,a,c,t);o.push(...l.pending)}do{let l=yield*BT(e,i,a,n,ST(`turn`,n),o,t);s=l.message;let u=RT(l.message);if(u!==`completed`)return yield*UT(n,r,l.message,a,u,t);if(e.prepareNextTurn!==void 0&&!l.terminate&&l.message.content.some(e=>e.type===`toolCall`)){let t=yield*e.prepareNextTurn({message:l.message,toolResults:l.toolResults,context:i,newMessages:a});t!==void 0&&i.splice(0,i.length,...t)}let d=yield*HT(e,l,i,a);o=[...d.pending],c=d.continue}while(c);return yield*UT(n,r,s,a,`completed`,t)})}var qT={run:WT},JT=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 Ob({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)}},YT=N({code:j}),XT="Run async JavaScript in the sandbox. To enumerate all available operations, use forage.list({limit:50}) and follow nextCursor until null; optionally filter by namespace. Use await forage.search({ query: ... }) with short operation keywords, such as read or shell. Search matches operation names and descriptions; if no results match, retry with one relevant keyword. Then use await forage.describe({ path: ... }) to inspect the input before calling an operation. Describe known paths directly. For multiline shell commands, put the command in a JavaScript template literal, for example const command = `pwd\\nprintf done`; a physical newline inside a double-quoted JavaScript string is invalid source. Code is evaluated as JavaScript before shell commands run: if a shell command needs a backslash, write it doubled in the JavaScript string (for example, `\\\\(` passes `\\(` to the shell; `\\(` becomes `(`). For file edits, prefer Files operations when available. Explicitly return the final value. For shell or process results, inspect status, exitCode, and stderr when present before treating the operation as successful. Each execute call runs in a fresh sandbox: no variable, function, or other global survives from a previous call, so redefine any helpers you need every time, or persist state to a file and read it back instead.";function ZT(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await wC(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function QT(e,t,n,r){let i=new Map;for(let a of e){let e=a.namespace,o=a.name,s=i.get(e)??new Map;s.set(o,ZT(a,t,n,r)),i.set(e,s)}return Object.freeze(Object.fromEntries([...i].map(([e,t])=>[e,Object.freeze(Object.fromEntries(t))])))}function $T(e,t){let n=e.safeParse(t);if(!n.success)throw new _b(n.error.issues);return n.data}function eE(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list($T(qv,t))),describe:t=>Promise.resolve().then(()=>e.describe($T(Kv,t))),search:t=>Promise.resolve().then(()=>e.search($T(Gv,t)))})}function tE(e,t,n,r,i){return Object.freeze({...QT(e,n,r,i),forage:eE(t)})}function nE(e,t,n,r,i,a,o,s){let c=n.execution??vw(void 0),l=new JT,u=(u,d,f,p)=>Ow({executionId:u,toolCallId:p,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>tE(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>Wn(()=>{let n=oh();return u(n,e,t).pipe(Gn(x(()=>{l.dispose(n)})))}),f=(e,t)=>Wn(()=>{let n=oh(),r=()=>l.drain(n);return u(n,e,void 0,t).pipe(bt({onSuccess:e=>v(rE({text:e.text,isError:!1},r())),onFailure:e=>{let t=r();return e instanceof Eb&&t.length>0?v(rE({text:jb(e),isError:!0},t)):y(iE(e))}}),Gn(x(()=>{l.dispose(n)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:XT,parameters:aT({code:uT()},{additionalProperties:!1})},prepare:e=>Qf(YT)(e.arguments).pipe(Xe(({code:t})=>({execute:()=>g_(f(t,e.id))})),we(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function rE(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,details:{images:t.map(e=>({bytes:e.bytes,mimeType:e.mimeType,path:e.path}))},isError:e.isError}}}function iE(e){return{_tag:`MuleError`,phase:`tool`,message:Pb(e)?jb(e):e.message}}function aE(e,t){return e<t?-1:+(e>t)}var oE=128,sE=g(()=>b().min(1).max(160)),cE=g(()=>gr({version:b().min(1).max(160),modules:Ne(on())})),lE=1e3;function uE(e){if(e.length>oE)throw new U(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>aE(e.id,t.id)),n=new Set;for(let e of t){if(!sE.safeParse(e.id).success)throw new U(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new U(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function dE(e){if(e>lE)throw new U(`Candidate module count exceeds bound`)}function fE(e,t){let n=cE.safeParse(e);if(!n.success)throw new U(`Capability source snapshot must have a non-empty bounded version`);dE(t+n.data.modules.length)}function pE(e,t,n,r,a){return Lr(o=>i(function*(){let i=t=>Dn({try:()=>t.release(),catch:()=>new gb(e.id,`release`)}).pipe(an(e=>x(()=>{n.push(e)}))),s=yield*Sn({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(a===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:a}).then(e=>Hi(e),()=>Wi(new gb(e.id,`acquire`)))}},catch:()=>new gb(e.id,`acquire`)});yield*da(t,De(()=>s.outcome).pipe(S(e=>qi(e)?i(e.value):w)));let c=yield*o(De(()=>s.outcome)).pipe(Me(()=>x(()=>{s.controller.abort()})));return Ji(c)?yield*Bt(c.cause):c.value}))}function mE(e){return i(function*(){let t=yield*Sn({try:()=>uE(e.sources),catch:e=>e instanceof U?e:new U(`Capability sources are invalid`)});yield*Sn({try:()=>{dE(e.modules.length)},catch:e=>e instanceof U?e:new U(`Static capability modules are invalid`)});let n=yield*sa(),r=[],a=!1,o=[...e.modules],s=[];return yield*i(function*(){for(let i of t){let t=yield*pE(i,n,r,()=>{a=!0},e.session);yield*Sn({try:()=>{fE(t.snapshot,o.length)},catch:e=>e instanceof U?e:new U(`Capability source snapshot is invalid`)}),o.push(...t.snapshot.modules),s.push({id:i.id,version:t.snapshot.version})}let c=e.precompiled??(yield*Sn({try:()=>sw(o,s),catch:e=>e instanceof U?e:new U(`Capability compilation failed`)})),l=e.backingWork.createGroup(),u=nE(c.operations,c.catalog,e.sandbox,l,c.moduleAliases,c.namespacePaths,e.session?.sessionId??null,e.access),d=!1;return Object.freeze({compiled:c,executeDoor:u,isStale:()=>a,close:()=>i(function*(){d||(d=!0,yield*l.awaitIdle,yield*pa(n,Ki));let e=r[0];e!==void 0&&(yield*y(e))})})}).pipe(wt(e=>qi(e)?w:pa(n,e)))})}var hE=2;function gE(e){return i(function*(){for(let t=0;t<hE;t+=1){let t=yield*mE(e);if(!t.isStale())return t;yield*t.close()}return yield*y(new gb(void 0,`stale`))})}function _E(e,t,n){return Lr(r=>r(e.take(1)).pipe(S(()=>x(t).pipe(Gn(e.release(1)))),S(n)))}function vE(e,t){return Ut(e.candidate.close().pipe(bt({onFailure:t=>ra(e.settled,t).pipe(Wt(y(t))),onSuccess:()=>ia(e.settled,void 0).pipe(Wt(x(()=>{t.delete(e)})))})))}function yE(e,t){return e.runCleanup?vE(e.installed,t):ta(e.installed.settled)}function bE(e,t){return On(e.map(e=>yE(e,t).pipe(Cn)),{concurrency:`unbounded`}).pipe(S(e=>{let t=e.find(Ji);return t===void 0?w:Bt(t.cause)}))}function xE(e){return i(function*(){let t=yield*Cg(1),n=yw(),r=yield*Sn({try:()=>vw(e.execution),catch:e=>e instanceof U?e:new U(`Execution policy is invalid`)}),a=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:r}),o=yield*Sn({try:()=>sw(e.modules),catch:e=>e instanceof U?e:new U(`Capability compilation failed`)}),s=yield*Sn({try:()=>Object.freeze(e.tools.map(t=>DC(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof U?e:new U(`Direct tool labels are invalid`)}),c,l=new Set,u=!1;if(e.sources.length===0){let t={candidate:yield*gE({...e,sandbox:a,backingWork:n,precompiled:o}),settled:yield*ea(),leases:0,retired:!1,closing:!1};c=t,l.add(t)}let d=()=>_E(t,()=>(u=!0,[...l].map(e=>{e.retired=!0;let t=e.leases===0&&!e.closing;return t&&(e.closing=!0),{installed:e,runCleanup:t}})),e=>bE(e,l));return yield*hr(()=>d().pipe(dr)),Object.freeze({acquire:()=>t.withPermits(1)(i(function*(){if(u)return yield*y(new hb);if(c===void 0||c.candidate.isStale()){let t=yield*gE({...e,sandbox:a,backingWork:n}),r=c,i={candidate:t,settled:yield*ea(),leases:0,retired:!1,closing:!1};c=i,l.add(i),r!==void 0&&(r.retired=!0,r.leases===0&&!r.closing&&(r.closing=!0,yield*vE(r,l)))}let r=c;r.leases+=1;let i,o=()=>_E(t,()=>{if(i!==void 0)return i?{installed:r,runCleanup:!1}:void 0;if(--r.leases,i=r.retired&&r.leases===0&&!r.closing,i)return r.closing=!0,{installed:r,runCleanup:!0}},e=>e===void 0?w:yE(e,l));return yield*hr(()=>o().pipe(dr)),Object.freeze({revision:r.candidate.compiled.revision,catalog:r.candidate.compiled.catalog,executeDoor:r.candidate.executeDoor,effectExecuteTool:r.candidate.executeDoor.effectTool,tools:s,release:o})})),close:d})})}function SE(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>Ut(Dn({try:()=>e.execute(t,n),catch:Fb}))})}function CE(e){return xE({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(Xe(e=>Object.freeze({acquire:()=>e.acquire().pipe(Xe(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function wE(e,t){let n=await Or(e,t);if(qi(n))return n.value;let r=Li(n.cause);if(kt(r))throw r.value;if(Ni(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Fi(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function TE(e){let t=await wE(sa()),n=e.onSandboxFailure;try{let r=await wE(xE({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:SE(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>De(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(la(t))),i=async e=>{let t=await wE(sa());try{let n=await wE(r.acquire().pipe(la(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??=wE(n.release().pipe(Gn(pa(t,Ki)))),i)})}catch(e){throw await wE(pa(t,Ki)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=wE(r.close().pipe(Gn(pa(t,Ki)))),a)})}catch(e){throw await wE(pa(t,Ki)),e}}var EE=Ap(()=>P([gp,vp,Qp,j,Dp(Tp(EE)),dp(Sp(j,EE))])),DE=j.check(Em(1),B(256)),OE=j.check(Em(1),B(128)),kE=N({kind:A(`sandbox_failure`),ref:DE,executionId:DE,adapter:OE,buildSha:I(OE),tag:F([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:Sp(j,EE),healthAlert:vp});function AE(e){return LC(e)}function jE(e){return RC(e)}var ME=Object.freeze({module:jE,operation:AE,make:TE,gate:GC,grantAs:WC}),NE=eh;function PE(t,n){e(We(`shiitake_operation_failed`,ii(n)).pipe(er({operation:t,errorKind:n instanceof Error?`error`:`non-error`})))}var FE=64,IE=256,LE=new WeakMap;function RE(e,t){return e===`closed`||t===`closed`?`closed`:e===`reset`||t===`reset`?`reset`:e===`durable`||t===`durable`?`durable`:`progress`}function zE(e,t){if(e.pendingCount>=IE){e.pendingCount=0,e.pendingReason=void 0,e.reset=!0;return}e.pendingCount+=1,e.pendingReason=e.pendingReason===`durable`||t===`durable`?`durable`:`progress`}function BE(e,t){if(e.closed||e.reset)return;let n=e.wake;if(n===void 0){zE(e,t);return}e.wake=void 0;try{n(t)}catch(t){PE(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function VE(e,t,n=`durable`){let r=LE.get(e);if(r!==void 0)for(let e of r)try{e(t,n)}catch(e){PE(`owner-observation-publish`,e);continue}}function HE(e){let t=new Map,n=new Set,r=LE.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===`durable`?`durable`:`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){PE(`observation-listener-close`,e)}},s=(e,r)=>{let i=e===null?n:t.get(e);if(i!==void 0)for(let e of i)BE(e,r)};return r.add(s),LE.set(e,r),Object.freeze({register:e=>Wn(()=>{if(i)return y(new V(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=FE)return y(new V(`runtime`,`rejected`,`Observation capacity is exhausted`));let r={sessionId:e,closed:!1,pendingCount:0,pendingReason:void 0,reset:!1,wake:void 0},s=t.get(e)??new Set;s.add(r),t.set(e,s),n.add(r);let c=x(()=>a(r)),l=Bn(e=>{let t=a(r);if(t!==void 0){e(v(t));return}let n=t=>{e(v(t))};return r.wake=n,x(()=>{r.wake===n&&(r.wake=void 0)})});return v(Object.freeze({pollSignal:c,awaitSignal:l,close:()=>{o(r)}}))}),close:x(()=>{if(!i){i=!0,r.delete(s),r.size===0&&LE.delete(e);for(let e of n)o(e)}})})}var UE=np(N({extension_id:j,value_json:j})),WE=np(Gm(U_)),GE=np(W_),KE=lp(Gm(U_));function qE(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
18
|
+
extension_id TEXT PRIMARY KEY
|
|
19
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention (
|
|
20
|
+
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
21
|
+
extension_id TEXT NOT NULL,
|
|
22
|
+
id TEXT NOT NULL,
|
|
23
|
+
value_json TEXT NOT NULL,
|
|
24
|
+
PRIMARY KEY (session_id, extension_id, id)
|
|
25
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_attention_owner ON session_attention(extension_id, session_id)`)}function JE(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=UE(e);return GE({...WE(t.value_json),extensionId:t.extension_id})})}function YE(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 = ? LIMIT 1`,t).toArray().length>0}function XE(e,t,n,r){if(np(N({count:z}))(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 V(`contract`,`invalid`,`Session attention capacity reached`);if(np(N({count:z}))(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 V(`contract`,`invalid`,`Extension attention capacity reached`);e.sql.exec(`INSERT INTO session_attention (session_id, extension_id, id, value_json) VALUES (?, ?, ?, ?)
|
|
26
|
+
ON CONFLICT (session_id, extension_id, id) DO UPDATE SET value_json = excluded.value_json`,t,n,r.id,KE(r))}function ZE(e,t,n,r){e.sql.exec(`DELETE FROM session_attention WHERE session_id = ? AND extension_id = ? AND id = ?`,t,n,r)}function QE(e,t,n){let r=np(N({session_id:j}));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 $E(e,t){let n=np(N({extension_id:j})),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 eD=new TextEncoder,tD=new TextDecoder,nD=/^[A-Za-z0-9_-]+$/u,rD=N({v:A(1),generation:j.pipe(L(Em(1)),L(B(128)),L(R(e=>eD.encode(e).byteLength<=128))),sequence:z.pipe(L(om(0)),L(lm(2**53-1)))}),iD={onExcessProperty:`error`},aD=E(rD,iD),oD=E(Gm(rD),iD);function sD(e){let t=aD({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(eD.encode(n).byteLength>384)return;let r=Yo(n);return eD.encode(r).byteLength<=512?r:void 0}function cD(e){if(eD.encode(e).byteLength>512||!nD.test(e))return;let t=Xo(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=tD.decode(t.success),r=oD(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&Yo(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var lD=4096,uD=new TextEncoder,dD=NE.check(R(e=>uD.encode(JSON.stringify(e)).byteLength<=lD)),fD=E(dD);function pD(e,t){if(up(e))return at(E(e)(t));let n=e[`~standard`].validate(t);if(Xn(n,`then`))throw new V(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function mD(e,t){let n=fD(t);if(Re(n))throw new V(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!pD(e.schema,n.success))throw new V(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function hD(e,t){return JSON.stringify(e)===JSON.stringify(t)}var gD=N({status:F([`accepted`,`duplicate`]),cursor:z.check(sm(0))});P([F([`accepted`,`duplicate`,`refused`]),gD,N({status:F([`accepted`,`duplicate`,`refused`]),receipt:eh})]),Di(`PostError`);var _D=j.check(Em(1),B(256));N({postKey:_D}),z.check(sm(1),lm(64)),Ch({family:`post`,version:1,kinds:{work:{prefix:`post_work`}}});var vD=N({key:_D,kind:_D,address:hp,event:hp});Gm(P([N({state:A(`pending`),envelope:vD,attempts:z.check(sm(0)),nextAttemptAt:M.check(sm(0)),jobId:k(_D),delivery:k(vD),nextKey:k(_D)}),N({state:A(`delivered`),receipt:k(eh),nextKey:k(_D)}),N({state:A(`dead`),envelope:vD,attempts:z.check(sm(0)),reason:F([`refused`,`exhausted`]),receipt:k(eh),delivery:k(vD),nextKey:k(_D)})])),N({key:j,value:j}),N({due:I(M.check(sm(0)))});var yD=j.check(Em(1),B(256)),bD=N({kind:A(`agent`),agentId:yD,sessionId:yD}),xD=N({commandId:yD,outcome:F([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:O(j.check(Em(1),B(200)))}),SD=N({key:yD,to:bD,from:bD,replyTo:Tp(bD),content:j,createdAt:M.check(sm(0)),meta:O(eh),reply:O(xD)}),CD=N({jobId:yD,sessionId:yD,commandFactId:yD,recovery:k(N({maxRecoveries:z.check(sm(0))}))}),wD=N({work:N({sessionId:yD,commandFactId:yD}),mail:k(SD)}),TD=N({work:CD,mail:k(SD)}),ED=e=>{let t=np(TD)(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:0,payload:r,state:`queued`};return t.work.recovery===void 0?i:{...i,recovery:t.work.recovery}},DD=e=>np(wD)(e.payload),OD=j.check(Em(1),B(256)),kD=N({agentId:OD,sessionId:OD,...xD.fields}),AD=`fungi_agent_reply`,jD=RegExp(`<(?=\\s*/?\\s*${AD})`,`giu`);function MD(e){return e.replace(jD,`<`)}function ND(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function PD(e){let t=[[`agent_id`,e.agentId],[`session_id`,e.sessionId],[`command_id`,e.commandId],[`outcome`,e.outcome]];return e.diagnostic!==void 0&&t.push([`diagnostic`,e.diagnostic]),`<${AD} ${t.map(([e,t])=>`${e}="${ND(t)}"`).join(` `)}>`}function FD(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:MD(e.text)}:e):MD(e.content);if(t===void 0)return{...e,content:n};let r=PD(t),i=`</${AD}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var ID={onExcessProperty:`error`},LD=new TextEncoder,RD=(e=>j.pipe(L(Em(1)),L(R(t=>LD.encode(t).byteLength<=e))))(256),zD=j.pipe(L(Wp(/^[0-9a-f]{64}$/u))),BD=Ap(()=>P([j,M,vp,gp,Tp(BD),Sp(j,BD)])),VD=N({type:A(`text`),text:j,textSignature:O(j)}),HD=N({type:A(`thinking`),thinking:j,thinkingSignature:O(j),redacted:O(vp)}),UD=N({type:A(`image`),data:j,mimeType:j}),WD=N({type:A(`toolCall`),id:j,name:j,arguments:Sp(j,BD),thoughtSignature:O(j),namespace:O(j)}),GD=N({input:M,output:M,cacheRead:M,cacheWrite:M,cacheWrite1h:O(M),reasoning:O(M),totalTokens:M,cost:N({input:M,output:M,cacheRead:M,cacheWrite:M,total:M})}),KD=N({role:A(`user`),content:P([j,Dp(Tp(P([VD,UD])))]),timestamp:M}),qD=N({role:A(`user`),content:j,timestamp:M}),JD=N({name:j,description:j,parameters:Sp(j,BD),constrainedSampling:O(P([A(!1),N({type:A(`json_schema`),strict:F([`prefer`,`require`])}),N({type:A(`grammar`),variants:N({openai_lark:O(j),openai_regex:O(j)})})]))}),YD=P([N({role:A(`system`),content:P([j,Dp(Tp(VD))]),sections:O(Sp(j,P([j,gp]))),toolsAdded:O(Dp(Tp(JD))),toolsRemoved:O(Dp(Tp(N({name:j})))),timestamp:M}),KD,N({role:A(`assistant`),content:Dp(Tp(P([VD,HD,WD]))),api:j,provider:j,model:j,responseModel:O(j),responseId:O(j),diagnostics:O(Dp(Tp(N({type:j,timestamp:M,error:O(N({name:O(j),message:j,stack:O(j),code:O(P([j,M]))})),details:O(Sp(j,BD))})))),usage:GD,stopReason:F([`pending`,`stop`,`length`,`toolUse`,`error`,`aborted`,`deferred`]),deferred:O(N({provider:j,modelId:j,api:j,id:j,expiresAt:O(M),pollAfterMs:O(M),data:O(BD)})),errorMessage:O(j),rawStopReason:O(j),providerThinkingLevel:O(j),endTurn:O(vp),timestamp:M}),N({role:A(`toolResult`),toolCallId:j,toolName:j,content:Dp(Tp(P([VD,UD]))),details:O(BD),usage:O(GD),isError:vp,timestamp:M})]),XD=F([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),ZD=Ap(()=>N({kind:XD,value:RD,parent:k(ZD)})),QD=P([N({type:A(`auto_retry_start`),run:ZD,attempt:M,maxAttempts:M,delayMs:M,errorMessage:j}),N({type:A(`auto_retry_attempt`),run:ZD,attempt:M}),N({type:A(`auto_retry_end`),run:ZD,attempt:M,success:vp,finalError:O(j)})]),$D=N({core:zD,extensions:Tp(wp([RD,j.pipe(L(Wp(/^sha256:[0-9a-f]{64}$/u)))])).pipe(L(B(128)))}),eO=N({content:Dp(Tp(P([VD,UD]))),details:k(BD),usage:k(GD),isError:vp,terminate:k(vp)}),tO={workId:RD},nO=F([`manual`,`threshold`,`overflow`]),rO=Gm(P([N({...tO,kind:A(`sandbox_failure`),event:kE}),N({kind:A(`document`),workId:gp,extensionId:RD,name:RD,valueJson:j}),N({kind:A(`model_preference`),workId:gp,preference:I(J_)}),N({...tO,kind:A(`command`),meta:O(dD),reply:O(kD),delivery:O(F([`steer`,`followUp`])),requestId:RD,targetWorkId:O(RD),receiptId:RD,message:KD,contract:$D}),N({...tO,kind:A(`command`),work:A(`compact`),instructions:O(_v),meta:O(dD),requestId:RD,receiptId:RD,timestamp:z.check(sm(0)),contract:$D}),N({kind:A(`operator`),workId:gp,requestId:RD,author:F([`operator`,`party`]),meta:O(dD),message:qD}),N({...tO,kind:A(`cancellation`),requestId:RD,receiptId:RD,targetWorkId:RD,meta:O(dD)}),N({...tO,kind:A(`model_selection`),provider:RD,model:RD,catalogRevision:RD,definitionRevision:RD,selectionPolicyRevision:RD}),N({...tO,kind:A(`run_started`),run:ZD,contract:$D}),N({...tO,kind:A(`turn_started`),run:ZD,turn:ZD}),N({...tO,kind:A(`model_prompt`),run:ZD,turn:ZD,attempt:M.pipe(L(fm()),L(om(0))),contract:$D,systemPrompt:j.pipe(L(R(e=>LD.encode(e).byteLength<=1048576)))}),N({...tO,kind:A(`message_start`),run:ZD,turn:ZD,message:ZD,role:F([`assistant`,`system`,`toolResult`,`user`])}),N({...tO,kind:A(`message`),run:ZD,turn:ZD,message:ZD,value:YD}),N({...tO,kind:A(`tool_intent`),replay:F([`safe`,`unsafe`]).pipe(Rp(v(`unsafe`))),contract:$D,run:ZD,turn:ZD,toolCall:ZD,call:WD}),N({...tO,kind:A(`tool_outcome`),run:ZD,turn:ZD,toolCall:ZD,call:WD,result:eO}),N({...tO,kind:A(`live_retry`),event:QD}),N({...tO,kind:A(`compaction`),resumesRun:O(vp),trigger:O(nO),tokensAfter:O(M),firstKeptEntryId:RD,summary:j,tokensBefore:M,usage:GD,contextRevision:RD,details:O(N({readFiles:Tp(j),modifiedFiles:Tp(j)}))}),N({...tO,kind:A(`compaction_notice`),trigger:nO,result:F([`nothing_to_compact`,`failed`]),diagnostic:O(j.check(B(200)))}),N({...tO,kind:A(`run_terminal`),run:ZD,terminal:ZD,outcome:F([`completed`,`cancelled`,`failed`])}),N({...tO,kind:A(`work_terminal`),diagnostic:O(j),outcome:F([`completed`,`interrupted`,`cancelled`,`failed`])})])),iO=Gm(hp),aO=E(rO,ID),oO=lp(iO),sO=np(rO,ID);function cO(e){return`work`in e}function lO(e){return e.kind===`command`&&!cO(e)?e:void 0}function uO(e){return cO(e)?e.timestamp:e.message.timestamp}function dO(e){return FD(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 fO(e){return FD(e.message,e.reply)}function pO(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 mO(e){return Xr(aO(e),e=>e.kind===`command`&&!cO(e)&&e.delivery===void 0?{...e,delivery:`followUp`}:e)}function hO(e){let t=oO(e);return sO(t),t}var gO=j.pipe(L(Em(1))),_O=z.pipe(L(sm(0))),vO={onExcessProperty:`error`},yO=N({value_json:j}),bO=N({state_version:z.pipe(L(sm(1))),revision:gO}),xO=N({status:F([`running`,`stopped`]),reason:I(j),stopped_at:I(_O),revision:gO}),SO=N({extension_id:gO,key:gO,due_at:_O}),CO=N({collection:gO,key:gO,value_json:j}),wO=N({sequence:_O}),TO=N({due:F([0,1]),next_due_at:I(_O)});function EO(e){return new V(`store`,`unavailable`,e)}function DO(e,t,n){let r=E(e,vO);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw EO(n);return t.success})}function OO(e){e.transactionSync(()=>{e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_records (
|
|
27
|
+
extension_id TEXT NOT NULL,
|
|
28
|
+
collection TEXT NOT NULL,
|
|
29
|
+
key TEXT NOT NULL,
|
|
30
|
+
index_value TEXT,
|
|
31
|
+
value_json TEXT NOT NULL,
|
|
32
|
+
PRIMARY KEY (extension_id, collection, key)
|
|
33
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_shiitake_extension_records_index
|
|
34
|
+
ON shiitake_extension_records(extension_id, collection, index_value, key)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_state (
|
|
35
|
+
extension_id TEXT PRIMARY KEY,
|
|
36
|
+
state_version INTEGER NOT NULL CHECK (state_version >= 1),
|
|
37
|
+
revision TEXT NOT NULL
|
|
38
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_status (
|
|
39
|
+
extension_id TEXT PRIMARY KEY,
|
|
40
|
+
status TEXT NOT NULL CHECK (status IN ('running', 'stopped')),
|
|
41
|
+
reason TEXT,
|
|
42
|
+
stopped_at INTEGER,
|
|
43
|
+
revision TEXT NOT NULL,
|
|
44
|
+
CHECK ((status = 'running') = (reason IS NULL)),
|
|
45
|
+
CHECK ((reason IS NULL) = (stopped_at IS NULL))
|
|
46
|
+
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_timers (
|
|
47
|
+
extension_id TEXT NOT NULL,
|
|
48
|
+
key TEXT NOT NULL,
|
|
49
|
+
due_at INTEGER NOT NULL CHECK (due_at >= 0),
|
|
50
|
+
PRIMARY KEY (extension_id, key)
|
|
51
|
+
)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_shiitake_extension_timers_due
|
|
52
|
+
ON shiitake_extension_timers(due_at, extension_id, key)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_settled_cursors (
|
|
53
|
+
consumer TEXT PRIMARY KEY,
|
|
54
|
+
sequence INTEGER NOT NULL CHECK (sequence >= 0)
|
|
55
|
+
)`)})}function kO(e,t,n,r){return DO(yO,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
|
|
56
|
+
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r).toArray(),`Stored extension record is invalid`)[0]?.value_json}function AO(e,t,n,r){return DO(yO,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
|
|
57
|
+
WHERE extension_id = ? AND collection = ?
|
|
58
|
+
AND (? IS NULL OR index_value = ?)
|
|
59
|
+
AND (? IS NULL OR key > ?)
|
|
60
|
+
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 jO(e,t,n,r,i,a){e.sql.exec(`INSERT INTO shiitake_extension_records
|
|
61
|
+
(extension_id, collection, key, index_value, value_json)
|
|
62
|
+
VALUES (?, ?, ?, ?, ?)
|
|
63
|
+
ON CONFLICT(extension_id, collection, key) DO UPDATE SET
|
|
64
|
+
index_value = excluded.index_value, value_json = excluded.value_json`,t,n,r,i,a)}function MO(e,t,n,r){e.sql.exec(`DELETE FROM shiitake_extension_records
|
|
65
|
+
WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r)}function NO(e,t){return DO(CO,e.sql.exec(`SELECT collection, key, value_json FROM shiitake_extension_records
|
|
66
|
+
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 PO(e,t){e.sql.exec(`DELETE FROM shiitake_extension_records WHERE extension_id = ?`,t)}function FO(e,t){let n=DO(bO,e.sql.exec(`SELECT state_version, revision FROM shiitake_extension_state
|
|
67
|
+
WHERE extension_id = ?`,t).toArray(),`Extension ledger is invalid`)[0];return n===void 0?void 0:{version:n.state_version,revision:n.revision}}function IO(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_state (extension_id, state_version, revision)
|
|
68
|
+
VALUES (?, ?, ?)
|
|
69
|
+
ON CONFLICT(extension_id) DO UPDATE SET
|
|
70
|
+
state_version = excluded.state_version, revision = excluded.revision`,t,n,r)}function LO(e,t){let n=DO(xO,e.sql.exec(`SELECT status, reason, stopped_at, revision FROM shiitake_extension_status
|
|
71
|
+
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 RO(e,t,n){e.sql.exec(`INSERT INTO shiitake_extension_status
|
|
72
|
+
(extension_id, status, reason, stopped_at, revision)
|
|
73
|
+
VALUES (?, ?, ?, ?, ?)
|
|
74
|
+
ON CONFLICT(extension_id) DO UPDATE SET status = excluded.status,
|
|
75
|
+
reason = excluded.reason, stopped_at = excluded.stopped_at,
|
|
76
|
+
revision = excluded.revision`,t,n.status,n.reason,n.stoppedAt,n.revision)}function zO(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_timers (extension_id, key, due_at)
|
|
77
|
+
VALUES (?, ?, ?)
|
|
78
|
+
ON CONFLICT(extension_id, key) DO UPDATE SET due_at = excluded.due_at`,t,n,r)}function BO(e,t,n){e.sql.exec(`DELETE FROM shiitake_extension_timers WHERE extension_id = ? AND key = ?`,t,n)}function VO(e,t,n){return DO(SO,e.sql.exec(`SELECT extension_id, key, due_at FROM shiitake_extension_timers
|
|
79
|
+
WHERE extension_id = ? AND key = ?`,t,n).toArray(),`Extension timer is invalid`)[0]?.due_at}function HO(e){return e.map(()=>`?`).join(`, `)}function UO(e,t,n,r){return t.length===0?[]:DO(SO,e.sql.exec(`SELECT extension_id, key, due_at FROM shiitake_extension_timers
|
|
80
|
+
WHERE due_at <= ? AND extension_id IN (${HO(t)})
|
|
81
|
+
ORDER BY due_at, extension_id, key LIMIT ?`,n,...t,r).toArray(),`Extension timer is invalid`).map(e=>({extensionId:e.extension_id,key:e.key,dueAt:e.due_at}))}function WO(e,t,n){if(t.length===0)return{due:!1,nextWakeAt:null};let r=HO(t),i=DO(TO,e.sql.exec(`SELECT
|
|
82
|
+
EXISTS (SELECT 1 FROM shiitake_extension_timers
|
|
83
|
+
WHERE due_at <= ? AND extension_id IN (${r})) AS due,
|
|
84
|
+
(SELECT MIN(due_at) FROM shiitake_extension_timers
|
|
85
|
+
WHERE due_at > ? AND extension_id IN (${r})) AS next_due_at`,n,...t,n,...t).toArray(),`Extension timer is invalid`)[0];if(i===void 0)throw EO(`Extension timer is unavailable`);return{due:i.due===1,nextWakeAt:i.next_due_at}}function GO(e,t){return DO(wO,e.sql.exec(`SELECT sequence FROM shiitake_settled_cursors WHERE consumer = ?`,t).toArray(),`Settled cursor is invalid`)[0]?.sequence}function KO(e,t,n){e.sql.exec(`INSERT INTO shiitake_settled_cursors (consumer, sequence) VALUES (?, ?)
|
|
86
|
+
ON CONFLICT(consumer) DO UPDATE SET sequence = MAX(sequence, excluded.sequence)`,t,n)}var qO=N({extension_id:j,name:j,initial_json:j,fork:F([`inherit-at-fork-point`,`current`,`fresh`]),max_bytes:z.pipe(L(om(0)))});function JO(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_document_specs (
|
|
87
|
+
extension_id TEXT NOT NULL, name TEXT NOT NULL, initial_json TEXT NOT NULL,
|
|
88
|
+
fork TEXT NOT NULL, max_bytes INTEGER NOT NULL,
|
|
89
|
+
PRIMARY KEY (extension_id, name)
|
|
90
|
+
)`)}function YO(e,t){e.sql.exec(`INSERT INTO session_document_specs
|
|
91
|
+
(extension_id, name, initial_json, fork, max_bytes) VALUES (?, ?, ?, ?, ?)
|
|
92
|
+
ON CONFLICT(extension_id, name) DO UPDATE SET initial_json = excluded.initial_json,
|
|
93
|
+
fork = excluded.fork, max_bytes = excluded.max_bytes`,t.extensionId,t.name,t.initialJson,t.fork,t.maxBytes)}function XO(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=np(qO)(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 V(`store`,`rejected`,`Session document exceeds its declared size bound`);return[{kind:`document`,workId:null,extensionId:n.extension_id,name:n.name,valueJson:r}]})}var ZO=Zf(j),QO=`The conversation history before this point was compacted into the following summary:
|
|
94
|
+
|
|
95
|
+
<summary>
|
|
96
|
+
`,$O=`
|
|
97
|
+
</summary>`;function ek(e,t){return{role:`user`,content:[{type:`text`,text:QO+e+$O}],timestamp:t}}function tk(){return{edited:new Set,read:new Set,written:new Set}}function nk(e,t){if(e.role===`assistant`)for(let n of e.content){if(n.type!==`toolCall`)continue;let e=n.arguments.path;ZO(e)&&(n.name===`edit`&&t.edited.add(e),n.name===`read`&&t.read.add(e),n.name===`write`&&t.written.add(e))}}function rk(e){let t=new Set([...e.edited,...e.written]);return{modifiedFiles:[...t].sort(),readFiles:[...e.read].filter(e=>!t.has(e)).sort()}}function ik(e,t){let n=[];return e.length>0&&n.push(`<read-files>\n${e.join(`
|
|
98
|
+
`)}\n</read-files>`),t.length>0&&n.push(`<modified-files>\n${t.join(`
|
|
99
|
+
`)}\n</modified-files>`),n.length===0?``:`\n\n${n.join(`
|
|
100
|
+
|
|
101
|
+
`)}`}var ak=2e3;function ok(e){return e.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function sk(e){if(e.length<=ak)return e;let t=String(e.length-ak);return`${e.slice(0,ak)}\n\n[... ${t} more characters truncated]`}function ck(e){let t=ZO(e.content)?e.content:ok(e.content);return t?`[User]: ${t}`:void 0}function lk(e){let t=[],n=[],r=[];for(let i of e.content)if(i.type===`text`)t.push(i.text);else if(i.type===`thinking`)n.push(i.thinking);else{let e=Object.entries(i.arguments).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(`, `);r.push(`${i.name}(${e})`)}let i=[];return n.length>0&&i.push(`[Assistant thinking]: ${n.join(`
|
|
102
|
+
`)}`),t.length>0&&i.push(`[Assistant]: ${t.join(`
|
|
103
|
+
`)}`),r.length>0&&i.push(`[Assistant tool calls]: ${r.join(`; `)}`),i}function uk(e){let t=ok(e.content);return t?`[Tool result]: ${sk(t)}`:void 0}function dk(e){let t=[];for(let n of e)if(n.role===`system`){let e=ZO(n.content)?n.content:ok(n.content);e&&t.push(`[System]: ${e}`)}else if(n.role===`user`){let e=ck(n);e!==void 0&&t.push(e)}else if(n.role===`assistant`)t.push(...lk(n));else{let e=uk(n);e!==void 0&&t.push(e)}return t.join(`
|
|
104
|
+
|
|
105
|
+
`)}var fk=4800;function pk(e){return ZO(e)?e.length:e.reduce((e,t)=>e+(t.type===`text`?t.text?.length??0:t.type===`image`?fk:0),0)}function mk(e){let t=0;switch(e.role){case`system`:return Math.ceil(pk(e.content)/4);case`user`:return Math.ceil(pk(e.content)/4);case`assistant`:for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+JSON.stringify(n.arguments).length;return Math.ceil(t/4);case`toolResult`:return Math.ceil(pk(e.content)/4)}}function hk(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function gk(e){if(e.role===`assistant`&&e.stopReason!==`aborted`&&e.stopReason!==`error`)return hk(e.usage)>0?e.usage:void 0}function _k(e){let t=null,n=0;for(let r=e.length-1;r>=0;--r){let i=e[r];if(i===void 0)continue;let a=gk(i);if(a!==void 0){t=r,n=hk(a);break}}if(t===null){let t=e.reduce((e,t)=>e+mk(t),0);return{tokens:t,usageTokens:0,trailingTokens:t,lastUsageIndex:null}}let r=e.slice(t+1).reduce((e,t)=>e+mk(t),0);return{tokens:n+r,usageTokens:n,trailingTokens:r,lastUsageIndex:t}}function vk(e,t,n){return n.enabled?e>t-n.reserveTokens:!1}var yk={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4},bk=`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.
|
|
106
|
+
|
|
107
|
+
Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,xk=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
|
|
108
|
+
|
|
109
|
+
Use this EXACT format:
|
|
110
|
+
|
|
111
|
+
## Goal
|
|
112
|
+
[What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
|
|
113
|
+
|
|
114
|
+
## Constraints & Preferences
|
|
115
|
+
- [Any constraints, preferences, or requirements mentioned by user]
|
|
116
|
+
- [Or "(none)" if none were mentioned]
|
|
117
|
+
|
|
118
|
+
## Progress
|
|
119
|
+
### Done
|
|
120
|
+
- [x] [Completed tasks/changes]
|
|
121
|
+
|
|
122
|
+
### In Progress
|
|
123
|
+
- [ ] [Current work]
|
|
124
|
+
|
|
125
|
+
### Blocked
|
|
126
|
+
- [Issues preventing progress, if any]
|
|
127
|
+
|
|
128
|
+
## Key Decisions
|
|
129
|
+
- **[Decision]**: [Brief rationale]
|
|
130
|
+
|
|
131
|
+
## Next Steps
|
|
132
|
+
1. [Ordered list of what should happen next]
|
|
133
|
+
|
|
134
|
+
## Critical Context
|
|
135
|
+
- [Any data, examples, or references needed to continue]
|
|
136
|
+
- [Or "(none)" if not applicable]
|
|
137
|
+
|
|
138
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,Sk=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
|
|
139
|
+
|
|
140
|
+
Update the existing structured summary with new information. RULES:
|
|
141
|
+
- PRESERVE all existing information from the previous summary
|
|
142
|
+
- ADD new progress, decisions, and context from the new messages
|
|
143
|
+
- UPDATE the Progress section: move items from "In Progress" to "Done" when completed
|
|
144
|
+
- UPDATE "Next Steps" based on what was accomplished
|
|
145
|
+
- PRESERVE exact file paths, function names, and error messages
|
|
146
|
+
- If something is no longer relevant, you may remove it
|
|
147
|
+
|
|
148
|
+
Use this EXACT format:
|
|
149
|
+
|
|
150
|
+
## Goal
|
|
151
|
+
[Preserve existing goals, add new ones if the task expanded]
|
|
152
|
+
|
|
153
|
+
## Constraints & Preferences
|
|
154
|
+
- [Preserve existing, add new ones discovered]
|
|
155
|
+
|
|
156
|
+
## Progress
|
|
157
|
+
### Done
|
|
158
|
+
- [x] [Include previously done items AND newly completed items]
|
|
159
|
+
|
|
160
|
+
### In Progress
|
|
161
|
+
- [ ] [Current work - update based on progress]
|
|
162
|
+
|
|
163
|
+
### Blocked
|
|
164
|
+
- [Current blockers - remove if resolved]
|
|
165
|
+
|
|
166
|
+
## Key Decisions
|
|
167
|
+
- **[Decision]**: [Brief rationale] (preserve all previous, add new)
|
|
168
|
+
|
|
169
|
+
## Next Steps
|
|
170
|
+
1. [Update based on current state]
|
|
171
|
+
|
|
172
|
+
## Critical Context
|
|
173
|
+
- [Preserve important context, add new if needed]
|
|
174
|
+
|
|
175
|
+
Keep each section concise. Preserve exact file paths, function names, and error messages.`,Ck=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
|
|
176
|
+
|
|
177
|
+
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.
|
|
178
|
+
|
|
179
|
+
## Original Request
|
|
180
|
+
[What did the user ask for?]
|
|
181
|
+
|
|
182
|
+
## Progress So Far
|
|
183
|
+
- [Key decisions and work completed in these messages]
|
|
184
|
+
|
|
185
|
+
## Context Needed to Continue
|
|
186
|
+
- [Information from these messages needed to understand the later work]
|
|
187
|
+
|
|
188
|
+
Only summarize information explicitly present above. Do not infer or recreate later messages.`;function wk(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 Tk=Sp(j.check(Em(1),B(160)),F([`none`,`read`,`write`])).check(R(e=>Object.keys(e).length<=256)),Ek=E(N({version:z.check(sm(0),lm(2**53-1)),grants:Tk}),{onExcessProperty:`error`}),Dk=E(Gm(Tk)),Ok=lp(Gm(Tk)),kk=E(N({version:z,grants_json:j}));function Ak(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_tool_grants (
|
|
189
|
+
session_id TEXT PRIMARY KEY,
|
|
190
|
+
version INTEGER NOT NULL,
|
|
191
|
+
grants_json TEXT NOT NULL
|
|
192
|
+
)`)}function jk(e,t,n){let r=Ek(n);if(Re(r))throw new V(`contract`,`invalid`,`Session grants delivery is invalid`);let i=Ok(r.success.grants),a=Mk(e,t);if(a!==void 0){if(r.success.version<a.version)throw new V(`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)
|
|
193
|
+
VALUES (?, ?, ?)
|
|
194
|
+
ON CONFLICT(session_id) DO UPDATE SET
|
|
195
|
+
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function Mk(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=kk(n);if(Re(r))throw new V(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:r.success.version,grantsJson:r.success.grants_json}}function Nk(e,t){let n=Mk(e,t);if(n===void 0)return null;let r=Dk(n.grantsJson);if(Re(r))throw new V(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:n.version,grants:r.success}}function Pk(e,t,n){e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
|
|
196
|
+
SELECT ?, version, grants_json FROM session_tool_grants WHERE session_id = ?`,n,t)}var Fk=200,Ik={onExcessProperty:`error`},Lk=new TextEncoder,Rk=j.pipe(L(Em(1)),L(R(e=>Lk.encode(e).byteLength<=256))),zk=z.pipe(L(sm(0))),Bk=F([0,1,2]),Vk=F([`needs_you`,`running`,`errored`,`done`]),Hk=F([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),Uk=N({session_id:Rk,title:I(j),created_at:zk,last_activity_at:zk,settled_at:I(zk),state:Vk,tier:Bk}),Wk=E(Uk,Ik);E(Uk.mapFields(If({revision:zk})),Ik),E(N({revision:zk}),Ik);var Gk=E(N({outcome:I(Hk)}),Ik),Kk=Gm(wp([Bk,zk,Rk])),qk=E(Kk),Jk=lp(Kk),Yk=`session_id, title, created_at, last_activity_at, settled_at, state, tier`;function Xk(e){return new V(`store`,`unavailable`,e)}function Zk(e){switch(e){case`needs_you`:return 0;case`running`:return 1;case`errored`:case`done`:return 2}}function Qk(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 $k(e){e.sql.exec(`
|
|
197
|
+
CREATE TABLE IF NOT EXISTS session_inbox (
|
|
198
|
+
session_id TEXT PRIMARY KEY REFERENCES sessions(id),
|
|
199
|
+
title TEXT,
|
|
200
|
+
created_at INTEGER NOT NULL,
|
|
201
|
+
last_activity_at INTEGER NOT NULL,
|
|
202
|
+
settled_at INTEGER,
|
|
203
|
+
outcome TEXT CHECK (
|
|
204
|
+
outcome IS NULL OR outcome IN (
|
|
205
|
+
'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
|
|
206
|
+
)
|
|
207
|
+
),
|
|
208
|
+
state TEXT NOT NULL
|
|
209
|
+
CHECK (state IN ('needs_you', 'running', 'errored', 'done')),
|
|
210
|
+
tier INTEGER NOT NULL CHECK (tier IN (0, 1, 2)),
|
|
211
|
+
revision INTEGER NOT NULL
|
|
212
|
+
)
|
|
213
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_order
|
|
214
|
+
ON session_inbox(tier, last_activity_at DESC, session_id)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_revision
|
|
215
|
+
ON session_inbox(revision)`),e.sql.exec(`
|
|
216
|
+
CREATE TABLE IF NOT EXISTS session_inbox_clock (
|
|
217
|
+
singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
|
|
218
|
+
revision INTEGER NOT NULL
|
|
219
|
+
)
|
|
220
|
+
`),e.sql.exec(`INSERT OR IGNORE INTO session_inbox_clock (singleton, revision) VALUES (1, 0)`),e.sql.exec(`
|
|
221
|
+
CREATE TABLE IF NOT EXISTS session_inbox_tombstones (
|
|
222
|
+
session_id TEXT PRIMARY KEY,
|
|
223
|
+
revision INTEGER NOT NULL
|
|
224
|
+
) STRICT
|
|
225
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_tombstones_revision ON session_inbox_tombstones(revision)`)}function eA(e){e.sql.exec(`UPDATE session_inbox_clock SET revision = revision + 1 WHERE singleton = 1`)}var tA=`(SELECT revision FROM session_inbox_clock WHERE singleton = 1)`;function nA(e,t){let n=t.title===void 0?``:t.title,r=t.title===void 0?0:1;eA(e),e.sql.exec(`INSERT INTO session_inbox
|
|
226
|
+
(session_id, title, created_at, last_activity_at, settled_at, outcome,
|
|
227
|
+
state, tier, revision)
|
|
228
|
+
SELECT id, ?, created_at, COALESCE(?, created_at), NULL, NULL, 'done', 2,
|
|
229
|
+
${tA}
|
|
230
|
+
FROM sessions
|
|
231
|
+
WHERE id = ?
|
|
232
|
+
ON CONFLICT (session_id) DO UPDATE SET
|
|
233
|
+
title = CASE WHEN ? = 1 THEN excluded.title ELSE title END,
|
|
234
|
+
last_activity_at = MAX(last_activity_at, excluded.last_activity_at),
|
|
235
|
+
revision = excluded.revision`,n,t.activityAt??null,t.sessionId,r)}function rA(e,t){eA(e),e.sql.exec(`INSERT INTO session_inbox_tombstones (session_id, revision)
|
|
236
|
+
VALUES (?, ${tA})
|
|
237
|
+
ON CONFLICT (session_id) DO UPDATE SET revision = excluded.revision`,t)}function iA(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=Gk(r);if(i._tag===`Failure`)throw Xk(`Stored inbox row is invalid`);let a=t.settled?.outcome??i.success.outcome,o=Qk(t.head,a,YE(e,t.queue));eA(e),e.sql.exec(`UPDATE session_inbox
|
|
238
|
+
SET outcome = ?, state = ?, tier = ?, revision = ${tA},
|
|
239
|
+
settled_at = CASE WHEN ? = 1 THEN ? ELSE settled_at END,
|
|
240
|
+
last_activity_at = MAX(last_activity_at, ?)
|
|
241
|
+
WHERE session_id = ?`,a,o,Zk(o),t.settled===void 0?0:1,n,n,t.queue)}function aA(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=Gk(r);if(i._tag===`Failure`)throw Xk(`Stored inbox row is invalid`);let a=Qk(n,i.success.outcome,YE(e,t));eA(e),e.sql.exec(`UPDATE session_inbox SET state = ?, tier = ?, revision = ${tA} WHERE session_id = ?`,a,Zk(a),t)}function oA(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 sA(e){let t=qk(e);if(t._tag===`Failure`)throw new V(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function cA(e,t){let n=t===void 0?void 0:sA(t),r=n===void 0?e.sql.exec(`SELECT ${Yk} FROM session_inbox
|
|
242
|
+
ORDER BY tier ASC, last_activity_at DESC, session_id ASC
|
|
243
|
+
LIMIT ?`,Fk).toArray():e.sql.exec(`SELECT ${Yk} FROM session_inbox
|
|
244
|
+
WHERE tier > ?
|
|
245
|
+
OR (tier = ? AND last_activity_at < ?)
|
|
246
|
+
OR (tier = ? AND last_activity_at = ? AND session_id > ?)
|
|
247
|
+
ORDER BY tier ASC, last_activity_at DESC, session_id ASC
|
|
248
|
+
LIMIT ?`,n[0],n[0],n[1],n[0],n[1],n[2],Fk).toArray(),i=[],a;for(let e of r){let t=Wk(e);if(t._tag===`Failure`)throw Xk(`Stored inbox row is invalid`);let n=t.success;a=[n.tier,n.last_activity_at,n.session_id],i.push(oA(n))}return{sessions:i,next:r.length===Fk&&a!==void 0?Jk(a):void 0}}var lA=Ch({family:`session`,version:1,kinds:{session:{prefix:`session`},work:{prefix:`session_work`},fact:{prefix:`session_fact`},receipt:{prefix:`session_receipt`}}});function uA(e){let t=[...e].reverse().find(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`);if(t?.entry.kind!==`message`||t.entry.value.role!==`assistant`)return;let n=e.filter(({sequence:e})=>e>t.sequence);if(n.some(({entry:e})=>e.kind===`turn_started`||e.kind===`compaction`&&e.resumesRun===!0||e.kind===`live_retry`&&e.event.type===`auto_retry_start`))return;let r=n.flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`toolResult`?[e.value]:[]),i=t.entry.value.content.flatMap(e=>{if(e.type!==`toolCall`)return[];let t=[...n].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.result,message:r.find(t=>t.toolCallId===e.id)}];let i=[...n].reverse().find(({entry:t})=>t.kind===`tool_intent`&&t.call.id===e.id)?.entry;return[i?.kind===`tool_intent`?{call:e,state:`started`,replay:i.replay}:{call:e,state:`pending`}]});return{message:t.entry.value,tools:i}}function dA(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)&&r.add(a.id)),e.kind===`compaction`&&e.resumesRun===!0||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 fA(e){let t=[...e].reverse(),n=t.find(({entry:e})=>e.kind===`run_terminal`);if(n?.entry.kind!==`run_terminal`||e.some(({sequence:e,entry:t})=>e>n.sequence&&(t.kind===`run_started`||t.kind===`compaction`&&t.resumesRun===!0)))return;if(n.entry.outcome===`cancelled`)return`cancelled`;if(n.entry.outcome!==`failed`)return;let r=t.find(({entry:e})=>e.kind===`turn_started`),i=t.find(({sequence:e,entry:t})=>t.kind===`message`&&t.value.role===`assistant`&&e>(r?.sequence??0));return i?.entry.kind===`message`&&i.entry.value.role===`assistant`&&i.entry.value.stopReason===`error`&&!e.some(({sequence:e,entry:t})=>e>i.sequence&&t.kind===`live_retry`&&t.event.type===`auto_retry_start`)?void 0:`failed`}var pA={onExcessProperty:`error`},mA=new TextEncoder,Z=j.pipe(L(Em(1)),L(R(e=>mA.encode(e).byteLength<=256))),hA=z.pipe(L(om(0))),gA=z.pipe(L(sm(0))),_A=N({id:Z,leaf_id:I(Z)}),vA=N({session_id:Z}),yA=N({id:Z,leaf_id:I(Z),created_at:gA,updated_at:gA,metadata_json:I(j)}),bA=Gm(N({title:bv})),xA=E(bA,pA),SA=lp(bA),CA=N({id:Z}),wA=N({version:z,protocol:A(`shiitake.extension/v0`)}),TA=N({name:Z}),EA=N({id:Z,session_id:Z,parent_id:I(Z),sequence:hA,type:j,role:I(F([`user`,`assistant`,`tool_result`])),state:F([`complete`,`streaming`]),request_id:I(Z),work_id:I(Z),data_json:j,timestamp:gA,completed_at:I(gA)}),DA=N({id:Z,session_id:Z,sequence:hA,request_id:Z,work_id:Z,data_json:j,timestamp:gA,origin_kind:F([`user`,`extension`]),origin_id:I(Z),origin_correlation:I(Z)}),OA=N({kind:A(`extension`),extensionId:Z,correlation:I(Z)}),kA=P([N({kind:A(`user`)}),OA]),AA=E(kA,pA),jA=Zm(kA),MA=e=>[`id`,`session_id`,`sequence`,`request_id`,`work_id`,`data_json`,`timestamp`,`origin_kind`,`origin_id`,`origin_correlation`].map(t=>e+t).join(`, `),NA=N({next_sequence:hA}),PA=N({present:A(1)}),FA=E(_A,pA),IA=E(vA,pA),LA=E(yA,pA),RA=E(CA,pA),zA=E(wA,pA),BA=E(TA,pA),VA=E(N({candidate_id:I(Z),path_count:z.pipe(L(om(0))),root_count:z.pipe(L(sm(0))),missing_parent_count:z.pipe(L(sm(0))),leaf_state:F([`complete`,`streaming`])}),pA),HA=E(EA,pA),UA=E(DA,pA),WA=E(N({sequence:I(hA)}),pA),GA=E(NA,pA),KA=E(PA,pA);function qA(e,t){return t===void 0?e:{...e,meta:t}}function JA(e,t){let n=e.sql.exec(`SELECT id, leaf_id, created_at, updated_at, metadata_json
|
|
249
|
+
FROM sessions
|
|
250
|
+
WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=LA(n);if(r._tag===`Failure`)throw Q(`Stored Session summary row is invalid`);let i=QA(e,t,r.success),a=r.success.metadata_json;if(a===null)return i;let o=xA(a);if(o._tag===`Failure`)throw Q(`Stored Session title is invalid`);return Object.freeze({createdAt:r.success.created_at,updatedAt:r.success.updated_at,title:o.success.title})}var YA=E(N({id:Z,sequence:hA}),pA);function XA(e,t,n,r){let i=e.sql.exec(`SELECT command.id AS id, command.sequence AS sequence
|
|
251
|
+
FROM session_entries AS command
|
|
252
|
+
WHERE command.session_id = ? AND command.type = 'command'
|
|
253
|
+
AND command.role = 'user' AND command.state = 'complete'
|
|
254
|
+
AND NOT EXISTS (
|
|
255
|
+
SELECT 1 FROM session_entries AS cancelled
|
|
256
|
+
WHERE cancelled.work_id = command.work_id
|
|
257
|
+
AND cancelled.session_id = command.session_id
|
|
258
|
+
AND cancelled.type = 'cancellation'
|
|
259
|
+
AND cancelled.sequence < command.sequence
|
|
260
|
+
)
|
|
261
|
+
ORDER BY command.sequence ASC LIMIT 1`,t).toArray()[0];if(i===void 0)return null;let a=YA(i);if(a._tag===`Failure`)throw Q(`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
|
|
262
|
+
WHERE parent.session_id = ? AND parent.sequence < ?
|
|
263
|
+
AND (SELECT COUNT(*) FROM session_entries AS child
|
|
264
|
+
WHERE child.parent_id = parent.id
|
|
265
|
+
AND child.session_id = parent.session_id
|
|
266
|
+
AND child.state = 'complete') > 1
|
|
267
|
+
LIMIT 1`,t,o.sequence).toArray()[0]===void 0?o.id:ZA(e,t,n)}function ZA(e,t,n){let r=VA(e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, type, role, state, work_id) AS (
|
|
268
|
+
SELECT id, parent_id, sequence, type, role, state, work_id
|
|
269
|
+
FROM session_entries
|
|
270
|
+
WHERE session_id = ? AND id = ?
|
|
271
|
+
UNION
|
|
272
|
+
SELECT parent.id, parent.parent_id, parent.sequence,
|
|
273
|
+
parent.type, parent.role, parent.state, parent.work_id
|
|
274
|
+
FROM session_entries AS parent
|
|
275
|
+
JOIN branch AS child ON parent.id = child.parent_id
|
|
276
|
+
WHERE parent.session_id = ?
|
|
277
|
+
)
|
|
278
|
+
SELECT
|
|
279
|
+
(SELECT command.id FROM branch AS command
|
|
280
|
+
WHERE command.type = 'command' AND command.role = 'user'
|
|
281
|
+
AND command.state = 'complete'
|
|
282
|
+
AND NOT EXISTS (
|
|
283
|
+
SELECT 1 FROM branch AS cancelled
|
|
284
|
+
WHERE cancelled.type = 'cancellation'
|
|
285
|
+
AND cancelled.work_id = command.work_id
|
|
286
|
+
AND cancelled.sequence < command.sequence
|
|
287
|
+
)
|
|
288
|
+
ORDER BY command.sequence ASC LIMIT 1) AS candidate_id,
|
|
289
|
+
(SELECT COUNT(*) FROM branch) AS path_count,
|
|
290
|
+
(SELECT COUNT(*) FROM branch WHERE parent_id IS NULL) AS root_count,
|
|
291
|
+
(SELECT COUNT(*) FROM branch AS child
|
|
292
|
+
WHERE child.parent_id IS NOT NULL
|
|
293
|
+
AND NOT EXISTS (
|
|
294
|
+
SELECT 1 FROM session_entries AS parent
|
|
295
|
+
WHERE parent.session_id = ? AND parent.id = child.parent_id
|
|
296
|
+
)) AS missing_parent_count,
|
|
297
|
+
(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 Q(`Stored Session summary lineage is invalid`);return r.success.candidate_id}function QA(e,t,n){if(n.leaf_id===null)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:``});let r=lj(e,t,n.leaf_id);if(r?.state!==`complete`)throw Q(`Stored Session summary leaf is invalid`);let i=XA(e,t,n.leaf_id,r.sequence),a=i===null?void 0:lj(e,t,i)?.entry,o=a===void 0?void 0:lO(a);if(o!==void 0)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:Array.from(wM(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 $A(e,t){try{return JA(e,t)?.title??``}catch(e){if(e instanceof V&&e.cause===`unavailable`)return null;throw e}}function Q(e){return new V(`store`,`unavailable`,e)}function ej(e){return new V(`store`,`incompatible`,e)}function tj(e){let t=FA(e);if(t._tag===`Failure`)throw Q(`Stored Session row is invalid`);return t.success}function nj(e){return e.kind===`command`||e.kind===`cancellation`||e.kind===`operator`?e.requestId:null}function rj(e){return e.kind===`command`?cO(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 ij(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function aj(e){let t=HA(e);if(t._tag===`Failure`)throw Q(`Stored Session entry row is invalid`);let n=t.success,r=mO(n.data_json);if(r._tag===`Failure`)throw Q(`Stored Session entry data is invalid`);let i=r.success;if(n.type!==i.kind||n.work_id!==i.workId||n.request_id!==nj(i)||n.role!==rj(i))throw Q(`Stored Session entry columns disagree with its data`);return Object.freeze({id:n.id,sessionId:n.session_id,parentId:n.parent_id,sequence:n.sequence,state:n.state,timestamp:n.timestamp,completedAt:n.completed_at,entry:i})}function oj(e){let t=UA(e);if(t._tag===`Failure`)throw Q(`Stored command admission row is invalid`);let n=t.success,r=mO(n.data_json);if(r._tag===`Failure`||r.success.kind!==`command`)throw Q(`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!==uO(i))throw Q(`Stored command admission columns disagree with its data`);let a=AA(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 Q(`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 sj(e,t){return cj(e,t)!==void 0}function cj(e,t){let n=e.sql.exec(`SELECT id, leaf_id FROM sessions WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:tj(n)}function lj(e,t,n){let r=e.sql.exec(`SELECT id, session_id, parent_id, sequence, type, role, state,
|
|
298
|
+
request_id, work_id, data_json, timestamp, completed_at
|
|
299
|
+
FROM session_entries
|
|
300
|
+
WHERE session_id = ? AND id = ?`,t,n).toArray()[0];return r===void 0?void 0:aj(r)}function uj(e,t){if(t.leaf_id===null){let n=e.sql.exec(`SELECT 1 AS present
|
|
301
|
+
FROM session_entries
|
|
302
|
+
WHERE session_id = ?
|
|
303
|
+
LIMIT 1`,t.id).toArray()[0];if(n===void 0)return;throw KA(n)._tag===`Failure`?Q(`Session entry presence is invalid`):Q(`Session leaf is invalid`)}let n=lj(e,t.id,t.leaf_id);if(n?.state!==`complete`)throw Q(`Session leaf is invalid`);return n}function dj(e,t){let n=e.sql.exec(`SELECT id, session_id, parent_id, sequence, type, role, state,
|
|
304
|
+
request_id, work_id, data_json, timestamp, completed_at
|
|
305
|
+
FROM session_entries
|
|
306
|
+
WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:aj(n)}function fj(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 ${MA(``)}
|
|
307
|
+
FROM session_command_admissions
|
|
308
|
+
WHERE session_id = ? AND ${r} = ?`,t,i).toArray()[0];return a===void 0?void 0:oj(a)}var pj=`FROM session_command_admissions AS a
|
|
309
|
+
WHERE a.session_id = ?
|
|
310
|
+
AND NOT EXISTS (
|
|
311
|
+
SELECT 1 FROM session_entries AS e
|
|
312
|
+
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
313
|
+
AND e.type IN ('command', 'cancellation', 'run_terminal', 'work_terminal')
|
|
314
|
+
)`,mj=np(N({total:z.check(sm(0))}));function hj(e,t,n,r=`all`){let i=r===`prompts`?`AND json_extract(a.data_json, '$.work') IS NULL`:``,a=mj(e.sql.exec(`SELECT COUNT(*) AS total ${pj} ${i}`,t).one()).total;return{commands:e.sql.exec(`SELECT ${MA(`a.`)} ${pj} ${i}
|
|
315
|
+
ORDER BY a.sequence ASC LIMIT ?`,t,n).toArray().map(oj),total:a}}function gj(e,t,n,r,i=200){return e.sql.exec(`SELECT ${MA(`a.`)}
|
|
316
|
+
FROM session_command_admissions AS a
|
|
317
|
+
WHERE a.session_id = ?
|
|
318
|
+
AND json_extract(a.data_json, '$.delivery') = ?
|
|
319
|
+
AND (? IS NULL OR json_extract(a.data_json, '$.targetWorkId') = ?)
|
|
320
|
+
AND NOT EXISTS (
|
|
321
|
+
SELECT 1 FROM session_entries AS e
|
|
322
|
+
WHERE e.session_id = a.session_id AND e.work_id = a.work_id
|
|
323
|
+
AND e.type IN ('command', 'run_terminal', 'work_terminal')
|
|
324
|
+
)
|
|
325
|
+
ORDER BY a.sequence ASC LIMIT ?`,t,n,r??null,r??null,i).toArray().map(oj)}function _j(e,t,n){return gj(e,t,`steer`,n,1).length>0}function vj(e,t,n,r){return e.transactionSync(()=>gj(e,t,n,r).map(n=>{let r=lO(lj(e,t,n.id)?.entry??Uj(e,{sessionId:t,id:n.id,entry:n.entry}).entry);if(r===void 0)throw Q(`Session control admission is invalid`);return{workId:r.workId,requestId:r.requestId,message:fO(r)}}))}function yj(e,t){e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${MA(`a.`)}
|
|
326
|
+
FROM session_command_admissions AS a
|
|
327
|
+
WHERE a.session_id = ?
|
|
328
|
+
AND json_extract(a.data_json, '$.delivery') = 'steer'
|
|
329
|
+
AND json_extract(a.data_json, '$.targetWorkId') = ?
|
|
330
|
+
ORDER BY a.sequence ASC`,t.sessionId,t.parentWorkId).toArray().map(oj);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){if(lj(e,t.sessionId,r.id)===void 0){t.enqueue({jobId:r.entry.workId,sessionId:t.sessionId,commandFactId:r.id});continue}Uj(e,{sessionId:t.sessionId,id:lA.fact.generate(),entry:{kind:`work_terminal`,workId:r.entry.workId,outcome:t.outcome}})}})}function bj(e,t,n){return fj(e,t,{id:n})}function xj(e,t,n){return fj(e,t,{workId:n})}function Sj(e,t,n){return fj(e,t,{requestId:n})}function Cj(e,t,n){return Object.freeze(e.sql.exec(`SELECT id, session_id, parent_id, sequence, type, role, state,
|
|
331
|
+
request_id, work_id, data_json, timestamp, completed_at
|
|
332
|
+
FROM session_entries
|
|
333
|
+
WHERE session_id = ? AND work_id = ?
|
|
334
|
+
ORDER BY sequence ASC`,t,n).toArray().map(aj))}function wj(e,t,n){let r=e.sql.exec(`SELECT id, session_id, parent_id, sequence, type, role, state,
|
|
335
|
+
request_id, work_id, data_json, timestamp, completed_at
|
|
336
|
+
FROM session_entries
|
|
337
|
+
WHERE session_id = ? AND work_id = ? AND type = 'live_retry'
|
|
338
|
+
ORDER BY sequence DESC
|
|
339
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=aj(r);if(i.entry.kind!==`live_retry`)throw Q(`Stored live retry entry is invalid`);return{event:i.entry.event,timestamp:i.timestamp}}function Tj(e,t,n,r){return e.sql.exec(`SELECT 1 FROM session_entries INDEXED BY idx_session_entries_successful_tool
|
|
340
|
+
WHERE session_id = ? AND work_id = ? AND type = 'tool_outcome'
|
|
341
|
+
AND json_extract(data_json, '$.result.isError') = 0
|
|
342
|
+
AND json_extract(data_json, '$.call.id') = ? LIMIT 1`,t,n,r).toArray().length>0}function Ej(e,t,n){let r=e.sql.exec(`SELECT intent.id, intent.session_id, intent.parent_id,
|
|
343
|
+
intent.sequence, intent.type, intent.role, intent.state,
|
|
344
|
+
intent.request_id, intent.work_id, intent.data_json,
|
|
345
|
+
intent.timestamp, intent.completed_at
|
|
346
|
+
FROM session_entries AS intent
|
|
347
|
+
WHERE intent.session_id = ? AND intent.work_id = ?
|
|
348
|
+
AND intent.type = 'tool_intent'
|
|
349
|
+
AND NOT EXISTS (
|
|
350
|
+
SELECT 1 FROM session_entries AS outcome
|
|
351
|
+
WHERE outcome.session_id = intent.session_id
|
|
352
|
+
AND outcome.work_id = intent.work_id
|
|
353
|
+
AND outcome.type = 'tool_outcome'
|
|
354
|
+
AND json_extract(outcome.data_json, '$.toolCall.value') =
|
|
355
|
+
json_extract(intent.data_json, '$.toolCall.value')
|
|
356
|
+
)
|
|
357
|
+
ORDER BY intent.sequence DESC
|
|
358
|
+
LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=aj(r);if(i.entry.kind!==`tool_intent`)throw Q(`Stored tool intent is invalid`);return i.entry.call.name}function Dj(e,t){let n=GA(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
359
|
+
FROM session_entries
|
|
360
|
+
WHERE session_id = ?`,t).one());if(n._tag===`Failure`)throw Q(`Next Session sequence is invalid`);return n.success.next_sequence}function Oj(e,t){let n=GA(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
|
|
361
|
+
FROM (
|
|
362
|
+
SELECT sequence
|
|
363
|
+
FROM session_command_admissions
|
|
364
|
+
WHERE session_id = ?
|
|
365
|
+
UNION ALL
|
|
366
|
+
SELECT sequence
|
|
367
|
+
FROM session_entries
|
|
368
|
+
WHERE session_id = ? AND type = 'command'
|
|
369
|
+
)`,t,t).one());if(n._tag===`Failure`)throw Q(`Next command admission sequence is invalid`);return n.success.next_sequence}function kj(e,t){let n=cj(e,t);if(n!==void 0)return n;let r=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
370
|
+
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
371
|
+
VALUES (?, '/', NULL, NULL, ?, ?, NULL)`,t,r,r),nA(e,{sessionId:t,activityAt:r,title:``});let i=cj(e,t);if(i===void 0)throw Q(`Created Session row is unavailable`);return i}function Aj(e,t,n){return e.transactionSync(()=>{let r=e.sql.exec(`SELECT session_id FROM session_creation_receipts WHERE request_id = ?`,t).toArray()[0];if(r!==void 0){let e=IA(r);if(e._tag===`Failure`)throw Q(`Session creation receipt is invalid`);return e.success.session_id}n();let i=lA.session.generate();return kj(e,i),e.sql.exec(`INSERT INTO session_creation_receipts (request_id, session_id) VALUES (?, ?)`,t,i),i})}function jj(e,t){return e.transactionSync(()=>{if(cj(e,t.sessionId)===void 0)return!1;t.assertIdleSession(t.sessionId),t.recordInboxDeletion(t.sessionId);for(let n of[`DELETE FROM session_entries WHERE session_id = ?`,`DELETE FROM session_command_admissions WHERE session_id = ?`,`DELETE FROM session_attention 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 = ?`])e.sql.exec(n,t.sessionId);return!0})}var Mj=1,Nj=`shiitake.extension/v0`;function Pj(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(BA(n)._tag===`Failure`)throw Q(`Store catalog row is invalid`);return!0}function Fj(e){if(!Pj(e,`woodstock_schema`))return Pj(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=zA(t[0]);return n._tag===`Success`&&n.success.version===Mj?`v0`:`unmarked`}function Ij(e){let t=Fj(e);if(t!==`v0`){if(t===`unmarked`)throw ej(`Woodstock store has no v0 protocol marker; a hosted store never resets itself — reset the owning Durable Object storage, or remove the old local store file before opening a fresh one`);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 (?, ?)`,Mj,Nj)}}function Lj(e){e.sql.exec(`
|
|
372
|
+
CREATE TABLE IF NOT EXISTS session_entries (
|
|
373
|
+
id TEXT PRIMARY KEY,
|
|
374
|
+
session_id TEXT NOT NULL,
|
|
375
|
+
parent_id TEXT,
|
|
376
|
+
sequence INTEGER NOT NULL,
|
|
377
|
+
type TEXT NOT NULL,
|
|
378
|
+
role TEXT,
|
|
379
|
+
state TEXT NOT NULL CHECK (state IN ('complete', 'streaming')),
|
|
380
|
+
request_id TEXT,
|
|
381
|
+
work_id TEXT,
|
|
382
|
+
data_json TEXT NOT NULL,
|
|
383
|
+
timestamp INTEGER NOT NULL,
|
|
384
|
+
completed_at INTEGER,
|
|
385
|
+
UNIQUE (session_id, sequence)
|
|
386
|
+
)
|
|
387
|
+
`)}function Rj(e){e.transactionSync(()=>{Ij(e),e.sql.exec(`
|
|
388
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
389
|
+
id TEXT PRIMARY KEY,
|
|
390
|
+
cwd TEXT NOT NULL,
|
|
391
|
+
parent_session TEXT,
|
|
392
|
+
leaf_id TEXT,
|
|
393
|
+
created_at INTEGER NOT NULL,
|
|
394
|
+
updated_at INTEGER NOT NULL,
|
|
395
|
+
metadata_json TEXT
|
|
396
|
+
)
|
|
397
|
+
`),Lj(e),JO(e),qE(e),Ak(e),$k(e),e.sql.exec(`
|
|
398
|
+
CREATE TABLE IF NOT EXISTS session_creation_receipts (
|
|
399
|
+
request_id TEXT PRIMARY KEY,
|
|
400
|
+
session_id TEXT NOT NULL UNIQUE REFERENCES sessions(id)
|
|
401
|
+
)
|
|
402
|
+
`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_parent ON session_entries(parent_id)`),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
|
|
403
|
+
ON session_entries(session_id, request_id)
|
|
404
|
+
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_successful_tool
|
|
405
|
+
ON session_entries(session_id, work_id, json_extract(data_json, '$.call.id'))
|
|
406
|
+
WHERE type = 'tool_outcome' AND json_extract(data_json, '$.result.isError') = 0`),e.sql.exec(`
|
|
407
|
+
CREATE TABLE IF NOT EXISTS session_command_admissions (
|
|
408
|
+
id TEXT PRIMARY KEY,
|
|
409
|
+
session_id TEXT NOT NULL,
|
|
410
|
+
sequence INTEGER NOT NULL,
|
|
411
|
+
request_id TEXT NOT NULL,
|
|
412
|
+
work_id TEXT NOT NULL,
|
|
413
|
+
data_json TEXT NOT NULL,
|
|
414
|
+
timestamp INTEGER NOT NULL,
|
|
415
|
+
origin_kind TEXT NOT NULL CHECK (origin_kind IN ('user', 'extension')),
|
|
416
|
+
origin_id TEXT,
|
|
417
|
+
origin_correlation TEXT,
|
|
418
|
+
CHECK ((origin_kind = 'user') = (origin_id IS NULL)),
|
|
419
|
+
CHECK (origin_kind = 'extension' OR origin_correlation IS NULL),
|
|
420
|
+
-- This orders durable acceptance facts, not conversation entries.
|
|
421
|
+
UNIQUE (session_id, sequence),
|
|
422
|
+
UNIQUE (session_id, request_id),
|
|
423
|
+
UNIQUE (session_id, work_id)
|
|
424
|
+
)
|
|
425
|
+
`)}),OO(e)}function zj(e,t){return fM(e,oM(e,{sessionId:t}))}function Bj(e,t){let n=cj(e,t)?.leaf_id;if(n==null)return null;let r=WA(e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, type, state) AS (
|
|
426
|
+
SELECT id, parent_id, sequence, type, state
|
|
427
|
+
FROM session_entries
|
|
428
|
+
WHERE session_id = ? AND id = ?
|
|
429
|
+
UNION
|
|
430
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.type,
|
|
431
|
+
parent.state
|
|
432
|
+
FROM session_entries AS parent
|
|
433
|
+
JOIN branch AS child ON parent.id = child.parent_id
|
|
434
|
+
WHERE parent.session_id = ?
|
|
435
|
+
)
|
|
436
|
+
SELECT MAX(sequence) AS sequence
|
|
437
|
+
FROM branch
|
|
438
|
+
WHERE type = 'model_preference' AND state != 'streaming'`,t,n,t).one());if(r._tag===`Failure`)throw Q(`Stored model choice order is invalid`);return r.success.sequence}function Vj(e,t,n){return e.transactionSync(()=>Uj(e,{sessionId:t,id:lA.fact.generate(),entry:{kind:`model_preference`,workId:null,preference:n}}))}function Hj(e,t,n){e.transactionSync(()=>{kj(e,t),e.sql.exec(`UPDATE sessions SET metadata_json = ? WHERE id = ?`,n===null?null:SA({title:n}),t),nA(e,{sessionId:t,title:$A(e,t)})})}function Uj(e,t){let n=uj(e,kj(e,t.sessionId)),r=t.state??`complete`;if(r===`streaming`!=(t.entry.kind===`message_start`))throw Q(`A message start must be the streaming entry`);if(r===`streaming`&&t.entry.kind===`message_start`&&t.id!==t.entry.message.value)throw Q(`Message placeholder identity does not match its row`);let i=Date.now(),a=Dj(e,t.sessionId);e.sql.exec(`INSERT INTO session_entries
|
|
439
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
440
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
441
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.id,t.sessionId,n?.id??null,a,t.entry.kind,rj(t.entry),r,nj(t.entry),t.entry.workId,hO(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),nA(e,t.entry.kind===`command`?{sessionId:t.sessionId,activityAt:i,title:$A(e,t.sessionId)}:{sessionId:t.sessionId,activityAt:i}));let o=lj(e,t.sessionId,t.id);if(o===void 0)throw Q(`Appended Session entry is unavailable`);return o}function Wj(e,t){let n=uj(e,kj(e,t.sessionId)),r=lj(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?Dj(e,t.sessionId):r?.sequence??Dj(e,t.sessionId),c=r?.timestamp??i;if(t.id!==t.entry.message.value)throw Q(`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 Q(`Completed Session leaf is not a message entry`);if(e.workId!==t.entry.workId||!ij(e.run,t.entry.run)||!ij(e.turn,t.entry.turn)||!ij(e.message,t.entry.message)||e.kind===`message_start`&&e.role!==t.entry.value.role)throw Q(`Completed message does not match its placeholder`)}e.sql.exec(`INSERT OR REPLACE INTO session_entries
|
|
442
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
443
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
444
|
+
VALUES (?, ?, ?, ?, 'message', ?, 'complete',
|
|
445
|
+
NULL, ?, ?, ?, ?)`,t.id,t.sessionId,o,s,rj(t.entry),t.entry.workId,hO(t.entry),c,i),e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,t.id,i,t.sessionId),nA(e,{sessionId:t.sessionId,activityAt:i});let l=lj(e,t.sessionId,t.id);if(l===void 0)throw Q(`Completed Session leaf is unavailable`);return l}var Gj=`id, session_id, parent_id, sequence, type, role, state,
|
|
446
|
+
request_id, work_id, data_json, timestamp, completed_at`,Kj=4e3,qj=4194304,Jj={selected:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
|
|
447
|
+
SELECT id, parent_id, sequence, state
|
|
448
|
+
FROM session_entries
|
|
449
|
+
WHERE session_id = ? AND id = ?
|
|
450
|
+
UNION
|
|
451
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state
|
|
452
|
+
FROM session_entries AS parent
|
|
453
|
+
JOIN branch AS child ON parent.id = child.parent_id
|
|
454
|
+
WHERE parent.session_id = ?
|
|
455
|
+
)`,fork:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
|
|
456
|
+
SELECT id, parent_id, sequence, state
|
|
457
|
+
FROM session_entries
|
|
458
|
+
WHERE session_id = ? AND id = ? AND state != 'streaming'
|
|
459
|
+
UNION
|
|
460
|
+
SELECT parent.id, parent.parent_id, parent.sequence, parent.state
|
|
461
|
+
FROM session_entries AS parent
|
|
462
|
+
JOIN branch AS child ON parent.id = child.parent_id
|
|
463
|
+
WHERE parent.session_id = ? AND parent.state != 'streaming'
|
|
464
|
+
)`},Yj={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`}},Xj=z.pipe(L(sm(0))),Zj=E(N({length:Xj,root_id:I(Z),root_parent_id:I(j),broken:Xj,newest_id:I(Z),newest_sequence:I(hA)}),pA),Qj=E(N({sequence:hA,bytes:Xj}),pA),$j=E(N({bytes:Xj}),pA),eM=E(N({sequence:hA}),pA),tM=E(N({first_kept:Z}),pA),nM=E(N({work_id:Z}),pA),rM=E(N({work_id:Z,diagnostic:j}),pA);function iM(e,t,n,...r){return e.sql.exec(`${Jj[t.walk]} ${n}`,t.sessionId,t.tipId,t.sessionId,...r).toArray()}function aM(e,t,n,r){let i=Yj[r],a=Zj(e.sql.exec(`${Jj[r]},
|
|
465
|
+
kept AS MATERIALIZED (
|
|
466
|
+
SELECT id, parent_id, sequence FROM branch
|
|
467
|
+
WHERE state != 'streaming'
|
|
468
|
+
),
|
|
469
|
+
links AS (
|
|
470
|
+
SELECT parent_id, LAG(id) OVER (ORDER BY sequence) AS previous
|
|
471
|
+
FROM kept
|
|
472
|
+
)
|
|
473
|
+
SELECT
|
|
474
|
+
(SELECT COUNT(*) FROM kept) AS length,
|
|
475
|
+
(SELECT id FROM kept ORDER BY sequence ASC LIMIT 1) AS root_id,
|
|
476
|
+
(SELECT parent_id FROM kept ORDER BY sequence ASC LIMIT 1)
|
|
477
|
+
AS root_parent_id,
|
|
478
|
+
(SELECT COUNT(*) FROM links
|
|
479
|
+
WHERE previous IS NOT NULL AND parent_id IS NOT previous) AS broken,
|
|
480
|
+
(SELECT id FROM kept ORDER BY sequence DESC LIMIT 1) AS newest_id,
|
|
481
|
+
(SELECT sequence FROM kept ORDER BY sequence DESC LIMIT 1)
|
|
482
|
+
AS newest_sequence`,t,n,t).one());if(a._tag===`Failure`)throw Q(`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 Q(i.empty);if(o.root_parent_id!==null)throw Q(i.missingParent);if(o.broken!==0)throw Q(i.invalid);return Object.freeze({sessionId:t,walk:r,tipId:n,rootId:o.root_id,newestId:o.newest_id,newestSequence:o.newest_sequence})}function oM(e,t){let n=t.leafId??cj(e,t.sessionId)?.leaf_id;if(n!=null)return aM(e,t.sessionId,n,`selected`)}function sM(e,t,n,r){return Object.freeze(iM(e,t,`SELECT ${Gj}
|
|
483
|
+
FROM session_entries
|
|
484
|
+
WHERE session_id = ? AND state != 'streaming'
|
|
485
|
+
AND sequence BETWEEN ? AND ?
|
|
486
|
+
AND id IN (SELECT id FROM branch)
|
|
487
|
+
ORDER BY sequence ASC`,t.sessionId,n,r).map(aj))}function cM(e,t,n){let r=iM(e,t,`SELECT sequence, LENGTH(CAST(data_json AS BLOB)) AS bytes
|
|
488
|
+
FROM session_entries
|
|
489
|
+
WHERE session_id = ? AND state != 'streaming'
|
|
490
|
+
AND sequence > ? AND sequence < ?
|
|
491
|
+
AND id IN (SELECT id FROM branch)
|
|
492
|
+
ORDER BY sequence ${n.from===`newest`?`DESC`:`ASC`}
|
|
493
|
+
LIMIT ?`,t.sessionId,n.after??0,n.before??2**53-1,n.rows+1).map(e=>{let t=Qj(e);if(t._tag===`Failure`)throw Q(`Stored Session entry size is invalid`);return t.success}),i=0,a=0;for(let e of r){if(i===n.rows||i>0&&a+e.bytes>qj)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:sM(e,t,Math.min(o.sequence,s.sequence),Math.max(o.sequence,s.sequence)),more:r.length>i})}function lM(e,t,n){return iM(e,t,`SELECT 1 AS present
|
|
494
|
+
FROM session_entries
|
|
495
|
+
WHERE session_id = ? AND state != 'streaming' AND sequence = ?
|
|
496
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,n).length>0}function uM(e,t,n){let r=iM(e,t,`SELECT sequence
|
|
497
|
+
FROM session_entries
|
|
498
|
+
WHERE session_id = ? AND state != 'streaming' AND id = ?
|
|
499
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,n)[0];if(r===void 0)return;let i=eM(r);if(i._tag===`Failure`)throw Q(`Stored Session entry sequence is invalid`);return i.success.sequence}function dM(e,t,n){let r=iM(e,t,`SELECT ${Gj}
|
|
500
|
+
FROM session_entries
|
|
501
|
+
WHERE session_id = ? AND state != 'streaming' AND type = ?
|
|
502
|
+
AND id IN (SELECT id FROM branch)
|
|
503
|
+
ORDER BY sequence DESC
|
|
504
|
+
LIMIT 1`,t.sessionId,n)[0];return r===void 0?void 0:aj(r)}function fM(e,t){let n=t===void 0?void 0:dM(e,t,`model_preference`)?.entry;return n?.kind===`model_preference`?n.preference:null}function pM(e,t,n,r){if(t===void 0)return;let i=iM(e,t,`SELECT ${Gj}
|
|
505
|
+
FROM session_entries
|
|
506
|
+
WHERE session_id = ? AND state != 'streaming' AND type = 'document'
|
|
507
|
+
AND json_extract(data_json, '$.extensionId') = ?
|
|
508
|
+
AND json_extract(data_json, '$.name') = ?
|
|
509
|
+
AND id IN (SELECT id FROM branch)
|
|
510
|
+
ORDER BY sequence DESC
|
|
511
|
+
LIMIT 1`,t.sessionId,n,r)[0],a=i===void 0?void 0:aj(i).entry;if(a!==void 0){if(a.kind!==`document`||a.extensionId!==n||a.name!==r)throw Q(`Stored Session document disagrees with its row`);return a.valueJson}}function mM(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=new Set(iM(e,t,`SELECT DISTINCT work_id
|
|
512
|
+
FROM session_entries
|
|
513
|
+
WHERE session_id = ? AND state != 'streaming' AND type = 'command'
|
|
514
|
+
AND work_id IN (SELECT value FROM json_each(?))
|
|
515
|
+
AND id IN (SELECT id FROM branch)`,t.sessionId,r).map(e=>{let t=nM(e);if(t._tag===`Failure`)throw Q(`Stored Session command work is invalid`);return t.success.work_id})),a=new Map;for(let n of iM(e,t,`SELECT work_id, diagnostic FROM (
|
|
516
|
+
SELECT work_id, sequence,
|
|
517
|
+
CASE
|
|
518
|
+
WHEN type = 'work_terminal'
|
|
519
|
+
THEN json_extract(data_json, '$.diagnostic')
|
|
520
|
+
WHEN type = 'message'
|
|
521
|
+
THEN json_extract(data_json, '$.value.errorMessage')
|
|
522
|
+
WHEN json_extract(data_json, '$.event.type') = 'auto_retry_end'
|
|
523
|
+
THEN json_extract(data_json, '$.event.finalError')
|
|
524
|
+
END AS diagnostic
|
|
525
|
+
FROM session_entries
|
|
526
|
+
WHERE session_id = ? AND state != 'streaming'
|
|
527
|
+
AND work_id IN (SELECT value FROM json_each(?))
|
|
528
|
+
AND (type IN ('work_terminal', 'live_retry')
|
|
529
|
+
OR (type = 'message' AND role = 'assistant'))
|
|
530
|
+
AND id IN (SELECT id FROM branch)
|
|
531
|
+
)
|
|
532
|
+
WHERE diagnostic IS NOT NULL
|
|
533
|
+
ORDER BY sequence ASC`,t.sessionId,r)){let e=rM(n);if(e._tag===`Failure`)throw Q(`Stored Session diagnostic is invalid`);a.set(e.success.work_id,e.success.diagnostic)}let o=new Map;for(let{entry:n}of iM(e,t,`SELECT ${Gj}
|
|
534
|
+
FROM session_entries
|
|
535
|
+
WHERE session_id = ? AND state != 'streaming' AND type = 'cancellation'
|
|
536
|
+
AND json_extract(data_json, '$.targetWorkId')
|
|
537
|
+
IN (SELECT value FROM json_each(?))
|
|
538
|
+
AND id IN (SELECT id FROM branch)
|
|
539
|
+
ORDER BY sequence ASC`,t.sessionId,r).map(aj))n.kind===`cancellation`&&n.meta!==void 0&&o.set(n.targetWorkId,n.meta);return Object.freeze({commands:i,diagnostics:a,cancellations:o})}function hM(e,t,n,r,...i){return iM(e,t.lineage,`SELECT ${n}
|
|
540
|
+
FROM session_entries
|
|
541
|
+
WHERE session_id = ? AND state != 'streaming'
|
|
542
|
+
AND id IN (SELECT id FROM branch)
|
|
543
|
+
AND sequence > ?
|
|
544
|
+
AND (? IS NULL OR work_id = ?
|
|
545
|
+
OR (type = 'command'
|
|
546
|
+
AND json_extract(data_json, '$.targetWorkId') = ?))
|
|
547
|
+
${r}`,t.lineage.sessionId,t.after,t.work,t.work,t.work,...i)}function gM(e,t){for(let n of[...t].reverse()){let r=hM(e,n,`json_extract(data_json, '$.firstKeptEntryId') AS first_kept`,`AND type = 'compaction' ORDER BY sequence DESC LIMIT 1`)[0];if(r===void 0)continue;let i=tM(r);if(i._tag===`Failure`)throw Q(`Stored Session compaction boundary is invalid`);for(let n of t){let t=hM(e,n,`sequence`,`AND id = ?`,i.success.first_kept)[0];if(t===void 0)continue;let r=eM(t);if(r._tag===`Failure`)throw Q(`Stored Session entry sequence is invalid`);return r.success.sequence}return 0}return 0}function _M(e,t,n){let r=gM(e,t),i=0;for(let n of t){let t=$j(hM(e,n,`COALESCE(SUM(LENGTH(CAST(data_json AS BLOB))), 0) AS bytes`,`AND sequence >= ?`,r)[0]);if(t._tag===`Failure`)throw Q(`Stored Session context size is invalid`);i+=t.success.bytes}if(i>12582912)throw new V(`store`,`context_too_large`,`This Session's model context is too large to read safely. Branch or fork from an earlier entry to continue.`);let a=t.flatMap(t=>hM(e,t,Gj,`AND sequence >= ? ORDER BY sequence ASC`,r).map(aj));if(r===0)return Object.freeze(a);let o=JSON.stringify(a.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[])),s=t.flatMap(t=>hM(e,t,Gj,`AND sequence < ?
|
|
548
|
+
AND ((type = 'compaction' AND work_id = ?)
|
|
549
|
+
OR (type = 'cancellation'
|
|
550
|
+
AND json_extract(data_json, '$.targetWorkId')
|
|
551
|
+
IN (SELECT value FROM json_each(?))))
|
|
552
|
+
ORDER BY sequence ASC`,r,n,o).map(aj));return Object.freeze([...s,...a])}function vM(e,t){let n=oM(e,{sessionId:t.sessionId});return n===void 0?Object.freeze([]):_M(e,[{lineage:n,after:0,work:null}],t.workId??null)}function yM(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 bM(e,t){let n=yM(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.firstKeptEntryId),o=a>=0?e.slice(a):e,s=dA(o,t),c=[];i!==void 0&&r!==void 0&&c.push(ek(i.summary,r.timestamp));for(let e of o){let t=lO(e.entry);t!==void 0&&!n.has(t.workId)&&c.push(fO(t)),e.entry.kind===`operator`&&c.push(dO(e.entry)),e.entry.kind===`message`&&s.has(e.id)&&c.push(e.entry.value)}return Object.freeze(c)}function xM(e,t){return e.transactionSync(()=>{let n=lj(e,t.sessionId,t.commandFactId),r=`replay`,i=bj(e,t.sessionId,t.commandFactId);if(n===void 0&&i!==void 0&&(n=Uj(e,{sessionId:i.sessionId,id:i.id,entry:i.entry}),r=`new`),n?.entry.kind!==`command`)throw Q(`Accepted Session command is unavailable`);if(i!==void 0&&hO(n.entry)!==hO(i.entry))throw Q(`Accepted Session command disagrees with its admission`);let a=aM(e,t.sessionId,n.id,`selected`);if(a.newestId!==n.id)throw Q(`Accepted Session command lineage is unavailable`);e.sql.exec(`DELETE FROM session_entries WHERE session_id = ? AND work_id = ? AND state = 'streaming' AND type = 'message_start'`,t.sessionId,n.entry.workId);let o=Cj(e,t.sessionId,n.entry.workId),s=n.entry.workId,c=oM(e,{sessionId:t.sessionId}),l=_M(e,c===void 0?[{lineage:a,after:0,work:null}]:[{lineage:a,after:0,work:null},{lineage:c,after:n.sequence,work:s}],s),u=Object.freeze({...n,entry:n.entry});return Object.freeze({command:u,modelPreference:fM(e,a),messages:bM(l,n.entry.workId),path:l,entryDelivery:r,resume:uA(o),abnormalTerminal:fA(o)})})}function SM(e,t){return e.transactionSync(()=>{let n={kind:`compaction_notice`,workId:t.workId,trigger:t.trigger,result:t.result};return Uj(e,{sessionId:t.sessionId,id:lA.fact.generate(),entry:t.diagnostic===void 0?n:{...n,diagnostic:t.diagnostic.slice(0,200)}})})}function CM(e,t){return e.transactionSync(()=>{if(cj(e,t.sessionId)?.leaf_id!==t.expectedLeafId)throw new V(`store`,`conflict`,`Session leaf changed during compaction`);let n={kind:`compaction`,resumesRun:t.resumesRun??!1,trigger:t.trigger,tokensAfter:t.tokensAfter,workId:t.workId,firstKeptEntryId:t.firstKeptEntryId,summary:t.summary,tokensBefore:t.tokensBefore,usage:t.usage,contextRevision:t.contextRevision};return Uj(e,{sessionId:t.sessionId,id:lA.fact.generate(),entry:t.details===void 0?n:{...n,details:t.details}})})}function wM(e){return Array.isArray(e)}function TM(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 EM(e,t){return!wM(e)||!wM(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 DM(e,t){if(t.type===`compact`)return cO(e)&&e.instructions===t.instructions;let n=lO(e);return n?.delivery===t.delivery&&EM(n.message.content,TM(t))}function OM(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:TM(e),timestamp:n},contract:r},c=i===void 0?s:{...s,targetWorkId:i};return a===void 0?c:{...c,reply:a}}function kM(e,t){return e?.agentId===t?.agentId&&e?.sessionId===t?.sessionId&&e?.commandId===t?.commandId&&e?.outcome===t?.outcome&&e?.diagnostic===t?.diagnostic}function AM(e,t,n,r,i,a,o,s,c){let l=Sj(e,t,n.requestId);if(l!==void 0){if(!DM(l.entry,n)||!hD(l.entry.meta,r)||!kM(lO(l.entry)?.reply,c)||!jA(l.origin,i))throw new V(`contract`,`conflict`,`Request id conflicts with an accepted Session command`);return jM(l,`replay`)}let u=lA.fact.generate();kj(e,t);let d=Date.now(),f=OM(n,u,d,a,s,c);e.sql.exec(`INSERT INTO session_command_admissions
|
|
553
|
+
(id, session_id, sequence, request_id, work_id, data_json, timestamp,
|
|
554
|
+
origin_kind, origin_id, origin_correlation)
|
|
555
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,u,t,Oj(e,t),n.requestId,u,hO(qA(f,r)),d,i.kind,i.kind===`user`?null:i.extensionId,i.kind===`user`?null:i.correlation);let p=bj(e,t,u);if(p===void 0)throw Q(`Accepted Session command admission is unavailable`);return o?.({jobId:u,sessionId:t,commandFactId:u}),jM(p,`new`)}function jM(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 MM(e,t,n){if(e.entry.kind!==`cancellation`)throw Q(`Accepted Session cancellation is unavailable`);return Object.freeze({accepted:Object.freeze({commandId:e.entry.targetWorkId,entryId:e.id}),delivery:t,active:n})}function NM(e,t,n,r,i){return e.transactionSync(()=>{let a=n(),o=a.state===`running`?xj(e,t,a.jobId):void 0,s=o===void 0?void 0:FM(e,t,o.id,n,r,!1,i);for(let a=Oj(e,t);a>0;){let{commands:o}=hj(e,t,64);if(o.length===0)return s;a-=o.length;for(let a of o){if(FM(e,t,a.id,n,r,!1,i,!0)===void 0)throw Q(`Pending Session command could not be cancelled`);Uj(e,{sessionId:t,id:a.id,entry:a.entry})}}throw Q(`Session cancellation did not settle its pending admissions`)})}function PM(e,t,n,r,i,a=!1,o){return e.transactionSync(()=>FM(e,t,n,r,i,a,o))}function FM(e,t,n,r,i,a=!1,o,s=!1){let c=r(),l=bj(e,t,n);if(l?.entry.kind!==`command`)return;let u=Cj(e,t,l.entry.workId),d=u.find(({entry:e})=>e.kind===`cancellation`);if(d?.entry.kind===`cancellation`)return MM(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`))||lO(l.entry)?.delivery===`steer`&&u.some(({entry:e})=>e.kind===`command`)&&!f)return;let p=lA.fact.generate(),m=i({jobId:l.entry.workId,cancellationId:p,onlyIfPending:a});if(m.status===`missing`&&lO(l.entry)?.delivery!==`steer`&&!s||m.status===`conflict`&&a)return;if(m.status!==`recorded`&&m.status!==`missing`)throw new V(`store`,`conflict`,`Session cancellation identity conflicts`);let ee=Uj(e,{sessionId:t,id:p,entry:qA({kind:`cancellation`,requestId:p,receiptId:p,workId:l.entry.workId,targetWorkId:l.entry.workId},o)});return m.status===`missing`&&Uj(e,{sessionId:t,id:lA.fact.generate(),entry:{kind:`work_terminal`,workId:l.entry.workId,outcome:`cancelled`}}),MM(ee,`new`,f)}function IM(e,t){e.transactionSync(()=>{t.assertIdleSession?.(t.sessionId);let n=cj(e,t.sessionId);if(n===void 0)throw Q(`Session is unavailable for branch selection`);uj(e,n);let r=lj(e,t.sessionId,t.entryId);if(r?.state!==`complete`)throw Q(`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),nA(e,{sessionId:n.id,activityAt:i,title:$A(e,n.id)})})}function LM(e,t){return e.transactionSync(()=>{if(cj(e,t.sessionId)===void 0)throw Q(`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=RA(n);if(r._tag===`Failure`)throw Q(`Stored Session entry identity is invalid`);let i=lj(e,t.sessionId,r.success.id);if(i?.entry.kind===`operator`&&i.entry.author===t.author&&hD(i.entry.meta,t.meta)&&i.entry.message.content===t.text)return!1;throw new V(`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 Uj(e,{sessionId:t.sessionId,id:lA.fact.generate(),entry:qA(r,t.meta)}),!0})}function RM(e,t){return e.transactionSync(()=>{if(t.assertIdleSession?.(t.sessionId),cj(e,t.sessionId)===void 0)throw Q(`Source Session is unavailable`);let n=aM(e,t.sessionId,t.entryId,`fork`),r=lA.session.generate(),i=Date.now();e.sql.exec(`INSERT INTO sessions
|
|
556
|
+
(id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
|
|
557
|
+
VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),Pk(e,t.sessionId,r);let a=null,o=null,s=1,c=new Map,l=0;for(;;){let t=cM(e,n,{after:l,from:`oldest`,rows:Kj});for(let n of t.rows){let t=lA.fact.generate();c.set(n.id,t);let i=n.entry.kind===`compaction`?{...n.entry,firstKeptEntryId:c.get(n.entry.firstKeptEntryId)??(()=>{throw Q(`Fork compaction boundary is unavailable`)})()}:n.entry;e.sql.exec(`INSERT INTO session_entries
|
|
558
|
+
(id, session_id, parent_id, sequence, type, role, state,
|
|
559
|
+
request_id, work_id, data_json, timestamp, completed_at)
|
|
560
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,rj(i),n.state,nj(i),i.workId,hO(i),n.timestamp,n.completedAt),a=t,o=t,s+=1,l=n.sequence}if(!t.more)break}if(o===null)throw Q(`Fork path is empty`);e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,o,i,r);let u=oM(e,{sessionId:t.sessionId});for(let t of XO(e,(t,n)=>pM(e,u,t,n)))Uj(e,{sessionId:r,id:lA.fact.generate(),entry:t});return nA(e,{sessionId:r,activityAt:i,title:$A(e,r)}),r})}function zM(e,t,n,r){if(cj(e,t)===void 0)throw Q(`Session document owner is unavailable`);return pM(e,oM(e,{sessionId:t}),n,r)}function BM(e,t,n,r,i){if(cj(e,t)===void 0)throw Q(`Session document owner is unavailable`);Uj(e,{sessionId:t,id:lA.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var VM=2097152,HM=200,UM=200,WM=new TextEncoder;function GM(e){return new V(`store`,`unavailable`,e)}function KM(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)bj(e,t,n)!==void 0&&r.set(n,n);return r}function qM(e,t){return n=>{let r=bj(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function JM(e,t,n){return{commandIds:KM(e,t,n),diagnostics:ZM(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:qM(e,t)}}function YM(e,t,n,r){let i=mM(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)&&bj(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:qM(e,t)}}function XM(e,t){let n=lO(e.entry);if(n!==void 0){let r=t.origin(n.workId),i={id:e.id,sequence:e.sequence,commandId:n.workId,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,value:pO(e.entry)};return e.entry.meta!==void 0&&(t={...t,meta:e.entry.meta}),Object.freeze(t)}if(e.entry.kind===`message`)return Object.freeze({id:e.entry.message.value,sequence:e.sequence,commandId:t.commandIds.get(e.entry.workId)??null,value:e.entry.value})}function ZM(e){let t=new Map;for(let{entry:n}of e)n.kind===`work_terminal`&&n.diagnostic!==void 0?t.set(n.workId,n.diagnostic):n.kind===`message`&&n.value.role===`assistant`?n.value.errorMessage!==void 0&&t.set(n.workId,n.value.errorMessage):n.kind===`live_retry`&&n.event.type===`auto_retry_end`&&n.event.finalError!==void 0&&t.set(n.workId,n.event.finalError);return t}function QM(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})}function $M(e,t,n){let r=[];for(let i of n){let n=i.entry;if(n.kind!==`compaction`)continue;let a=uM(e,t,n.firstKeptEntryId);if(a===void 0)throw GM(`Session compaction horizon is unavailable`);r.push(Object.freeze({id:i.id,sequence:a,at:i.timestamp,tokensBefore:n.tokensBefore,tokensAfter:n.tokensAfter??null,trigger:n.trigger??null}))}return Object.freeze(r)}function eN(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.diagnostic??null})]:[]))}function tN(e){return WM.encode(JSON.stringify(e)).byteLength}function nN(e,t){let n=sD({generation:e,sequence:t});if(n===void 0)throw GM(`Session cursor is unavailable`);return n}function rN(e,t,n,r,i=!1){let a=XM(t,r),o=QM(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:tN(a))+(o===void 0?0:tN(o))+(s===void 0?0:tN(s));if(c>VM)throw GM(`Session projection entry exceeds the read bound`);return e.bytes+c>VM?!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 iN(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==UM;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!rN(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw GM(`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 aN(e){return Array.isArray(e)}function oN(e,t){let{commands:n,total:r}=hj(e,t,UM+1,`prompts`),i=[],a=WM.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=lO(e.entry);if(t===void 0)throw GM(`Pending Session prompt is unavailable`);let n=t.message.content,o=aN(n)?{commandId:e.entry.workId,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,text:n,delivery:t.delivery??`followUp`},s=e.entry.meta===void 0?o:{...o,meta:e.entry.meta},c=e.origin.kind===`extension`?{...s,origin:{extensionId:e.origin.extensionId,correlation:e.origin.correlation}}:s,l=WM.encode(JSON.stringify(c)).byteLength+(i.length===0?0:1);if(i.length===UM||a+l>VM)return{prompts:i,hasMore:!0,total:r};i.push(c),a+=l}return{prompts:i,hasMore:!1,total:r}}function sN(e,t,n){let r=cD(n);if(r?.generation===t.rootId)return lM(e,t,r.sequence)?r.sequence:void 0}function cN(e,t,n,r,i=()=>({})){return e.transactionSync(()=>{let a=oN(e,t),o=oM(e,{sessionId:t});if(o===void 0)return Object.freeze({sessionId:t,cursor:null,hasMore:!1,oldestCursor:null,messages:Object.freeze([]),terminals:Object.freeze([]),compactions:Object.freeze([]),compactionNotices:Object.freeze([]),pending:a,activity:r.facts,progress:r.progress,extensions:i(),attention:JE(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:sN(e,o,n.before);if(c===void 0)throw GM(`Session read cursor is unavailable`);let l=cM(e,o,{before:c,from:`newest`,rows:UM}),u=iN(l.rows,l.more,n.limit,YM(e,t,o,l.rows),`backward`,n.includeSandboxFailures===!0),d=l.rows.slice(l.rows.length-u.consumed),f=l.rows.at(-1),p=d[0],m={sessionId:t,cursor:f===void 0?null:nN(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?nN(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:$M(e,o,d),compactionNotices:eN(d),pending:a,activity:r.facts,progress:n.before===void 0?r.progress:null,extensions:i(),attention:JE(e,t)};return Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var lN=Object.freeze({kind:`reset`});function uN(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return lM(e,t,n.sequence)?n.sequence:void 0}function dN(e,t,n,r,i,a,o,s,c){let l=cM(e,t,{after:n,from:`oldest`,rows:UM}),u=iN(l.rows,l.more,HM,YM(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:nN(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:$M(e,t,d),compactionNotices:eN(d),pending:s,activity:i.facts,extensions:a,attention:o},m=[Object.freeze(c?{...p,sandboxFailures:u.sandboxFailures}:p)];return r===`live`&&!u.hasMore&&i.progress!==null&&m.push(Object.freeze({kind:`progress`,progress:i.progress,activity:i.facts})),Object.freeze({kind:`page`,frames:Object.freeze(m),hasMore:u.hasMore})}function fN(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:cD(n);return n!==void 0&&s===void 0?lN:e.transactionSync(()=>{let c=oN(e,t),l=oM(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:JE(e,t),pending:c}],hasMore:!1}:lN;let u=uN(e,l,s);return u===void 0?lN:dN(e,l,u,r,i,a(),JE(e,t),c,o)})}function pN(e,t,n){let r=bj(e,t,n);if(r===void 0)throw GM(`Accepted Session command is unavailable`);let i=Cj(e,t,r.entry.workId),a=JM(e,t,i),o=i.flatMap(e=>{let t=QM(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;return{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}}var mN=new WeakMap;function hN(e){let t=mN.get(e);if(t!==void 0)return t;let n=new Map;return mN.set(e,n),n}function gN(e){return new V(`runtime`,`rejected`,e)}function _N(e,t,n){let r=hN(e).get(t);return r?.workId===n?r.value:null}function vN(e){let t=``,n=``;for(let r of e.value.content)r.type===`text`&&(t+=r.text),r.type===`thinking`&&(n+=r.thinking);return{text:t,thinking:n}}function yN(e,t,n){return i(function*(){let r,i=x(()=>{hN(e).delete(t.sessionId)&&VE(e,t.sessionId,`progress`),r=void 0});return yield*hr(()=>i),Object.freeze({started:n=>x(()=>{r=n,hN(e).delete(t.sessionId)}),update:n=>Wn(()=>{let i=r;if(i===void 0)return y(gN(`Mule progress arrived before its message start`));if(i.run.value!==n.run.value||i.turn.value!==n.turn.value||i.message.value!==n.message.value)return y(gN(`Mule progress identity conflicts`));let a=hN(e).get(t.sessionId),o=vN(n);return a?.workId===t.commandId&&a.value.text===o.text&&a.value.thinking===o.thinking?w:(hN(e).set(t.sessionId,Object.freeze({workId:t.commandId,value:Object.freeze({messageId:n.message.value,revision:(a?.workId===t.commandId?a.value.revision:0)+1,text:o.text,thinking:o.thinking,textTruncated:!1,thinkingTruncated:!1})})),VE(e,t.sessionId,`progress`),w)}),terminal:e=>i.pipe(Wt(n(e)))})})}var bN=new WeakMap;function xN(e){let t=bN.get(e);if(t!==void 0)return t;let n=new Map;return bN.set(e,n),n}function SN(e,t){return xN(e).get(t)??null}function CN(e,t,n){xN(e).set(t,Object.freeze({trigger:n})),VE(e,t,`progress`)}function wN(e,t){xN(e).delete(t)&&VE(e,t,`progress`)}var TN=Object.freeze({refuseAt:.8,readmitBelow:.75}),EN=E(z.pipe(L(om(0)))),DN=E(M.pipe(L($p()),L(sm(0)))),ON=Object.freeze({admitNew:()=>{}});function kN(e){if(e===void 0)return ON;let t=EN(e.budgetBytes);if(t._tag===`Failure`)throw new V(`contract`,`invalid`,`Storage budget must be a positive whole number of bytes`);let n=t.success,r=!1;return Object.freeze({admitNew:()=>{let t=DN(e.usedBytes());if(t._tag===`Failure`)throw new V(`store`,`unavailable`,`Owner storage size is unavailable`);let i=t.success/n;if(r=r?i>=TN.readmitBelow:i>=TN.refuseAt,r)throw new V(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function AN(e,t){let n=SM(e,t);return VE(e,t.sessionId),n}function jN(e,t){let n=CM(e,t);return VE(e,t.sessionId),n}function MN(e){return new V(`store`,`rejected`,e)}function NN(e){return new V(`store`,`conflict`,e)}function $(e){return Sn({try:e,catch:e=>e instanceof V?e:new V(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function PN(e){return $(()=>{Rj(e)})}function FN(e,t,n,r,i,a,o){return $(()=>{let s=PM(e,t,n,i,a,r,o);return s?.delivery===`new`&&VE(e,t),s})}function IN(e,t){return $(()=>{let n=vj(e,t.sessionId,t.delivery,t.workId);return n.length>0&&VE(e,t.sessionId),n})}function LN(e,t){return $(()=>{yj(e,t),VE(e,t.sessionId)})}function RN(e,t,n,r,i){return $(()=>{let a=NM(e,t,n,r,i);return VE(e,t),a?.accepted})}function zN(e,t){return $(()=>{IM(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),VE(e,t.sessionId)})}function BN(e,t){return $(()=>{LM(e,t)&&VE(e,t.sessionId)})}function VN(e,t){return $(()=>{let n=RM(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return VE(e,n),Object.freeze({sessionId:n})})}function HN(e,t){return $(()=>{let n=xM(e,{sessionId:Pv(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&VE(e,t.sessionId),n})}function UN(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function WN(e,t){return $(()=>{let n=bj(e,t.sessionId,t.commandFactId);if(n===void 0)throw MN(`Accepted Session command is unavailable`);let r=Cj(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`)return UN(t.value)}return``})}function GN(e,t,n){return $(()=>{let r=bj(e,t.sessionId,t.commandFactId);if(r===void 0)throw MN(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=Cj(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function KN(e,t){return $(()=>{let n=bj(e,t.sessionId,t.commandFactId);if(n===void 0)throw MN(`Accepted Session command is unavailable`);return ZM(Cj(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function qN(e,t,n,r,i=()=>({})){return $(()=>cN(e,Pv(t),Lv(r),n,i))}function JN(e,t,n){return $(()=>Aj(e,Iv({requestId:t}),n))}function YN(e,t){return $(()=>jj(e,{sessionId:Pv(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{rA(e,t)}}))}function XN(e,t){return $(()=>cA(e,t))}function ZN(e,t,n,r,i,a=()=>({}),o=!1){return $(()=>fN(e,Pv(t),n,r,i,a,o))}function QN(e,t){return hO(e)===hO(t)}function $N(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function eP(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 tP(e,t,n,r,i){e.transactionSync(()=>{i?.();let a=Cj(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||QN(a.entry,n))return`replay`;throw NN(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=lA.fact.generate();if(dj(e,r)===void 0&&bj(e,t.sessionId,r)===void 0)return Uj(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw MN(`Session fact identity allocation failed`)})===`new`&&VE(e,t.sessionId)}function nP(e,t,n){return $(()=>{tP(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function rP(e,t,n,r){let i=bj(e,t,n);if(i?.entry.workId!==r)throw MN(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function iP(e,t,n,r){let i=rP(e,t,n,r),a=Cj(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 aP(e,t){return $(()=>{if(bj(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw MN(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};tP(e,{sessionId:t.sessionId,commandId:t.workId},t.diagnostic===void 0?n:{...n,diagnostic:t.diagnostic},({entry:e})=>e.kind===`work_terminal`||e.kind===`run_terminal`&&e.outcome===t.outcome,()=>{e.sql.exec(`DELETE FROM session_entries WHERE session_id = ? AND work_id = ? AND state = 'streaming' AND type = 'message_start'`,t.sessionId,t.workId)})})}function oP(e,t,n,r){return $(()=>{let i=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};tP(e,t,i,({entry:e})=>e.kind===i.kind?e.kind===`run_started`&&i.kind===`run_started`?$N(e.run,i.run)&&eP(e.contract,n):e.kind===`turn_started`&&i.kind===`turn_started`?$N(e.turn,i.turn):e.kind===`run_terminal`&&i.kind===`run_terminal`&&$N(e.terminal,i.terminal):!1)})}function sP(e,t,n){return $(()=>{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=Cj(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&$N(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!$N(i.entry.run,r.run)||!$N(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw NN(`Mule message-start identity conflicts`);return`replay`}if(!QN(i.entry,r))throw NN(`Mule message-start identity conflicts`);return`replay`}return Uj(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&VE(e,t.sessionId)})}function cP(e,t,n,r){return $(()=>{tP(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`&&$N(e.turn,r.turn)&&e.attempt===r.attempt&&eP(e.contract,n))})}function lP(e,t,n){return $(()=>{let r={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value};e.transactionSync(()=>{let i=Cj(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&$N(e.message,n.message));if(i?.entry.kind===`message`){if(!QN(i.entry,r))throw NN(`Mule completed-message identity conflicts`);return`replay`}return Wj(e,{sessionId:t.sessionId,id:n.message.value,entry:r}),`new`})===`new`&&VE(e,t.sessionId)})}function uP(e,t,n,r){return $(()=>{tP(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`&&$N(e.toolCall,r.toolCall)&&eP(e.contract,n))})}function dP(e,t,n){return $(()=>{tP(e,t,{kind:`tool_outcome`,workId:t.commandId,run:n.run,turn:n.turn,toolCall:n.toolCall,call:n.call,result:n.result},({entry:e})=>e.kind===`tool_outcome`&&$N(e.toolCall,n.toolCall))})}function fP(e,t,n,r){return $(()=>{let i=Cj(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&$N(e.turn,r));if(i===void 0)throw NN(`Retry has no recorded turn`);tP(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&&$N(e.event.run,n.run))}).pipe(we(pP))}var pP=()=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`});function mP(e,t,n){return i(function*(){let r=yield*yN(e,t,n=>lP(e,t,n)),i=i=>{switch(i.type){case`model_prompt`:return cP(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return oP(e,t,n,i);case`message_start`:return i.value.role===`user`?w:sP(e,t,i).pipe(Wt(i.value.role===`assistant`?r.started(i):w));case`message_update`:return r.update(i);case`message_end`:return i.value.role===`user`?w:i.value.role===`assistant`?r.terminal(i):lP(e,t,i);case`tool_execution_start`:return uP(e,t,n,i);case`tool_execution_end`:return dP(e,t,i);case`tool_execution_update`:case`turn_end`:return w}};return e=>i(e).pipe(we(pP))})}function hP(e,t,n){return $(()=>pN(e,Pv(t),Pv(n)))}var gP=j.pipe(L(Em(1)),L(B(128)),L(Wp(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),_P=j.pipe(L(Em(1)),L(B(64)),L(Wp(/^(?: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))),vP=gP.pipe(Mp(`ExtensionId`)),yP=j.pipe(L(Wp(/^sha256:[0-9a-f]{64}$/u)),Mp(`ExtensionRevision`)),bP=j.pipe(L(Wp(/^sha256:[0-9a-f]{64}$/u)),Mp(`ExtensionFingerprint`)),xP=class extends Di(`ExtensionHookError`){};function SP(e){return Wn(()=>{let t=e();return Ve(t)?t:Dn({try:()=>Promise.resolve(t),catch:e=>new xP({cause:e})})})}var CP=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function wP(e,t){let n=e(t);if(n instanceof Promise||Ve(n)&&!Nt(n))throw new CP;return n}export{zj as $,Ps as $i,mg as $n,um as $r,QE as $t,BN as A,Di as Aa,dm as Ai,Pv as An,_p as Ar,NO as At,kA as B,$m as Bi,y_ as Bn,Qf as Br,IO as Bt,XN as C,Ki as Ca,B as Ci,GC as Cn,Sp as Cr,wk as Ct,KN as D,Li as Da,Em as Di,Lv as Dn,Jm as Dr,MO as Dt,WN as E,Ri as Ea,Am as Ei,Fv as En,yp as Er,PO as Et,kN as F,k as Fi,Y_ as Fn,L as Fr,FO as Ft,sj as G,Us as Gi,I_ as Gn,sp as Gr,cO as Gt,AM as H,Yf as Hi,b_ as Hn,ep as Hr,zO as Ht,CN as I,O as Ii,X_ as In,Hf as Ir,LO as It,Bj as J,pu as Ji,N_ as Jn,ap as Jr,kD as Jt,Tj as K,zs as Ki,O_ as Kn,lp as Kr,dO as Kt,wN as L,jp as Li,U_ as Ln,Vf as Lr,VO as Lt,aP as M,Yp as Mi,zv as Mn,P as Mr,UO as Mt,LN as N,Kp as Ni,V as Nn,hp as Nr,kO as Nt,GN as O,Ni as Oa,Rm as Oi,jv as On,wp as Or,BO as Ot,IN as P,R as Pi,ev as Pn,Mp as Pr,AO as Pt,zM as Q,Bs as Qi,vg as Qn,Zf as Qr,ZE as Qt,SN as R,Ap as Ri,K_ as Rn,tp as Rr,WO as Rt,qN as S,Yi as Sa,jm as Si,LC as Sn,M as Sr,vk as St,iP as T,Vi as Ta,Im as Ti,Av as Tn,N as Tr,KO as Tt,bM as U,Rp as Ui,L_ as Un,E as Ur,YD as Ut,OA as V,Qm as Vi,P_ as Vn,$f as Vr,RO as Vt,_j as W,Bu as Wi,C_ as Wn,np as Wr,fO as Wt,Sj as X,js as Xi,E_ as Xn,Gm as Xr,DD as Xt,wj as Y,Ls as Yi,B_ as Yn,op as Yr,ED as Yt,vM as Z,Fs as Zi,yg as Zn,Bp as Zr,mD as Zt,HN as _,ea as _a,Cm as _i,Vw as _n,mp as _r,_k as _t,bP as a,Rl as aa,Lm as ai,PE as an,oh as ar,aA as at,hP as b,Ji as ba,wm as bi,Nw as bn,gp as br,ik as bt,_P as c,ts as ca,om as ci,kE as cn,vp as cr,Nk as ct,jN as d,oa as da,sm as di,vT as dn,z as dr,bk as dt,Ms as ea,Tm as ei,$E as en,gg as er,Vj as et,zN as f,da as fa,Sm as fi,qT as fn,eh as fr,Ck as ft,VN as g,ta as ga,cm as gi,Hw as gn,pm as gr,tk as gt,YN as h,la as ha,fm as hi,Lw as hn,F as hr,rk as ht,vP as i,cu as ia,Bm as ii,VE as in,Ch as ir,dA as it,nP as j,ii as ja,Wp as ji,Rv as jn,kp as jr,GO as jt,fP as k,Fi as ka,Fm as ki,Iv as kn,Xm as kr,OO as kt,RN as l,rs as la,xm as li,SE as ln,Um as lr,yk as lt,JN as m,sa as ma,Zp as mi,gT as mn,A as mr,ek as mt,SP as n,su as na,bm as ni,RE as nn,Vh as nr,yM as nt,gP as o,Cs as oa,Xp as oi,NE as on,Tp as or,iA as ot,FN as p,pa,_m as pi,hT as pn,th as pr,Sk as pt,Ej as q,Is as qi,T_ as qn,Pp as qr,lO as qt,wP as r,lu as ra,km as ri,HE as rn,Bh as rr,BM as rt,yP as s,es as sa,$p as si,ME as sn,bp as sr,jk as st,CP as t,Vs as ta,Mm as ti,XE as tn,Wh as tr,Hj as tt,AN as u,Ca as ua,gm as ui,CE as un,Qp as ur,xk as ut,mP as v,ia as va,vm as vi,Rw as vn,Ep as vr,mk as vt,ZN as w,Mi as wa,zm as wi,av as wn,j as wr,YO as wt,rP as x,qi as xa,ym as xi,RC as xn,I as xr,dk as xt,PN as y,Wi as ya,lm as yi,Mw as yn,Vm as yr,nk as yt,_N as z,zp as zi,G_ as zn,rp as zr,jO as zt};
|