@fungi.computer/grove 0.7.0 → 0.8.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.
Files changed (40) hide show
  1. package/dist/assets/{Effect-CtszBD7f.js → Effect-CsknxyoC.js} +1 -1
  2. package/dist/assets/animation-Ca8A_H2p.js +1 -0
  3. package/dist/assets/{anthropic-messages-CDm0hoBV.js → anthropic-messages-CVTSajCf.js} +3 -3
  4. package/dist/assets/{azure-openai-responses-BjoRAOlM.js → azure-openai-responses-Bl0qLprn.js} +1 -1
  5. package/dist/assets/{base-face-DzmOsdaJ.js → base-face-BYNJAADF.js} +1 -1
  6. package/dist/assets/burger-CkHWi49Z.js +1 -0
  7. package/dist/assets/cat-DyLB0vqU.js +1 -0
  8. package/dist/assets/compat-CqXUS3Sf.js +2 -0
  9. package/dist/assets/{document-Bagsf-XI.js → document-Bq-ilh6h.js} +1 -1
  10. package/dist/assets/extension-hook-CI69uLQY.js +809 -0
  11. package/dist/assets/{google-generative-ai-xdelq2ko.js → google-generative-ai-CNNdplPY.js} +1 -1
  12. package/dist/assets/{google-shared-P7z8Pe9d.js → google-shared-BIcQKTFY.js} +1 -1
  13. package/dist/assets/{google-vertex-8hsu6Eaf.js → google-vertex-DDdvFanV.js} +1 -1
  14. package/dist/assets/index-CCFVxQrP.js +117 -0
  15. package/dist/assets/{mistral-conversations-JKMpJrPb.js → mistral-conversations-DyAgbR7r.js} +1 -1
  16. package/dist/assets/{mushroom-ur0TNKww.js → mushroom-Bm99-6Un.js} +1 -1
  17. package/dist/assets/{node.browser-GHKlzSn3.js → node.browser-ILUZE1xW.js} +1 -1
  18. package/dist/assets/{openai-codex-responses-CidQ12Xa.js → openai-codex-responses-D3R6a8BL.js} +1 -1
  19. package/dist/assets/openai-codex.models-B_MCwO6E.js +1 -0
  20. package/dist/assets/{openai-completions-D9RzypE9.js → openai-completions-mxaKYcNn.js} +1 -1
  21. package/dist/assets/{openai-responses-BXeaL2BV.js → openai-responses-Bm0Qs189.js} +1 -1
  22. package/dist/assets/{openai-responses-shared-Da1jFqQB.js → openai-responses-shared-D6bv6hF3.js} +1 -1
  23. package/dist/assets/parakeet-DuJ3iiSB.js +36 -0
  24. package/dist/assets/parakeet-conversation-CDEkPNoL.js +4 -0
  25. package/dist/assets/renderer-B77qG8Ri.js +1 -0
  26. package/dist/assets/runtime-core-Dev7cGsf.js +40 -0
  27. package/dist/assets/sigil-B438LdFL.js +31 -0
  28. package/dist/assets/{transform-messages-YmXk5TtR.js → transform-messages-BYFvCqeV.js} +1 -1
  29. package/dist/assets/website-conversation-BaqjHBp1.js +1 -0
  30. package/dist/index.html +7 -5
  31. package/package.json +12 -12
  32. package/dist/assets/burger-DGewjCsv.js +0 -1
  33. package/dist/assets/cat-CRMM8U8H.js +0 -1
  34. package/dist/assets/compat-tatm8WJ0.js +0 -2
  35. package/dist/assets/extension-hook-CmoMuW6C.js +0 -819
  36. package/dist/assets/extensions-CrmxvtfG.js +0 -1
  37. package/dist/assets/index-CCJvRnqn.js +0 -174
  38. package/dist/assets/parakeet-conversation-DYlN7oL9.js +0 -4
  39. package/dist/assets/renderer-BKCye2Ev.js +0 -1
  40. package/dist/assets/runtime-core-DKpk6tKT.js +0 -40
@@ -1,819 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-tatm8WJ0.js","assets/preload-helper-DY31Aviq.js","assets/index-CCJvRnqn.js","assets/rolldown-runtime-hePW80VL.js","assets/Effect-CtszBD7f.js","assets/document-Bagsf-XI.js","assets/base-face-DzmOsdaJ.js","assets/index-DVjf7FkJ.css","assets/provider-env-CcCbsTJq.js","assets/diagnostics-CxvqSC4Q.js","assets/models-BM_0GHMS.js","assets/json-parse-M7s0500m.js","assets/openai-codex-responses-CidQ12Xa.js","assets/headers-FK4rgixo.js","assets/transform-messages-YmXk5TtR.js","assets/runtime-core-DKpk6tKT.js","assets/extensions-CrmxvtfG.js","assets/error-body-pkrba6pf.js","assets/openai-prompt-cache-DXo9f3w5.js","assets/openai-responses-shared-Da1jFqQB.js","assets/sanitize-unicode-DmIE6hZJ.js","assets/hash-yQufAZII.js","assets/abort-signals-joV34wzR.js"])))=>i.map(i=>d[i]);
2
- import{$ as e,$r as t,$t as n,A as r,Ai as i,An as a,Ar as o,At as s,B as c,Bn as l,Br as u,Bt as d,C as f,Ci as p,Cn as m,Cr as ee,Ct as h,D as te,Di as g,Dn as ne,Dr as re,Dt as ie,E as ae,Ei as oe,Er as se,Et as ce,Fn as le,Fr as ue,Ft as de,G as fe,Gn as pe,Gr as me,Gt as he,H as ge,Hn as _e,Hr as ve,Ht as ye,I as be,Ir as xe,It as Se,J as Ce,Ja as we,Ji as Te,Jn as Ee,Jt as De,K as Oe,Ki as ke,Kn as Ae,Kr as je,Kt as Me,L as Ne,Ln as Pe,Lr as Fe,Lt as Ie,M as Le,Mi as Re,Mn as ze,Mr as Be,Mt as Ve,N as He,Ni as Ue,Nn as We,Nr as Ge,Nt as Ke,O as qe,Or as Je,Ot as Ye,P as Xe,Pi as Ze,Pn as Qe,Pr as $e,Pt as et,Qi as tt,Qr as nt,Qt as rt,R as it,Rn as at,Rr as ot,Rt as st,S as ct,Sa as lt,Si as ut,Sn as dt,St as ft,T as pt,Ti as mt,Tn as ht,Tr as gt,Tt as _t,U as vt,Ur as yt,Ut as bt,V as xt,Vn as St,Vr as Ct,Vt as wt,W as Tt,Wr as _,Wt as Et,X as Dt,Xi as Ot,Xn as kt,Xr as At,Xt as jt,Y as Mt,Yi as Nt,Yr as v,Yt as Pt,Z as Ft,Za as It,Zi as Lt,Zn as Rt,Zt as zt,_ as Bt,_a as Vt,_i as Ht,_n as Ut,_r as Wt,_t as Gt,a as y,aa as Kt,ai as qt,an as Jt,ar as Yt,at as Xt,b as Zt,bi as Qt,bn as $t,bt as en,c as tn,ca as nn,ci as rn,cn as an,cr as on,ct as sn,d as cn,da as ln,di as un,dn,dt as fn,ea as pn,ei as mn,en as hn,eo as gn,et as _n,f as vn,fa as yn,fi as bn,fn as xn,fr as Sn,ft as b,g as x,ga as Cn,gi as wn,gn as Tn,gr as En,h as Dn,hi as On,hn as kn,hr as An,ht as jn,i as Mn,ia as Nn,in as Pn,ir as Fn,it as In,j as S,ji as Ln,jn as Rn,jr as zn,jt as Bn,k as Vn,ki as Hn,kn as Un,kr as Wn,kt as Gn,l as Kn,la as C,li as qn,ln as Jn,lt as Yn,m as Xn,ma as Zn,mi as Qn,mn as $n,mr as er,mt as w,na as tr,ni as nr,nn as rr,nr as ir,nt as ar,o as or,oi as sr,on as cr,ot as lr,p as ur,pa as dr,pi as fr,pn as pr,pr as mr,pt as hr,q as gr,qn as _r,qr as vr,qt as yr,r as br,ra as xr,ri as Sr,rn as Cr,rr as wr,rt as Tr,s as Er,sa as Dr,si as Or,sn as kr,sr as Ar,t as jr,ti as Mr,tn as Nr,tr as Pr,tt as Fr,u as Ir,ua as Lr,ui as Rr,un as zr,ur as Br,v as Vr,va as T,vi as Hr,vn as Ur,vr as Wr,vt as Gr,w as Kr,wi as qr,wn as Jr,wr as Yr,wt as Xr,x as Zr,xa as Qr,xi as $r,xn as ei,xr as ti,xt as ni,y as E,ya as ri,yi as ii,yn as ai,yr as oi,yt as si,z as ci,zr as li,zt as ui}from"./Effect-CtszBD7f.js";import{l as di,t as fi}from"./preload-helper-DY31Aviq.js";var pi=e=>e>0?Math.floor(e):0,mi=e=>Math.max(1,pi(e)),hi=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},gi=`~effect/BigDecimal`,_i={[gi]:gi,[qn](){let e=Ti(this);return qt(rn(String(e.value)),Or(e.scale))},[Sr](e){return vi(e)&&Ai(this,e)===0},toString(){return`BigDecimal(${Mi(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[yt](){return this.toJSON()},pipe(){return Ze(this,arguments)}},vi=e=>Rr(e,gi),yi=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(_i);return n.value=e,n.scale=t,n},bi=(e,t)=>{let n=yi(e,t);return n.normalized=n,n},xi=BigInt(0),Si=BigInt(1),Ci=BigInt(10),wi=bi(xi,0),Ti=e=>{if(e.normalized===void 0){if(e.value===xi)e.normalized=wi;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=bi(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Ei=100,Di=[Si],Oi=(e,t)=>e===t?0:e<t?-1:1,ki=(e,t)=>{let n=`${e.value<xi?-e.value:e.value}`,r=`${t.value<xi?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==xi)return i<xi?-1:1;let a=Math.max(n.length,r.length);return An(n.padEnd(a,`0`),r.padEnd(a,`0`))},Ai=(e,t)=>{if(e.scale===t.scale)return Oi(e.value,t.value);let n=ji(e),r=ji(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>Ei)return n===-1?ki(t,e):ki(e,t);let o=Di[a]??=Ci**BigInt(a);return i>0?Oi(e.value,t.value*o):Oi(e.value*o,t.value)},ji=e=>e.value===xi?0:e.value<xi?-1:1,Mi=e=>{let t=Ti(e);if(Math.abs(t.scale)>=16)return Ni(t);let n=t.value<xi,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},Ni=e=>{if(Pi(e))return`0e+0`;let t=Ti(e),n=`${t.value}`,r=t.value<xi?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Pi=e=>e.value===xi,Fi=Yr,Ii=`~effect/encoding/EncodingError`,Li=class extends Fi(`EncodingError`){[Ii]=Ii},Ri=Fe,zi=Je,Bi=re,Vi=se,Hi=hn,Ui=Ve,Wi=et,Gi=jt,Ki=zt,qi=Pt,Ji=Ke,Yi=ue,Xi=Wn,Zi=ie;a()(`effect/Cause/StackTrace`),a()(`effect/Cause/InterruptorStackTrace`);var Qi=$e,$i=Ge,ea=Be,ta=zn,na=bt,ra=wt,ia=d,aa=ye,oa=st,sa={"~effect/Deferred":{_A:Hn,_E:Hn},pipe(){return Ze(this,arguments)}},ca=function(){this.resumes=void 0,this.effect=void 0};ca.prototype=sa;var la=()=>new ca,ua=()=>ai(()=>la()),da=e=>s(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),ai(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),fa=g(2,(e,t)=>ai(()=>ha(e,t))),pa=g(2,(e,t)=>fa(e,Be(t))),ma=g(2,(e,t)=>fa(e,$e(t))),ha=(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},ga=kn,_a=pr,va=$n,ya=cr,ba=Jn,xa=an,Sa=dn,Ca=xn,wa=zr,Ta=ce,Ea=Se,Da=`~effect/DateTime`,Oa=`~effect/DateTime/TimeZone`,ka={[Da]:Da,pipe(){return Ze(this,arguments)},[yt](){return this.toString()},toJSON(){return Ba(this).toJSON()}},Aa={...ka,_tag:`Utc`,[qn](){return Or(this.epochMilliseconds)},[Sr](e){return Ma(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ba(this).toJSON()})`}};({...ka});var ja={[Oa]:Oa,[yt](){return this.toString()}};({...ja}),{...ja};var Ma=e=>Rr(e,Da),Na=e=>e._tag===`Utc`,Pa=e=>{let t=Object.create(Aa);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Fa=e=>{let t=e.getTime();if(Number.isNaN(t))throw new Zi(`Invalid date`);return Pa(t)},Ia=e=>{if(Ma(e))return e;if(e instanceof Date)return Fa(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Fa(new Date(e.epochMilliseconds));let t=new Date(0);return Va(t,e),Fa(t)}return typeof e==`string`&&!La(e)?Fa(new Date(e+`Z`)):Fa(new Date(e))},La=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Ra=Yt(Ia),za=e=>Pa(e.epochMilliseconds),Ba=e=>new Date(e.epochMilliseconds),Va=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Ha=e=>Ba(e).toISOString();globalThis.Number;var Ua=g(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]=Wa(e),[i,a]=Wa(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 Wa(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 Ga=e=>e.trim(),Ka=g(2,(e,t)=>Bn(e,Xa,e=>t(e))),qa=e=>e.reasons.some(Ja),Ja=e=>e._tag===`Fail`&&Yi(e.error),Ya=e=>{let t,n=!1;for(let r of e.reasons)Ja(r)?t??=r.error:r._tag!==`Interrupt`&&(n=!0);return t===void 0?_e(e):n?_e(zi(e.reasons.filter(e=>!Ja(e)))):kt(t)},Xa=e=>{let t=Ya(e);return pe(t)?t:kt(t.success.value)},Za=e=>{let t=Ya(e);return pe(t)?$i(t.failure):Qi(t.success.value)},Qa=Un(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),$a=Un(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),eo=`~effect/Metric`,to=class{[eo]=eo;#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=We(e,Qa);t!==this.#e&&(this.#e=t,this.#t=co(this,uo(this.attributes,t)));let n=We(e,$a),r=n.get(this.#t);return p(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?uo(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return Ze(this,arguments)}},no=BigInt(0),ro=class extends to{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,fo(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?no:0,t=this.#t?this.#e?e=>e>=no:e=>e>=0:e=>!0;return lo(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},io=class extends to{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()}},ao=(e,t)=>new ro(e,t),oo=g(2,(e,t)=>de(n=>ai(()=>e.updateUnsafe(t,n)))),so=g(2,(e,t)=>{let n=po(t);return new io(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function co(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 lo(e,t,n){return{get:e,update:t,modify:n??t}}function uo(e,t){return{...fo(e),...fo(t)}}function fo(e){return wn(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(v(e,t,n),e),{}):e}function po(e){let t,n={};return r=>{let i=We(r,Qa);return i!==t&&(t=i,n=uo(i,e)),Rn(r,Qa,n)}}var mo=Ma,ho=Na,go=Ia,_o=Ra,vo=za;a()(`effect/DateTime/CurrentTimeZone`);var yo=Ha,bo=e=>So(typeof e==`string`?Co.encode(e):e),xo=e=>{let t=wo(e),n=t.length;if(n%4!=0)return _e(new Li({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 _e(new Li({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=Do(t.charCodeAt(e))<<18|Do(t.charCodeAt(e+1))<<12|Do(t.charCodeAt(e+2))<<6|Do(t.charCodeAt(e+3));r[i]=n>>16,r[i+1]=n>>8&255,r[i+2]=n&255}return kt(r)}catch(e){return _e(new Li({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},So=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=To[e[r-2]>>2],n+=To[(e[r-2]&3)<<4|e[r-1]>>4],n+=To[(e[r-1]&15)<<2|e[r]>>6],n+=To[e[r]&63];return r===t+1&&(n+=To[e[r-2]>>2],n+=To[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=To[e[r-2]>>2],n+=To[(e[r-2]&3)<<4|e[r-1]>>4],n+=To[(e[r-1]&15)<<2],n+=`=`),n},Co=new TextEncoder,wo=e=>e.replace(/[\n\r]/g,``),To=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Eo=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Eo[To.charCodeAt(e)]=e;Eo[61]=0;var Do=e=>{if(e>=Eo.length||Eo[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Eo[e]};Fi(`CookiesError`),{...ve},{...ve};var Oo=new WeakMap,ko=`~effect/Redacted`,Ao=e=>Rr(e,ko),jo=(e,t)=>{let n=Object.create(Mo);return t?.label&&(n.label=t.label),Oo.set(n,e),n},Mo={[ko]:{_A:e=>e},label:void 0,...ee,toJSON(){return this.toString()},toString(){return`<redacted${$r(this.label)?`:`+this.label:``}>`},[qn](){return sr(Oo.get(this))},[Sr](e){return Ao(e)&&mn(Oo.get(this),Oo.get(e))}};({...ee});function No(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Po(e){return t=>No(t)?.[e]}var Fo=`~structural`,Io=`~identifier`,Lo=`~sentinels`,Ro=`~constructor`,zo=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],Bo=Po(`identifier`),Vo=Po(Io),Ho=Po(`title`),Uo=Po(`description`),Wo=i(e=>{let t=No(e)?.identifier;return typeof t==`string`?t:e.getExpected(Wo)}),Go=new Set([Lo,Fo,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),D=Symbol(),Ko=Qi,qo=Ko(D),Jo=Ko(D),Yo=e=>e===D?on():Br(e),Xo=e=>e._tag===`None`?qo:Ko(e.value),Zo=`~effect/SchemaIssue/Issue`;function Qo(e){return Rr(e,Zo)&&e[Zo]===Zo}function $o(e){return Object.hasOwn(e,`input`)}var es=class{[Zo]=Zo;constructor(e,t){t?.reportInput===!0&&e!==D&&(this.input=e)}},ts=class extends es{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},ns=class extends es{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},rs=class extends es{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},is=class extends es{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},as=class extends es{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},os=class extends es{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ss=class extends es{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},cs=class extends es{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},ls=class extends es{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},us=class extends es{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ds=class extends es{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function fs(e,t,n){if(Qo(e))return e;if(typeof e==`string`)return new cs({message:e},t,n);let r=typeof e.issue==`string`?new cs({message:e.issue},t,n):e.issue;return new rs(e.path,r)}function ps(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new cs(void 0,t,n):fs(e,t,n)}function ms(e,t,n,r){return Array.isArray(t)?at(t)?t.length===1?fs(t[0],n,r):new os(e,l(t,e=>fs(e,n,r)),n,r):void 0:ps(t,n,r)}var hs=e=>{let t=Es(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return bs(Wo(e.ast),e);case`InvalidValue`:{let t=ys(e);if(t!==void 0)return bs(t,e);let n=vs(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=vs(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=vs(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},gs=e=>Es(e.issue)??Es(e);function _s(e){return t=>({issues:xs(t,[],e?.leafHook??hs,e?.checkHook??gs)})}function vs(e){return $o(e)?_(e.input):void 0}function ys(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function bs(e,t){let n=vs(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function xs(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 xs(e.issue,t,n,r);let a=ys(e.issue);return[{path:t,message:a===void 0?bs(Ss(e.filter),e):bs(a,e.issue)}]}case`Encoding`:return xs(e.issue,t,n,r);case`Pointer`:return xs(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>xs(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:Es(e)??bs(Wo(e.ast),e)}]:e.issues.flatMap(e=>xs(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Ss(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=>Ss(e)).join(` & `)}}function Cs(){return e=>Ts(e,``)}var ws=Cs();function Ts(e,t){let n;switch(e._tag){case`Filter`:{let r=gs(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return Ts(e.issue,t);let r=ys(e.issue);n=r===void 0?bs(Ss(e.filter),e):bs(r,e.issue)}break}case`Encoding`:return Ts(e.issue,t);case`Pointer`:return Ts(e.issue,t+je(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>Ts(e,t)).join(`
3
- `);n=Es(e)??bs(Wo(e.ast),e);break;default:n=hs(e)}return t?`${n}\n at ${t}`:n}function Es(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Es(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 Ds(e){let t;for(let n of e.reasons){if(!Ri(n)||!Qo(n.error))return;t??=n.error}return t}function Os(e,t){let n=Ds(e);if(n===void 0)throw Error(t,{cause:e});return n}var ks=e=>bo(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),As=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return _e(new Li({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 _e(new Li({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,`/`),xo(r)},js=e=>Object.assign(Object.create(Ue),e);function Ms(e){return Vs((t,n)=>x(e(t,n)))}function Ns(e){return Ms((t,n)=>{let r={message:e(t)};return Fn(t)?new ls(r,t.value,n):new ls(r)})}var Ps=Ns(()=>`Encoding is not supported`),Fs=js({_tag:`Passthrough`});function Is(){return Fs}function Ls(){return Fs}function Rs(e){return js({_tag:`Transform`,transform:e})}function zs(e){return js({_tag:`TransformEffect`,transform:e})}function Bs(e){return js({_tag:`TransformOptional`,transform:e})}function Vs(e){return js({_tag:`TransformOptionalEffect`,transform:e})}function Hs(){return Bs(()=>on())}function Us(e){return Vs(t=>{let n=Rt(t,wn);return Fn(n)?b(n):Ne(e,Br)})}function Ws(){return Rs(globalThis.String)}function Gs(){return Rs(globalThis.Number)}function Ks(){return Rs(globalThis.BigInt)}function qs(){return Rs(e=>new globalThis.Date(e))}function Js(){return Rs(Ga)}function Ys(e){return zs((t,n)=>en({try:()=>JSON.parse(t,e?.reviver),catch:()=>new cs({expected:`a valid JSON string`},t,n)}))}function Xs(e){return zs((t,n)=>en({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 cs({expected:`a JSON-serializable value`},t,n)}))}function Zs(){return Rs(bo)}function Qs(){return zs((e,t)=>ci(r(xo(e)),()=>new cs({expected:`a valid Base64 string`},e,t)))}var $s=class extends Re{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new $s(this.encode,this.decode)}},ec=`~effect/SchemaTransformation/Transformation`,tc=class extends Re{[ec]=ec;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new tc(this.encode,this.decode)}};function nc(e){return Rr(e,ec)&&e[ec]===ec}var rc=e=>nc(e)?e:new tc(e.decode,e.encode);function ic(e){return new tc(zs(e.decode),zs(e.encode))}function ac(){return new tc(Js(),Is())}var oc=new tc(Is(),Is());function sc(){return oc}var cc=new tc(Gs(),Ws()),lc=new tc(Ks(),Ws()),uc=new tc(qs(),Rs(me)),dc=new tc(Qs(),Zs());function fc(e){return new tc(Ys(e??{}),Xs(e))}function pc(e){return t=>t._tag===e}var mc=pc(`Declaration`),hc=pc(`Null`),gc=pc(`Undefined`),_c=pc(`Never`),vc=pc(`String`),yc=pc(`Number`),bc=pc(`Boolean`),xc=pc(`Literal`),Sc=pc(`UniqueSymbol`),Cc=pc(`Arrays`),wc=pc(`Objects`),Tc=pc(`Union`),Ec=pc(`Suspend`),Dc=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Oc={},kc=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}},Ac=`~effect/Schema`,jc=class{[Ac]=Ac;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}>`}},Mc=class extends jc{_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===D?qo:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=au(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Mc(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>`}},Nc=new class extends jc{_tag=`Null`;getParser(){return Eu(this,null)}getExpected(){return`null`}},Pc=class extends jc{_tag=`Undefined`;getParser(){return Eu(this,void 0)}toCodecJson(){return ql(this,[Fc])}getExpected(){return`undefined`}},Fc=new Dc(Nc,new tc(Rs(()=>void 0),Rs(()=>null))),Ic=new Pc,Lc=new class extends jc{_tag=`Never`;getParser(){return Du(this,Qn)}getExpected(){return`never`}},Rc=new class extends jc{_tag=`Unknown`;getParser(){return Du(this,qr)}getExpected(){return`unknown`}},zc=class extends jc{_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 Eu(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Bc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Bc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Bc(e){let t=globalThis.String(e.literal);return ql(e,[new Dc(new zc(t),new tc(Rs(()=>e.literal),Rs(()=>t)))])}var Vc=new class extends jc{_tag=`String`;getParser(){return Du(this,$r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Uu(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Hc=class extends jc{_tag=`Number`;getParser(){return Du(this,Ht)}matchKey(e,t){return this._match(Mu,e,t)}matchPart(e,t){return this._match(ju,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Uu(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Uc(this.checks,`effect/schema/isFinite`)||Uc(this.checks,`effect/schema/isInt`))?this:ql(this,[Hl])}toCodecStringTree(){return this.toCodecJson()===this?ql(this,[Fu]):ql(this,[Iu])}getExpected(){return`number`}};function Uc(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Uc(e.checks,t))}var Wc=new Hc,Gc=new class extends jc{_tag=`Boolean`;getParser(){return Du(this,bn)}getExpected(){return`boolean`}},Kc=new class extends jc{_tag=`Symbol`;getParser(){return Du(this,ut)}matchKey(e,t){return t.disableChecks||!this.checks?e:Uu(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return ql(this,[Vu])}getExpected(){return`symbol`}},qc=new class extends jc{_tag=`BigInt`;getParser(){return Du(this,un)}matchPart(e,t){if(!Lu.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Uu(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return ql(this,[zu])}getExpected(){return`bigint`}},Jc=class extends jc{_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(gu(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(gu(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 as(n,t[o],i),a=new rs([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return x(new os(n,[a],t,i))}return e.issues?x(new os(n,e.issues,t,i)):Ko(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:kr(t.concurrency),f=d===1?Zc(i,e,0,u):Qc(i,e,{concurrency:d,end:u});if(!f)return c(i);if(Ie(f))return Zt(f,()=>c(i));let p=!0;return hr(()=>p?(p=!1,E(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===D)return qo;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)):x(new ss(n,e,a))}catch(e){return ur(e)}}}_rebuild(e,t,n){let r=au(this.elements,e),i=au(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new Jc(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 Yc(e,t,n,r){if(n._tag===`Failure`)return $c(e,e.ast,r,n);let i=n===Jo?t:n[gt];if(i!==D)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(gu(t.ast))return;let n=new rs([r],new is(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return ea(new os(e.ast,[n],e.input,e.options))}}var Xc={onItem(e,t,n){let r=n<e.len?t:D;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:Yc},Zc=rr()(Xc),Qc=Nr()(Xc),$c=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Ds(r.cause);if(i===void 0)return $i(Ui(r.cause,r=>new os(t,[new rs([n],r)],e.input,e.options)));let a=new rs([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return ea(new os(t,[a],e.input,e.options))},el=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function tl(e,t,n=Oc){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(Ou(Su(t)))}var nl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function rl(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(rl);default:return!1}}function il(e){let t=Yl(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(il);default:return!1}}function al(e){return rl(e)&&il(e)}var ol=class{parameter;type;constructor(e,t){if(!al(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,gu(t)&&!Tu(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},sl=class extends jc{_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 Du(n,On);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(Ou(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 $c(t,n,i,s)??na;let c=s===Jo?o:s[gt];if(a!==D&&c!==D){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return na;v(t.out,a,c)}return na},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!Ie(t))return E(Dn(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return $c(e,n,r,a)??na;let o=a===Jo?r:a[gt],s=e.input[r],l=i.parserValue(s,e.options);return Ie(l)?t(e,r,o,s,l):E(Dn(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return Ie(a)?t(e,n,n,i,a):E(Dn(a),r=>t(e,n,n,i,r))},u=i?Nr()({onItem:(e,[t,n])=>n.is.parameter===Vc?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return f(function*(t,d){if(t===D)return D;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*x(new ss(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},ee=d.errors===`all`,h=d.onExcessProperty===`error`,te=d.concurrency===void 0?1:kr(d.concurrency),g=i&&h?n.indexSignatures.map(e=>tl(f,e.parameter,d)):void 0;if(h){let r=g?new Set(e):e;if(g)for(let e of g)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 as(n,f[a],d),r=new rs([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*x(new os(n,[r],t,d))}}}if(r){let e=te===1?ul(m,a):dl(m,a,{concurrency:te});e&&(yield*e)}if(i&&te===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===Vc?l:c,r=g?.[e]??(t.is.parameter===Vc?Object.keys(f):tl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!Ie(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=le();for(let t=0;t<i;t++){let n=o[t],r=g?.[t]??(n.is.parameter===Vc?Object.keys(f):tl(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:te});t&&(yield*t)}return m.issues?yield*x(new os(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return E(Dn(n),n=>{let i=cl(e,r,n);if(i)return i;let o=()=>Ko(e.out),s=ul(e,a.slice(t+1));return s?Zt(s,o):o()})};return(e,t)=>{if(e===D)return qo;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&kr(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return x(new ss(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=wl(i,s),l=c?i[s]:D,d=n.parser(l,t);if(!Ie(d))return u(o,e,d);if(d===Jo){c&&v(a,s,l);continue}let f=cl(o,n,d);if(f)return f}}catch(e){return ur(e)}return Ko(a)}}_rebuild(e,t,n,r){let i=au(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new nl(t.name,n)}),a=au(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new ol(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new sl(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 cl(e,t,n){if(n._tag===`Failure`)return $c(e,e.ast,t.name,n);if(n===Jo)return;let r=n[gt];if(r!==D){v(e.out,t.name,r);return}if(delete e.out[t.name],!gu(t.type)){let n=new rs([t.name],new is(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return ea(new os(e.ast,[n],e.input,e.options))}}var ll={onItem(e,t){if(!wl(e.input,t.name))return t.parser(D,e.options);let n=e.input[t.name];return v(e.out,t.name,n),t.parser(n,e.options)},step:cl},ul=rr()(ll),dl=Nr()(ll);function fl(e,t){return e?t?[...e,...t]:e:t}function pl(e,t,n){return new sl(Reflect.ownKeys(e).map(t=>new nl(t,e[t].ast)),[],n,t)}function ml(e){return e.ast}function hl(e,t=void 0){return new Jc(!1,e.map(e=>e.ast),[],void 0,t)}function gl(e,t,n){return new El(e.map(ml),t,void 0,n)}function _l(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new Jc(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var vl=Ln(e=>{for(;;){if(Ec(e))return Rc;let t=e.encoding;if(!t)return e.recur?.(vl,Hn)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==Hn))return Rc;e=t[t.length-1].to}});function yl(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(yl)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function bl(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Lo];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!gu(t)){if(xc(t))return[{key:e.name,literal:t.literal}];if(Sc(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!gu(e)){if(xc(e))return[{key:t,literal:e.literal}];if(Sc(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>bl(vl(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return bl(e.thunk())}}var xl=new WeakMap,Sl=Object.freeze([]),Cl=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,wl=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function Tl(e){let t=xl.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=vl(c);if(_c(l))continue;if(xc(l)||Sc(l)){a??=new Map;let e=xc(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=bl(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=yl(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Sl);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Sl;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(ii(e)){let n=wl(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Sl;if(t)return o}return Sl}}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=Cl(t);if(!ii(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=wl(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=wl(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=wl(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(Cl(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return xl.set(e,t),t}var El=class extends jc{_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===D)return qo;let i=(o??=Tl(n.types))(e,r);if(i.length===0)return x(new us(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:Ie(r)?Dl(n,r.cause,e,t):Ol(n,r,e,t)}return kl(n,a,i,e,t)}}_rebuild(e,t,n){let r=au(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new El(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=Su(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(xc);if(t.length>0)return`${Nl(n.isMutable)}[ ${t.map(t=>e(t)+Pl(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>xc(e.type));if(t.length>0)return`{ ${t.map(t=>`${Nl(t.type.context?.isMutable)}${vr(t.name)}${Pl(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Dl(e,t,n,r){let i=Ds(t);return i?ea(new us(e,[i],n,r)):$i(t)}function Ol(e,t,n,r){return Ir(t,t=>Dl(e,t,n,r))}function kl(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=jl(a,n);if(!o)return a.out?a.out:x(new us(e,a.issues??[],r,i));if(Ie(o))return Al(o,a);let s=!0;return hr(()=>s?(s=!1,Al(o,a)):kl(e,t,n,r,i))}function Al(e,t){return Zt(e,e=>t.out===Jo?b(t.input):t.out?t.out:x(new us(t.ast,t.issues??[],t.input,t.options)))}var jl=rr()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Ds(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]),ea(new ds(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return na}}}),Ml=new El([new zc(`Infinity`),new zc(`-Infinity`),new zc(`NaN`)]);function Nl(e){return e?``:`readonly `}function Pl(e){return e?`?`:``}var Fl=class extends jc{_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 Fl(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Il=class extends Re{_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 Il(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Il(this.run,this.annotations,!0)}and(e,t){return new Ll([this,e],t)}},Ll=class extends Re{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ll(this.checks,{...this.annotations,...e})}and(e,t){return new Ll([this,e],t)}};function Rl(e,t,n=!1){return new Il((t,n,r)=>ms(n,e(t,n,r),t,r),t,n)}function zl(e,t){return new Il((t,n,r)=>e(t)?void 0:new cs(void 0,t,r),t,!0)}function Bl(e){return Rl(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 Vl=Ql(Wc,[Bl()]),Hl=new Dc(new El([Vl,Ml]),new tc(Gs(),Rs(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Ul(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Rl(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 Wl=new WeakMap;function Gl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Wl.set(n,Kl(e)),n}function Kl(e){let t=Wl.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 Wl.set(e,n),n}function ql(e,t){return e.encoding===t?e:Gl(e,{encoding:t})}function Jl(e,t){if(e.context===t)return e;let n=Kl(e);return n.context===t&&n.encoding===e.encoding?n:Gl(e,{context:t})}function Yl(e){return e.encoding?Yl(e.encoding[e.encoding.length-1].to):e}function Xl(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return Zl(e,Qe(e.checks.slice(0,-1),n.annotate(t)))}return Gl(e,{annotations:{...e.annotations,...t}})}function Zl(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Gl(e,{checks:t})}function Ql(e,t){return Zl(e,fl(e.checks,t))}function $l(e,t){let n=t(e.to);return n===e.to?e:new Dc(n,e.transformation)}function eu(e,t){let n=e,r=n[n.length-1],i=$l(r,t);return i===r?e:Qe(e.slice(0,e.length-1),i)}function tu(e){return t=>t.encoding?ql(t,eu(t.encoding,e)):t}function nu(e,t){return tu(e=>Jl(e,t))(e)}function ru(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:ql(r,eu(r.encoding,n))}return e(r)}return Ln(n)}function iu(e,t,n){let r=new Dc(e,t);return ql(n,n.encoding?[...n.encoding,r]:[r])}function au(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 ou(e,t){return Jl(e,e.context?new kc(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new kc(!1,!1,void 0,t))}var su=Ln(e=>cu(Jl(e,e.context?e.context.isOptional===!1?new kc(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new kc(!0,!1)))),cu=tu(su),lu=i(e=>su(new El([e,Ic]))),uu=Ln(e=>du(Jl(e,e.context?e.context.isMutable===!1?new kc(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new kc(!1,!0)))),du=tu(uu);function fu(e,t){return Jl(e,e.context?new kc(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new kc(!1,!1,t))}function pu(e,t,n){return iu(e,n,t)}function mu(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:Qt(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 hu(e,t){let{literals:n,parameters:r}=mu(e);return new sl(n.map(e=>new nl(e,t)),r.map(e=>new ol(e,t)))}function gu(e){return e.context?.isOptional??!1}function _u(e){return e.context?.isMutable??!1}function vu(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(vu)}function yu(e){function t(e){return vu(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return Pe(n)?n:void 0}function bu(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Ec(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var xu=Ln(e=>{let t=Kl(e);if(t!==e){let n=xu(t);return n===t&&e.encoding===void 0?e:Jl(n,e.context)}let n=`recur`in e?e.recur(xu):e;if(`encodingChecks`in n&&n.encodingChecks){let t=bu(e)?n.encodingChecks:Cc(n)||wc(n)||mc(n)&&n.typeParameters.length>0?yu(n.encodingChecks):void 0;return Gl(n,{encodingChecks:void 0,checks:fl(n.checks,t)})}return n}),Su=Ln(e=>xu(wu(e)));function Cu(e,t){let n=t,r=n.length,i=n[r-1],a=[new Dc(wu(ql(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Dc(wu(n[e-1].to),n[e].transformation.flip()));let o=wu(i.to);return o.encoding?ql(o,[...o.encoding,...a]):ql(o,a)}var wu=i(e=>{if(e.encoding)return Cu(e,e.encoding);let t=Kl(e);if(t!==e){let n=wu(t);return n===t?e:Jl(n,e.context)}return`flip`in e?e.flip(wu):`recur`in e?e.recur(wu):e});function Tu(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(Tu);default:return!1}}function Eu(e,t){let n=t===0?Jo:Ko(t);return(r,i)=>r===D?qo:r===t?n:x(new ss(e,r,i))}function Du(e,t){return(n,r)=>n===D?qo:t(n)?Jo:x(new ss(e,n,r))}var Ou=ru(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Ou)}}),ku=ru(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(ku)}}),Au=`[\\s\\S]*?`,ju=new globalThis.RegExp(`^${el}$`),Mu=new globalThis.RegExp(`^(?:${el}|Infinity|-Infinity|NaN)$`);function Nu(e){return Ul(ju,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:ju.source}),...e})}var Pu=Ql(Vc,[Nu()]),Fu=new Dc(Pu,cc),Iu=new Dc(new El([Pu,Ml]),cc),Lu=new globalThis.RegExp(`^-?\\d+$`);function Ru(e){return Ul(Lu,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Lu.source}),...e})}var zu=new Dc(Ql(Vc,[Ru({expected:`a string representing a bigint`})]),lc),Bu=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),Vu=new Dc(Ql(Vc,[Hu()]),new tc(Rs(e=>globalThis.Symbol.for(Bu.exec(e)[1])),zs((e,t)=>globalThis.Symbol.keyFor(e)===void 0?x(new ls({message:`cannot serialize to string, Symbol is not registered`},e,t)):b(globalThis.String(e)))));function Hu(e){return Ul(Bu,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:Bu.source}),...e})}function Uu(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Uu(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 ts(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Wu(e){if(!mc(e))return;let t=e.annotations?.[Ro];return fr(t)?t(e.typeParameters):void 0}var Gu=No,Ku=Ho,qu=Uo;function Ju(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function Yu(e){return e===void 0||typeof e==`string`}function Xu(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 Zu(e){return Xu(e,Ju)}var Qu=new Mc([],()=>(e,t,n)=>Zu(e)?Jo:x(new ss(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>nd}),$u=new Dc(Qu,sc()),ed=new Dc(new El([new Jc(!1,[],[Qu]),new sl([],[new ol(Vc,Qu)])]),sc());function td(e){return Xu(e,Yu)}var nd=new Dc(new Mc([],()=>(e,t,n)=>td(e)?Jo:x(new ss(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),sc()),rd=(e,t,n)=>e===Jo?n(t):Zt(e,n);function id(e){if(e._tag===`Middleware`)return(t,n,r)=>ad(t===Jo?e.decode(Ko(Yo(n)),r):e.decode(Ne(t,Yo),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===Jo?Ko(t):e;case`Transform`:{let e=e=>e===D?qo:Ko(t.transform(e));return(t,n)=>rd(t,n,e)}case`TransformOptional`:{let e=e=>Xo(t.transform(Yo(e)));return(t,n)=>rd(t,n,e)}case`TransformEffect`:return(e,n,r)=>rd(e,n,e=>e===D?qo:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>rd(e,n,e=>ad(t.transform(Yo(e),r)))}}var ad=e=>Zt(e,Xo),od=(e,t,n,r)=>Ir(r,r=>Vr(()=>Ui(r,r=>new ns(e,r,t,n))));function sd(e,t){let n=id(e.link.transformation),r;return(i,a)=>{if(i===D)return qo;if(e.isConstructed(i))return Jo;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function cd(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==D&&r!==void 0)return t(r,i);let a=n;if(Ie(a)&&a._tag===`Success`){let e=t(a[gt],i);return e===Jo?a:e}return Zt(od(e,r,i,a),e=>{let n=t(e,i);return n===Jo?Ko(e):n})}}function ld(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:cd(e,n)}function ud(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Wu(e):void 0,o=a?sd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>id(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(Ie(r)){if(r._tag===`Success`){let i=r===Jo?t:r[gt];if(t!==D&&i!==D){let i=Uu(u,t,void 0,e,n);i&&(r=x(new os(e,i,t,n)))}}}else r=E(r,r=>{if(t!==D&&r!==D){let r=Uu(u,t,void 0,e,n);if(r)return x(new os(e,r,t,n))}return b(r)})}if(s&&!n.disableChecks){if(Ie(r)){if(r._tag===`Success`){let i=r===Jo?t:r[gt];if(i===D)return r;let a=Uu(s,i,void 0,e,n);a&&(r=x(new os(e,a,i,n)))}}else r=E(r,t=>{if(t!==D){let r=Uu(s,t,void 0,e,n);if(r)return x(new os(e,r,t,n))}return b(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[gt],o=t(a,r)):o=Zt(o,e=>{let n=t(e,r);return n===Jo?Ko(e):n})}if(o._tag===`Success`){let e=o[gt],t=p(e,r);return t===Jo?o:t}return o=od(e,n,r,o),Zt(o,e=>{let t=p(e,r);return t===Jo?Ko(e):t})}:p}var dd=Symbol(),fd=new WeakMap,pd=e=>_d(e).parser,md=e=>_d(e).makeEffect,hd=e=>ld(e,md),gd=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=ud(this.ast,pd)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=ud(this.ast,md,hd)}};function _d(e){let t=fd.get(e);if(t!==void 0)return t;let n=new gd(e);return fd.set(e,n),n}function vd(e){let t=e.ast,n;return(e,r)=>(n??=Fd(Hd,xu(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function yd(e){let t=vd(e);return(e,n)=>{let r=lr(t(e,n));return ra(r)?Br(r.value):(Os(r.cause,`Option adapter can only return none for schema issues`),on())}}function bd(e){return Bd(xu(e.ast))}function xd(e){return Cd(e.ast)}function Sd(e){{let t=Id(Nd(e));return e=>{let n=t(e,Oc);return ra(n)?!0:(Os(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function Cd(e){let t=xu(e),n=e=>(n=Sd(t),n(e));return e=>n(e)}function wd(e,t){let n=Nd(e.ast);return t===void 0?n:(e,r)=>n(e,jd(t,r))}function Td(e,t){return Id(wd(e,t))}function Ed(e,t){return Ld(wd(e,t))}function Dd(e,t){return Rd(wd(e,t))}function Od(e,t){let n=Nd(wu(e.ast));return t===void 0?n:(e,r)=>n(e,jd(t,r))}function kd(e,t){return Id(Od(e,t))}function Ad(e,t){return Rd(Od(e,t))}var jd=(e,t)=>t?{...e,...t}:e,Md=e=>e===D?x(new cs):b(e);function Nd(e){return Fd(Vd,e)}function Pd(e,t){return e===Jo?b(t):Ie(e)?e[gt]===D?Md(D):e:Zt(e,Md)}function Fd(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Oc);return a===Jo?b(r):Ie(a)?a[gt]===D?Md(D):a:Zt(a,Md)}}function Id(e){return(t,n)=>lr(e(t,n))}function Ld(e){let t=Id(e);return(e,n)=>{let r=t(e,n);return ra(r)?Br(r.value):(Os(r.cause,`Option adapter can only return none for schema issues`),on())}}function Rd(e){let t=Id(e);return(e,n)=>{let r=t(e,n);return ra(r)?kt(r.value):_e(Os(r.cause,`Result adapter can only return schema issues`))}}function zd(e,t){let n=lr(e);if(ra(n))return n.value;let r=Os(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Bd(e){let t,n;return(r,i)=>{t??=_d(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Oc,o=t.make;if(o!==void 0&&r!==D){let e;try{e=o(r,a)}catch(e){throw Os(Vi(e),`Constructor adapter can only throw schema issues`),e}if(e!==dd&&e!==D)return e}return zd(Pd((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var Vd=e=>_d(e).parser,Hd=e=>_d(e).makeEffect,Ud=`~effect/Schema/Schema`,Wd=Symbol(),Gd={[Ud]:Ud,get make(){let e=bd(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=vd(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=yd(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Ze(this,arguments)},annotate(e){return this.rebuild(Xl(this.ast,e))},annotateKey(e){return this.rebuild(ou(this.ast,e))},check(...e){return this.rebuild(Ql(this.ast,e))},rebuild(e){return Kd(e,this[Wd])}};function Kd(e,t){function n(){}let r=Object.setPrototypeOf(n,Gd);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[Wd]=t,r.ast=e,r}function qd(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Jd(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function Yd(e){return encodeURI(qd(e)).replace(/#/g,`%23`)}function Xd(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 Zd(e){let t=Xd(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(Jd)}function Qd(e){return e.reduce((e,t)=>`${e}/${Yd(t)}`,`#`)}var $d=`http://json-schema.org/draft-07/schema#`;function ef(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function tf(e){return{dialect:`draft-07`,...mf(e,Ef)}}function nf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!Hr(e))return e;let a=r||!i&&pf(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=of(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)}v(o,t,i)}return t(o,a),o}}function rf(e,t){return nf(e,e=>{af(e,t)})}function af(e,t){typeof e.$ref==`string`&&v(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&v(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function of(e,t){if(!Hr(e))return;let n={};for(let r of Object.keys(e))v(n,r,t(e[r],r));return n}function sf(e,t,n){let r=new Map,i=[],a=cf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=uf(Hr(e)?u(e):void 0,cf)??cf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=lf(t,n);if(a!==void 0){let e=Zd(a.hash);if(a.hash=``,e!==void 0){let n=r.get(ff(a.href,e));n!==void 0&&(i=df(t,n))}}v(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(!Hr(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&pf(c)){let e=uf(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 Hr(e)?of(e,(e,i)=>l(e,[...r,t,i],[...a,n,i],s)):e},reference(e,t){typeof t==`string`?i.push([e,t,f]):v(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(ff(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var cf=`https://effect.invalid/.json-schema/`;function lf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function uf(e,t){if(typeof e!=`string`)return;let n=lf(e,t);if(n!==void 0)return n.hash=``,n.href}function df(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${Qd(t)}`}function ff(e,t){return`${e}\u0000${JSON.stringify(t)}`}function pf(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function mf(e,t,n){return sf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:of(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var hf=new Set([`properties`,`patternProperties`]),gf=new Set([`allOf`,`anyOf`,`oneOf`]),_f=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function vf(e,t,n,r,i,a=hf){let o;if(a.has(t))o=r.schemaMap(n,t);else if(gf.has(t))o=r.schemaArray(n,t);else if(i.has(t))o=r.schema(n,t);else return!1;return v(e,t,o),!0}var yf=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...yf],[...yf];var bf=/^[A-Za-z_][-A-Za-z0-9._]*$/,xf=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Sf(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function Cf(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Sf(i,n,`it is not active in ${r} but would become active in the target`)}var wf=[`additionalItems`,`definitions`,`dependencies`];function Tf(e,t,n,r,i){n.isDocumentRoot?v(e,`$schema`,ef(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):ef(t,`https://json-schema.org/draft/2020-12/schema`)||Sf(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Ef(e,t){Cf(e,wf,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!vf(n,o,s,t,_f))switch(o){case`$ref`:r=s;break;case`$schema`:Tf(n,s,t,$d,`Draft-07`);break;case`$id`:case`$anchor`:break;case`$defs`:v(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`:Sf(o,`Draft-07`,`the target dialect has no equivalent`);case`required`:if(Array.isArray(s)&&s.length===0)break;v(n,o,s);break;default:v(n,o,s)}}if(Df(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Sf(`minContains/maxContains`,`Draft-07`,`contains cardinality cannot be represented`),Object.hasOwn(e,`minContains`)&&v(n,`minContains`,t)}else Object.hasOwn(e,`minContains`)&&v(n,`minContains`,e.minContains),Object.hasOwn(e,`maxContains`)&&v(n,`maxContains`,e.maxContains);return kf(e,n,t,`draft-07`),jf(e,n,`$id`,`Draft-07`),Of(n,r,t),n}function Df(e,t,n,r){if(t===void 0){n!==void 0&&v(e,`items`,r.schema(n,`items`));return}v(e,`items`,r.schemaArray(t,`prefixItems`,`items`)),n!==void 0&&v(e,`additionalItems`,r.schema(n,`items`,`additionalItems`))}function Of(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),Af(e,r)}else n.reference(e,t)}}function kf(e,t,n,r){let i=Hr(e.dependentRequired)?e.dependentRequired:void 0,a=Hr(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||v(o,e,t):t===void 0||c?v(o,e,n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e])):v(o,e,{allOf:[n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e,`allOf`,`0`]),{required:t}]})}Object.keys(o).length>0&&v(t,`dependencies`,o)}function Af(e,t){Array.isArray(e.allOf)?e.allOf.push(t):v(e,`allOf`,[t])}function jf(e,t,n,r){let i=e.$id,a=e.$anchor;if(a===void 0){i!==void 0&&v(t,n,i);return}(typeof a!=`string`||!bf.test(a))&&Sf(`$anchor`,r,`the anchor is not valid`),xf.test(a)||Sf(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?v(t,n,`#${a}`):Sf(`$anchor`,r,`it cannot be combined with the schema $id`)}function Mf(e){return Kd(Nf(e.ast),{schema:e})}var Nf=ru(e=>{let t=Rf(e,Nf),n=e.context;return t===e||n===void 0?t:nu(t,Pf(n))});function Pf(e){return e.constructorDefault===void 0?e:new kc(e.isOptional,e.isMutable,void 0,e.annotations)}function Ff(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function If(e){return t=>{let n=[...t].sort((t,n)=>e(Su(t))-e(Su(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Lf=If(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Rf(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!fr(n))return ql(e,[$u]);let r=n(e.typeParameters.map(e=>Kd(Su(e))));return r===void 0?e:ql(e,[$l(r,t)])}case`Unknown`:return ql(e,[$u]);case`ObjectKeyword`:return ql(e,[ed]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Ff(e),e.recur(t,ku);case`Union`:{let n=Lf(e.types);return n===e.types?e.recur(t):new El(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 zf=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Bf(e,t){return t.length>0&&(e+=`\n at ${je(t)}`),Error(e)}function Vf(e){return`#/$defs/${Yd(e)}`}var Hf=new Set([...Go,Io,...zo]);function Uf(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;Zu(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&Zu(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(Zu(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))Hf.has(r)||!t.includeAnnotationKey(r)||Zu(i)&&v(n,r,i);return Object.keys(n).length===0?void 0:n}function Wf(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=Wf(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 Gf(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 Kf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function qf(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function Jf(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var Yf=`|title|description|default|examples|readOnly|writeOnly|`,Xf=Kf+Yf;function Zf(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=Gf(e);if(i!==void 0||a){let r=Wf(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:qf(r.schema,Yf)&&Jf(o,s)?{...o,...r.schema}:Zf(o,r.schema,n)}}if(n&&Jf(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 Qf(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>Qf(e,t)))}function $f(e){return Array.isArray(e)}function ep(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,u=Object.keys(n);for(let e of u)ee(e,[`references`,e]);let d=l(e,(e,n)=>ne(e,t[n],[]));for(let[e,t]of s.values())if(!Qf(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of u){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=>mn(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let f=l(d,h),p={};for(let e of u)a.has(e)||v(p,e,h(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:f,definitions:p};function m(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function ee(e,t){if(!Object.hasOwn(n,e))throw Bf(`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]=ne(n[e],[`references`,e],a[1]),a}function h(e){return rf(e,e=>{let t=Xd(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(Jd(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,Vf(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[Io]:void 0}function g(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)=>ne(e,[...n,`representation`,`schemas`,t],i))??[]}),c=$f(s);c&&i.push(!1);let l=c?s[0]:s,u=Uf(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Kf:Xf;return[d,e._tag===`Filter`&&qf(d,f)&&(u===void 0||qf(u,Yf))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=g(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Uf(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function ne(e,t,n){if(e._tag===`Reference`)return n.push(ee(e.$ref,t)[1]),{$ref:Vf(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=re(e,t,a),c=Uf(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&tp(s.type)?s.type:void 0,i=g(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=Zf(s,...i))}return o.set(e,[s,a]),m(s)}function re(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 ne(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 Bf(`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(rp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Bf(`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=ne(e.type,[...t,`elements`,i,`type`],n),s=Uf(e.annotations,r);return s===void 0?o:m(Zf(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=ne(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 Bf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=ne(s.type,[...t,`propertySignatures`,i,`type`],n),u=Uf(s.annotations,r);v(a,c,u===void 0?l:m(Zf(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=ne(i.type,[...t,`indexSignatures`,r,`type`],n);mn(a,{not:{}})&&(a=!1),l.push(a);let o=ie(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];v(s,e,t===void 0?a:t===!1||a===!1?!1:m(Zf(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(ne(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)=>ne(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=np(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function ie(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw Bf(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(ee(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ie(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=ne(e,t,n);return Qf(n)&&r.type===`string`&&typeof r.pattern==`string`&&qf(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(rp).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=ie(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw Bf(`Invalid schema representation document`,t)}}}function tp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function np(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 rp(e){switch(e._tag){case`Literal`:return zf(globalThis.String(e.literal));case`String`:return Au;case`Number`:return el;case`TemplateLiteral`:return e.parts.map(rp).join(``);case`Union`:return`(?:${e.types.map(rp).join(`|`)})`;default:throw Bf(`Invalid schema representation document`,[])}}function ip(e,t){let n=ep([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var ap=({identifier:e})=>e;function op(e){return e===void 0?void 0:{annotations:e}}function sp(e,t){let{references:n,representations:r}=cp([e],t);return{representation:r[0],references:n}}function cp(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)p(t);let s=t?.referencePolicy??ap;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:l(e,e=>ee(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 u(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:Xl(e,{identifier:n}):Vo(e)===r?e:Xl(e,{[Io]:r})}function d(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=h(t);i.delete(e),v(n,e,r)}return{_tag:`Reference`,$ref:e}}function f(e){let t=Yl(e),n=Kl(t),r=Bo(t),i=r===void 0?(t===e?void 0:Bo(e))??Vo(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 p(e){let t=f(e),n=t.ast;if(t.occurrences++,o.has(t)){t.isRecursive=!0;return}if(!(t.occurrences>1)){switch(o.add(t),m(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(p(e),e));break;case`TemplateLiteral`:n.parts.forEach(p);break;case`Suspend`:p(n.thunk())}o.delete(t)}}function m(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>p(xu(e))),e._tag===`FilterGroup`&&m(e.checks)})}function ee(e){let t=f(e),n=t.ast,r=t.reference;return r===void 0?h(n):d(r,t.identifier===void 0?n:u(n,t,r))}function h(e){let t=te(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>ee(e)),checks:t,...ne(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,...op(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...op(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...op(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...op(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>ee(e)),checks:t,...op(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=Yl(e),n=t.context?.annotations;return{isOptional:gu(t),type:ee(e),...op(n)}}),rest:e.rest.map(e=>ee(e)),checks:t,...op(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=Yl(e.type),n=t.context?.annotations;return{name:e.name,type:ee(e.type),isOptional:gu(t),isMutable:_u(t),...op(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:ee(e.parameter),type:ee(e.type)})),checks:t,...op(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>ee(e)),...e.options===void 0?{}:{options:e.options},checks:t,...op(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:ee(e.thunk()),...op(e.annotations)}}}function te(e){return e?.map(g)??[]}function g(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...re(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:l(e.checks,g),...re(e.annotations)}}}function ne(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 re(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=>ee(xu(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function lp(e){return ra(e)?e.value:{issues:[{message:Ji(e.cause)}]}}function up(e,t){let n=wd(e),r={errors:`all`,...t?.parseOptions},i=_s(t),a=e=>{let t=new dt(`sync`),a=Fr(c(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?lp(o):new Promise(e=>{a.addObserver(t=>{e(lp(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}function dp(e){return ip(sp(Nf(e)))}function fp(e,t){let n=dp(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=tf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function pp(e){let t={input(t){return fp(e.ast,t.target)},output(t){return fp(xu(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 mp=i(e=>hp(e));function hp(e){let n=No(e)?.toEquivalence;if(n)return n(mc(e)?e.typeParameters.map(hp):[]);switch(e._tag){case`Never`:return t();case`Declaration`:return gp(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 mn;case`Arrays`:{let t=e.elements.map(hp),n=e.rest.map(hp),[r,...i]=n,a=i.length;return nt((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 mn;let t=e.propertySignatures.map(e=>hp(e.type)),n=e.indexSignatures.map(e=>hp(e.type));return nt((r,i)=>{if(!Hr(r)||!Hr(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(gu(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=tl(r,a.parameter),s=tl(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=xu(e).types,n=Tl(t),r=t.map((t,n)=>[Cd(t),hp(e.types[n])]);return nt((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 nt((n,r)=>(t??=mp(e.thunk()))(n,r))}}}function gp(e){let t=e.annotations?.representation;if(t===void 0)return mn;switch(t.id){case`effect/schema/Option`:{let[t]=_p(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=_p(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]=_p(e);return vp(t,n)}case`effect/schema/Cause`:{let[t,n]=_p(e);return yp(t,n)}case`effect/schema/Exit`:{let[t,n,r]=_p(e),i=yp(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]=_p(e);return Mr(t,n)}case`effect/schema/ReadonlySet`:return nr(_p(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 mn}}function _p(e){return e.typeParameters.map(hp)}function vp(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 yp(e,t){let n=At(vp(e,t));return(e,t)=>n(e.reasons,t.reasons)}var bp=g(2,(e,t)=>({...e,...t})),xp=e=>e,Sp=`~effect/Schema/SchemaError`;function Cp(e){return Rr(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var wp=Ud;function Tp(){return(e,t,n)=>qp(new Mc(e.map(ml),e=>t(e.map(e=>qp(e))),n))}function Ep(e,t){return Tp()([],()=>(t,n,r)=>e(t)?b(t):x(new ss(n,t,r)),t)}var Dp=class extends Fi(`SchemaError`){[Sp]=Sp;constructor(e){let t=u();Ct(0);try{super({issue:e})}finally{Ct(t)}}get message(){return ws(this.issue)}toString(){return`SchemaError(${this.message})`}};function Op(e){return Cp(e)}function kp(e){return Ie(e)?Ap(e):Ir(e,e=>Vr(()=>Ui(e,e=>new Dp(e))))}function Ap(e){return ra(e)?e:$i(Ui(e.cause,e=>new Dp(e)))}function jp(e,t){let n;for(let r of e.reasons){if(!Ri(r)||!Op(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 Mp(e){let t=lr(e);if(ra(t))return t.value;throw jp(t.cause,`Sync adapter can only throw schema errors`)}function Np(e,t){return up(e,t)}function Pp(e){return pp(e)}var Fp=xd;function Ip(e,t){let n=wd(e,t);return(e,t)=>kp(n(e,t))}function Lp(e,t){let n=Td(e,t);return(e,t)=>Ap(n(e,t))}var Rp=Ed;function O(e,t){let n=Dd(e,t);return(e,t)=>Ee(n(e,t),e=>new Dp(e))}var zp=O;function k(e,t){let n=Ip(e,t);return(e,t)=>Mp(n(e,t))}var Bp=k;function Vp(e,t){let n=Od(e,t);return(e,t)=>kp(n(e,t))}function Hp(e,t){let n=kd(e,t);return(e,t)=>Ap(n(e,t))}function Up(e,t){let n=Ad(e,t);return(e,t)=>Ee(n(e,t),e=>new Dp(e))}var Wp=Up;function Gp(e,t){let n=Vp(e,t);return(e,t)=>Mp(n(e,t))}var Kp=Gp,qp=Kd;function Jp(e){return Rr(e,wp)&&e[wp]===wp}var A=xp(e=>qp(su(e.ast),{schema:e})),j=xp(e=>{let t=fm(e);return qp(lu(e.ast),{schema:t})}),Yp=xp(e=>qp(uu(e.ast),{schema:e})),Xp=xp(e=>qp(xu(e.ast),{schema:e})),Zp=xp(e=>qp(Su(e.ast),{schema:e}));function M(e){let t=qp(new zc(e),{literal:e,transform(n){return t.pipe(gm(M(n),{decode:Rs(()=>n),encode:Rs(()=>e)}))}});return t}var Qp=qp(Lc),$p=qp(Rc),em=qp(Nc),tm=qp(Ic),N=qp(Vc),P=qp(Wc),nm=qp(Gc),rm=qp(Kc),im=qp(qc);function am(e,t){return qp(e,{fields:t,mapFields(e,t){let n=e(this.fields);return am(pl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function F(e){return am(pl(e,void 0),e)}function om(e,t){return qp(hu(e.ast,t.ast),{key:e,value:t})}function sm(e,t){return qp(e,{elements:t,mapElements(e,t){let n=e(this.elements);return sm(hl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function cm(e){return sm(hl(e),e)}var I=xp(e=>qp(new Jc(!1,[],[e.ast]),{value:e})),lm=xp(e=>qp(new Jc(!1,[e.ast],[e.ast]),{value:e})),um=xp(e=>qp(_l(e.ast),{schema:e}));function dm(e,t){return qp(e,{members:t,mapMembers(e,t){let n=e(this.members);return dm(gl(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function L(e,t){return dm(gl(e,t,void 0),e)}function R(e){let t=e.map(M);return qp(gl(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return L(e(this.members))},pick(e){return R(e)},transform(e){return L(t.map((t,n)=>t.transform(e[n])))}})}var z=xp(e=>L([e,em])),fm=xp(e=>L([e,tm]));function pm(e){return qp(new Fl(()=>e().ast))}function B(...e){return t=>t.check(...e)}function mm(e,t){return n=>qp(Ql(n.ast,[zl(e,t)]),{schema:n})}function hm(e){return t=>qp(t.ast,{schema:t,identifier:e})}function gm(e,t){return n=>qp(pu(n.ast,e.ast,t?rc(t):sc()),{from:n,to:e})}function _m(){return(e,t)=>Tm()(e,{decode:t,encode:Ps})}function vm(e,t){return n=>t?gm(n,t)(e):gm(n)(e)}function ym(e){return t=>qp(fu(t.ast,e),{schema:t})}function bm(e){return Ir(e,e=>Vr(()=>Ui(e,e=>e.issue)))}function xm(e,t){let n=t?.encodingStrategy===`omit`?Hs():Is();return t=>j(Zp(t)).pipe(gm(t,{decode:Us(bm(e)),encode:n}))}function Sm(e,t){return n=>Xp(n).pipe(xm(e,t),vm(j(n)))}function Cm(e){return M(e).pipe(ym(b(e)))}function wm(e,t){return Ep(t=>t instanceof e,t)}function Tm(){return(e,t)=>new Dc(e.ast,rc(t))}var V=Rl,Em=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Dm(e){let t=new globalThis.RegExp(Em);return V(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:Em,flags:``}]},...e})}function Om(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${_(n)})`:`new RegExp(${_(n)}, ${_(r)})`;return Ul(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var km=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 Am(e,t){let n=km(e);return Om(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 jm(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Om(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Mm(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 Nm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${zf(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return V(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>Mm(i,e,`^${zf(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Pm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${zf(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return V(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>Mm(i,e,`${zf(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Fm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(zf(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return V(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>Mm(i,e,zf(i)),toCode:()=>({runtime:`Schema.isIncluding(${_(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Im=qp(Vl),Lm=Bl;function Rm(e){let t=En(e.order),n=e.formatter??_;return(r,i)=>V(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function zm(e){let t=Wt(e.order),n=e.formatter??_;return(r,i)=>V(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 Bm(e){let t=Wr(e.order),n=e.formatter??_;return(r,i)=>V(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function Vm(e){let t=oi(e.order),n=e.formatter??_;return(r,i)=>V(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 Hm(e){let t=Wt(e.order),n=En(e.order),r=oi(e.order),i=Wr(e.order),a=e.formatter??_;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return V(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 Um(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${_(e)}`);return e}var Wm=Rm({order:er,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Um(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${_(e)})`})})}),H=zm({order:er,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Um(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${_(e)})`})})}),Gm=Bm({order:er,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Um(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${_(e)})`})})}),Km=Vm({order:er,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Um(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${_(e)})`})})}),qm=Hm({order:er,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Um(e.minimum),maximum:Um(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 Jm(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),V(t=>Ua(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 Ym(e){return V(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 U=P.check(Ym()),Xm=U.check(H(0));function Zm(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${_(e)}`);return e.toISOString()}function Qm(e){return`new Date(${_(e.getTime())})`}var $m=Rm({order:mr,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:Zm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${Qm(e)})`})})}),eh=zm({order:mr,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:Zm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${Qm(e)})`})})}),th=Bm({order:mr,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:Zm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${Qm(e)})`})})}),nh=Vm({order:mr,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:Zm(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${Qm(e)})`})})}),rh=Hm({order:mr,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:Zm(e.minimum),maximum:Zm(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${Qm(e.minimum)}, maximum: ${Qm(e.maximum)}, exclusiveMinimum: ${_(t)}, exclusiveMaximum: ${_(n)} })`})}}}),ih=Rm({order:Sn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${_(e)})`})})}),ah=zm({order:Sn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${_(e)})`})})}),oh=Bm({order:Sn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${_(e)})`})})}),sh=Vm({order:Sn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${_(e)})`})})}),ch=Hm({order:Sn,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 lh(e,t){return e=vh(e),uh(e,Math.ceil(e/2),t)}function uh(e,t,n){return V(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})`}),[Fo]:!0,arbitraryConstraint:{minLength:e},...n})}function dh(e){return uh(1,1,e)}function fh(e,t){return e=vh(e),V(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})`}),[Fo]:!0,arbitraryConstraint:{maxLength:e},...t})}function ph(e,t,n){return e=vh(e),t=vh(t),V(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})`}),[Fo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function mh(e,t){return e=vh(e),V(t=>_h(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 hh(e,t){return e=vh(e),V(t=>_h(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 gh(e,t,n){return e=vh(e),t=vh(t),V(n=>{let r=_h(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 _h(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function vh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function yh(e,t){return e=vh(e),V(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})`}),[Fo]:!0,arbitraryConstraint:{minSize:e},...t})}function bh(e,t){return e=vh(e),V(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})`}),[Fo]:!0,arbitraryConstraint:{maxSize:e},...t})}function xh(e,t,n){return e=vh(e),t=vh(t),V(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})`}),[Fo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function Sh(e,t){return e=vh(e),V(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})`}),[Fo]:!0,arbitraryConstraint:{minProperties:e},...t})}function Ch(e,t){return e=vh(e),V(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})`}),[Fo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function wh(e,t,n){return e=vh(e),t=vh(t),V(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})`}),[Fo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var Th=N.check(dh());globalThis.RegExp,globalThis.URL;var Eh=N.annotate({expected:`a string that will be decoded as a Date`}),Dh=Ep(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:()=>Tm()(Eh,uc)}),Oh=N.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function W(e,t){return Oh.pipe(gm(e,fc(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var kh=N.annotate({expected:`a string that will be decoded as a number`}).pipe(gm(P,cc)),Ah=N.check(Dm()),jh=N.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(gm(Ah,ac())),Mh=N.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),Nh=wm(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>Tm()(Mh,dc)}),Ph=ic({decode:(e,t)=>Ar(_o(e),{onNone:()=>x(new cs({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>b(vo(e))}),encode:e=>b(yo(e))}),Fh=-864e13,Ih=864e13;function Lh(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function Rh(e,t){return U.check(qm({minimum:e,maximum:t}))}var zh=Ep(e=>mo(e)&&ho(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=Lh(e,Fh,Ih);return _m()(Rh(t,n),Rs(go))},toCodecJson:()=>Tm()(N,Ph),toFormatter:()=>e=>e.toString()}),Bh=N.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(gm(zh,Ph));function Vh(e){return mp(e.ast)}function Hh(e,t){return sp(e.ast,t)}function Uh(e,t){return ip(sp(Nf(e.ast),t),t)}var Wh=Mf,Gh=qp(Xl(Qu,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),Kh=om(N,Gh),qh=C(()=>Vt({id:T().min(1).max(256),name:T().min(1).max(128),kind:Lr(`agent`).optional()})),Jh=C(()=>T().min(1).max(256)),Yh=C(()=>Vt({agentId:Jh,sessionId:Jh,commandId:Jh,outcome:Te([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:T().min(1).max(200).optional(),waitingOnYou:pn(Vt({itemId:Jh,kind:T().min(1).max(64),summary:T().min(1).max(200)})).min(1).max(8).optional()})),Xh=Vt({author:qh.optional(),sourceRequestId:Jh.optional(),delegation:Vt({ancestors:pn(Jh).max(8),maxDepth:dr().int().min(1).max(8),steer:Lr(!0).optional(),goal:Qr([T().min(1).max(4e3),Lr(!1)]).optional(),reply:Yh.optional()}).optional()});function Zh(e){let t=Xh.safeParse(e);return t.success?t.data.author:void 0}var Qh=e=>crypto.getRandomValues(new Uint8Array(e)),$h=(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}}},eg=(e,t=21)=>$h(e,t|0,Qh),tg=`abcdefghijklmnopqrstuvwxyz0123456789`;function ng(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return eg(tg,e)()}var rg=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ig=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,ag=T().min(1).max(64).regex(rg),og=T().min(1).max(64).regex(rg),sg=T().min(1).max(32).regex(ig),cg=Zn({prefix:sg}),lg=Zn({family:ag,version:Lr(1),kinds:Cn(og,cg)}).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)}}),ug=T(),dg=/^[a-z0-9]+$/,fg=new TextEncoder;function pg(e){return e===32||e>=9&&e<=13}function mg(e){let t=0,n=e.length;for(;t<n&&pg(e.charCodeAt(t));)t+=1;for(;n>t&&pg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function hg(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&dg.test(n)}let r=C(()=>Nn(e=>{let t=ug.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=fg.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(mg(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=C(()=>ug.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),gn)}));function o(){let n;try{n=ng(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 gg=Cn(T(),Zn({family:T(),kind:T(),version:Lr(1),generate:Nt(),schema:Ot(ke),parse:Nt(),is:Nt()})),_g=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},vg=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 yg(e){let t;try{t=lg.safeParse(e)}catch{throw new _g}if(!t.success)throw new _g;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=hg({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new vg({family:n.family,kind:t})})}let i=Nn(e=>{let t=gg.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 _g;return i.data}var bg=Symbol.for(`effect/MutableList/Empty`),xg=()=>({head:void 0,tail:void 0,length:0}),Sg=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})},Cg=()=>({array:[],mutable:!0,offset:0,next:void 0}),wg=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=Cg(),e.tail=e.tail.next):e.head=e.tail=Cg(),e.tail.array.push(t),e.length++},Tg=e=>{e.head=e.tail=void 0,e.length=0},Eg=(e,t)=>{if(t=pi(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 Tg(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?Tg(e):Sg(e),n;i=i.next}return Tg(e),n},Dg=e=>Eg(e,e.length),Og=e=>{if(!e.head)return bg;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:Tg(e):Sg(e),t},kg=`~effect/Queue`,Ag=`~effect/Queue/Enqueue`,jg=`~effect/Queue/Dequeue`,Mg={_A:Hn,_E:Hn},Ng={[kg]:Mg,[Ag]:Mg,[jg]:Mg,...ee,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:Xg(this)}}},Pg=e=>li(t=>{let n=Object.create(Ng);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=xg(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},Tn(n)}),Fg=e=>Pg({capacity:e}),Ig=e=>Pg({capacity:e,strategy:`dropping`}),Lg=g(2,(e,t)=>Ur(()=>Rg(e,t)?Qg:e.state._tag===`Open`&&e.strategy===`suspend`?s_(e,t):Zg)),Rg=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Og(e.messages),wg(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(wg(e.messages,t),t_(e),!0):(wg(e.messages,t),n_(e),!0):!1,zg=g(2,(e,t)=>Bg(e,re(t))),Bg=g(2,(e,t)=>ai(()=>Vg(e,t))),Vg=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Ge(t),r=Et(n,$g);return e.state.offers.size===0&&e.messages.length===0?(p_(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},n_(e),!0)},Hg=e=>Vg(e,re(ti())),Ug=e=>ai(()=>Wg(e)),Wg=e=>{if(e.state._tag===`Done`)return!1;Tg(e.messages);let t=e.state.offers;p_(e,e.state._tag===`Open`?e_:e.state.exit);for(let e of t)l_(e);return!0},Gg=e=>i_(()=>{if(e.state._tag===`Done`)return Ka(e.state.exit,()=>Tn([]));let t=f_(e);return d_(e),Tn(t)}),Kg=e=>qg(e,1,1/0),qg=g(3,(e,t,n)=>(t=pi(t),n=pi(n),i_(()=>r_(e,t,n)??Ye(o_(e,()=>a_(e,t)),qg(e,t,n))))),Jg=e=>i_(()=>Yg(e)??Ye(o_(e,()=>a_(e,1)),Jg(e))),Yg=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Og(e.messages);return d_(e),$e(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=u_(e.state.offers);return d_(e),$e(t)}},Xg=e=>e.state._tag===`Done`?0:e.messages.length,Zg=$e(!1),Qg=$e(!0),$g=Be(ti()),e_=ui(),t_=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(bt),e.messages.length===0))break}},n_=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,t_(e)},0))},r_=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return $e([]);if(!a_(e,t))return;let r=e.messages.length>0?Eg(e.messages,n):[u_(e.state.offers)];return d_(e),$e(r)},i_=ot({op:`QueueTake`,[o](e){let t=this[gt]();return xe(t)?t[o](e):t}}),a_=(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,o_=(e,t)=>s(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(bt);let r={ready:t,resume:n};return e.state.takers.add(r),ai(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),s_=(e,t)=>s(n=>Rg(e,t)?n(Qg):c_(e,{_tag:`Single`,message:t,resume:n})),c_=(e,t)=>{if(e.state._tag!==`Open`)return l_(t);let n=e.state.offers;return n.add(t),ai(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&p_(e,e.state.exit))})},l_=e=>e._tag===`Single`?e.resume(Zg):e.resume($e(e.remaining.slice(e.offset))),u_=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(Qg),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume($e([]))),n},d_=e=>{if(e.state._tag===`Done`)return qa(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(p_(e,e.state.exit),qa(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`)wg(e.messages,t.message),e.state.offers.delete(t),t.resume(Qg);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;wg(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume($e([]))}let r=e.state;if(r._tag===`Done`)return qa(r.exit.cause)}return!1},f_=e=>{if(e.messages.length>0){let t=Dg(e.messages);return d_(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[u_(e.state.offers)];return d_(e),t}return[]},p_=(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()},m_=he,h_=yr,g_=Me,__=n,v_=De,y_=Pn,b_=Cr,x_=e=>new C_(e),S_=(e,t,n)=>s(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),ai(()=>{e.waiters.delete(i)})}),C_=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=Ur(()=>this.free<e?S_(this,e,t):(this.taken+=e,Tn(e)));return t}takeIfAvailable(e){return Ur(()=>this.free<e?Tn(!1):(this.taken+=e,Tn(!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 li(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ei))}release(e){return li(t=>Tn(this.releaseUnsafe(t,e)))}get releaseAll(){return li(e=>Tn(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>$t(r=>{let i=Ur(()=>{if(this.free<e){let t=S_(this,e,ei);return rt(r(t),()=>i)}return this.taken+=e,Jt(r(t),()=>{this.releaseUnsafe(n(),e)},!0)});return i})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>$t(r=>this.free<e?Ut:(this.taken+=e,Jt(r(Gn(t)),()=>{this.releaseUnsafe(n(),e)},!0)))}},w_=e=>ai(()=>new C_(e)),T_=`~effect/Channel`,E_=e=>Rr(e,T_),D_={[T_]:{_Env:Hn,_InErr:Hn,_InElem:Hn,_OutErr:Hn,_OutElem:Hn},pipe(){return Ze(this,arguments)}},O_=e=>{let t=Object.create(D_);return t.transform=(t,n)=>Ir(e(t,n),e=>b(Bt(e))),t},k_=(e,t)=>O_((n,r)=>E(M_(e)(n,r),e=>t(e,r))),A_=e=>O_((t,n)=>e),j_=e=>O_(ct(function*(t,n){let r=Ca(n),i=e=>wa(r,Za(e)),a=yield*fe(e(t,n,r),i);return fe(a,i)})),M_=e=>e.transform,N_=4096,P_=(e,t,n)=>Pg({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(jn(t=>xa(e,Ug(t))),jn(n=>ya(t(n),e).pipe(Ir(e=>Bg(n,e)),qe(e)))),F_=(e,t)=>O_((n,r)=>be(P_(r,e,t),Kg)),I_=e=>O_((t,n)=>hr(()=>M_(e())(t,n))),L_=e=>A_(w(()=>{let t=e();return hr(()=>{let e=t.next();return e.done?Xi(e.value):b(e.value)})})),R_=(e,t=N_)=>{let n=mi(t);return A_(w(()=>{let t=e(),r=on();return hr(()=>{if(r._tag===`Some`)return Xi(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return Xi(n.value);r=Br(n.value);break}e.push(n.value)}return b(e)})}))},z_=(e,t=N_)=>R_(()=>e[Symbol.iterator](),t),B_=e=>W_(b(e)),V_=A_(b(Xi())),H_=e=>A_(b(x(e))),U_=e=>A_(Bt(e)),W_=e=>A_(w(()=>{let t=!1;return hr(()=>t?Xi():(t=!0,e))})),G_=e=>A_(b(Kg(e))),K_=(e,t)=>O_(ct(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*xa(r,Dt(()=>i.return()))),E(si({try:()=>i.next(),catch:t}),e=>e.done?Xi(e.value):b(e.value))})),q_=(e,t)=>J_(K_(e,t),St),J_=g(2,(e,t)=>k_(e,e=>w(()=>{let n=0;return be(e,e=>t(e,n++))}))),Y_=e=>e===void 0||e!==`unbounded`&&e<=1,X_=g(e=>E_(e[0]),(e,t,n)=>Y_(n?.concurrency)?Z_(e,t):Q_(e,t,n)),Z_=(e,t)=>O_((n,r)=>{let i=0;return be(M_(e)(n,r),E(e=>t(e,i++)))}),Q_=(e,t,n)=>j_(ct(function*(r,i,a){let o=0,s=yield*M_(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Fg(0);yield*xa(a,Ug(l));let u=ar(yield*vn()),d=v_(a);if(n.unordered){let e=x_(c),n=oe(e.release(1)),r=xt({onFailure:e=>E(Bg(l,e),n),onSuccess:e=>E(Lg(l,e),n)});yield*e.take(1).pipe(E(()=>s),E(e=>{let n=o++;return d(u(r(hr(()=>t(e,n))))),h}),pt({disableYield:!0}),Ir(t=>e.withPermits(c-1)(Bg(l,t))),qe(a))}else{let e=yield*Fg(c-2);yield*xa(a,Ug(e)),yield*Jg(e).pipe(Zr,E(e=>Lg(l,e)),pt({disableYield:!0}),Ir(e=>Bg(l,e)),qe(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,Vg(l,e.cause))};yield*s.pipe(E(i=>{if(n)return Bt(n);let a=o++,s=u(hr(()=>t(i,a)));return d(s),s.addObserver(r),Lg(e,h_(s))}),pt({disableYield:!0}),Ir(t=>Lg(e,$i(t)).pipe(y(Bg(e,t)))),qe(a))}return Jg(l)})),$_=g(e=>E_(e[0]),(e,t,n)=>Y_(n?.concurrency)?ev(e,t):tv(e,t,n)),ev=(e,t)=>O_((n,r)=>be(M_(e)(n,r),e=>{let i,a,o=E(e,e=>(a??=Ca(r),Zt(M_(t(e))(n,a),e=>(i=s(e),i)))),s=Ka(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=wa(a,na);return a=void 0,E(t,()=>o)});return hr(()=>i??o)})),tv=(e,t,n)=>e.pipe(J_(t),cv(n)),nv=e=>$_(e,Hn),rv=e=>k_(e,e=>{let t,n=0,r=hr(function r(){if(t===void 0)return E(e,e=>{switch(e.length){case 0:return r();case 1:return b(e[0]);default:return t=e,b(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),b(i)});return b(r)}),iv=g(2,(e,t)=>k_(e,e=>b(E(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return at(i)?b(i):E(e,n)})))),av=g(2,(e,t)=>O_((n,r)=>{let i=Ca(r);return be(M_(e)(n,i),e=>{let a=e.pipe(Ir(e=>{if(qa(e))return Bt(e);let o=i;return i=Ca(r),wa(o,$i(e)).pipe(y(M_(t(e))(n,i)),E(e=>(a=e,e)))}));return hr(()=>a)})})),ov=g(3,(e,t,n)=>av(e,e=>{let r=t(e);return pe(r)?U_(r.failure):n(r.success,e)})),sv=g(2,(e,t)=>ov(e,Gi,e=>t(e))),cv=g(2,(t,{bufferSize:n=16,concurrency:r,switch:i=!1})=>j_(ct(function*(a,o,s){let c=r===`unbounded`?2**53-1:Math.max(1,r),l=i?void 0:x_(c),u=yield*b_(!0),d=new Set,f=yield*Fg(n);yield*xa(s,Ug(f));let p=yield*M_(t)(a,o);return yield*S(function*(){for(;;){let t;l&&(d.size<c?yield*l.take(1):(t=yield*ae(p),yield*e(l.take(1),y(h_(t),Tt))));let n=t===void 0?yield*p:yield*h_(t),r=Ca(s),i=yield*M_(n)(a,r);for(;d.size>=c;){let e=hi(d);d.delete(e),d.size===0&&(yield*u.open),yield*g_(e)}let o=yield*i.pipe(jn(()=>_t),E(e=>Lg(f,e)),pt({disableYield:!0}),fe(ct(function*(e){let t=Za(e),n=yield*Dn(wa(r,t));if(!d.has(o))return;let i=oa([t,n]);ia(i)&&(yield*Bg(f,i.cause)),d.delete(o),l&&(yield*l.release(1)),d.size===0&&(yield*u.open)})),ae);u.closeUnsafe(),d.add(o)}}).pipe(Ir(e=>{let t=Ya(e);return Ae(t)?u.whenOpen(Bg(f,e)):Bg(f,e)}),qe(s)),Jg(f)}))),lv=g(e=>E_(e[0])&&E_(e[1]),(e,t,n)=>j_(ct(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Fg(0);yield*xa(a,Ug(s));let c=0;function l(e,t){if(c++,!qa(t))return Bg(s,t);switch(o){case`both`:return c===2?Bg(s,t):h;case`left`:case`right`:return e===o?Bg(s,t):h;case`either`:return Bg(s,t)}}let u=(e,t,n)=>M_(t)(r,n).pipe(E(e=>e.pipe(E(e=>Lg(s,e)),pt)),fe(t=>gr(Za(t),e=>wa(n,e)).pipe(xt({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),qe(a));return yield*u(`left`,e,Ca(a)),yield*u(`right`,t,Ca(a)),Jg(s)}))),uv=e=>O_((t,n)=>{let r;return b(hr(()=>r||e.pipe(ya(n),E(e=>M_(e)(t,n)),E(e=>r=e))))}),dv=g(2,(e,t)=>lv(e,A_(b(E(t,Xi))),{haltStrategy:`either`})),fv=g(2,(e,t)=>j_((n,r,i)=>ba(i,t).pipe(y(M_(e)(n,r))))),pv=g(2,(e,t)=>fv(e,e=>t)),mv=(e,t,n)=>hr(()=>{let r=va(),i=M_(e)(Xi(),r);return Ka(E(i,t),n||b).pipe(Oe(e=>wa(r,e)))}),hv=g(2,(e,t)=>mv(e,e=>pt(E(e,t),{disableYield:!0}))),gv=ct(function*(e){let t=x_(1),n=yield*vn(),r=We(n,ga);return(yield*M_(e)(Xi(),r)).pipe(Ft(n),t.withPermits(1))},Ir(e=>b(Bt(e)))),_v=(e,t)=>M_(e)(Xi(),t),vv=`~effect/Stream`,yv={_R:Hn,_E:Hn,_A:Hn},bv=function(e){this.channel=e};bv.prototype={[vv]:yv,pipe(){return Ze(this,arguments)}};var xv=e=>new bv(e),Sv=`~effect/Sink`,Cv={_A:Hn,_In:Hn,_L:Hn,_E:Hn,_R:Hn},wv={[Sv]:Cv,pipe(){return Ze(this,arguments)}},Tv=e=>{let t=Object.create(wv);return t.transform=e,t},Ev=((e,t,n)=>Tv(r=>{let i=e(),a;return t(i)?r.pipe(E(e=>{for(let r=0;r<e.length;r++)if(i=n(i,e[r]),!t(i))return r+1<e.length&&(a=e.slice(r+1)),Xi();return h}),pt({disableYield:!0}),Ka(()=>b([i,a]))):b([i])}))(on,ir,(e,t)=>Br(t)),Dv=()=>Ev,Ov=`~effect/Stream`,kv=e=>Rr(e,Ov),Av=xv,jv=e=>Av(W_(be(e,St))),Mv=e=>Pv(b(E(e,()=>Xi()))),Nv=e=>Pv(b(be(e,St))),Pv=e=>Av(A_(e)),Fv=(e,t)=>Av(O_((n,r)=>E(_v(e.channel,r),e=>t(e,r)))),Iv=e=>e.channel,Lv=(e,t)=>Av(F_(e,t)),Rv=Av(V_),zv=e=>Av(B_(St(e))),Bv=e=>Av(I_(()=>e().channel)),Vv=e=>Av(H_(e)),Hv=e=>Av(U_(e)),Uv=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Wv(e):Av(z_(e,t?.chunkSize)),Wv=e=>at(e)?Av(B_(e)):Rv,Gv=e=>Av(G_(e)),Kv=(e,t)=>Av(q_(e,t)),qv=(e,t)=>Pv(w(()=>{let n=e,r=!1;return hr(function e(){return r?Xi():E(t(n),([t,i])=>(ir(i)?r=!0:n=i.value,at(t)?b(t):e()))})})),Jv=e=>Av(uv(be(e,Iv))),Yv=g(2,(e,t)=>Bv(()=>{let n=0;return Av(J_(e.channel,l(e=>t(e,n++))))})),Xv=g(e=>kv(e[0]),(e,t,n)=>e.channel.pipe(rv,X_(t,n),J_(St),Av)),Zv=e=>e.pipe(Yv(kt),cy(e=>zv(_e(e)))),Qv=g(e=>kv(e[0]),(e,t,n)=>e.channel.pipe(rv,$_(e=>t(e).channel,n),Av)),$v=g(2,(e,t)=>{let n=m(t.duration);if(!Jr(n))return e;if(ht(n))return Bv(t.orElse);let r=Symbol();return sy(Bv(()=>{let t=__().getRef(Ta),i=ne(n),a,o=y_(!1);return iy(Fv(e,(e,n)=>hr(()=>(a=t.currentTimeMillisUnsafe()+i,o.openUnsafe(),e)).pipe(be(e=>(o.closeUnsafe(),a=void 0,e)),b)),Mv(S(function*(){for(;;)if(yield*o.await,a!==void 0&&(yield*fn(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*ur(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Hv(e))}),ey=e=>Qv(e,Uv),ty=g(2,(e,t)=>{let n=Av(nv(L_(()=>ry(e,t))));return ny.set(n,[e,t]),n}),ny=new WeakMap;function*ry(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=ny.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var iy=g(e=>kv(e[0])&&kv(e[1]),(e,t,n)=>Av(lv(Iv(e),Iv(t),n))),ay=g(2,(e,t)=>Av(iv(Iv(e),t))),oy=g(2,ct(function*(e,t){let n,r=yield*gv(e.channel),i=Ir(r,e=>(n=e,Bt(e))),[a,o]=yield*Yn(e=>t.transform(i,e)),s=n?Rv:Pv(b(r));return o&&(s=ty(Wv(o),s)),[a,s]})),sy=g(2,(e,t)=>e.channel.pipe(av(e=>t(e).channel),Av)),cy=g(2,(e,t)=>Av(sv(e.channel,e=>t(e).channel))),ly=g(e=>kv(e[0]),(e,t,n)=>Fv(e,(e,r)=>w(()=>{let r=0,i=!1;return E(hr(()=>i?Xi():e),e=>{let a=e.findIndex(e=>t(e,r++));if(a>=0){i=!0;let t=e.slice(0,n?.excludeLast?a:a+1);return at(t)?b(t):Xi()}return b(e)})}))),uy=g(2,(e,t)=>Av(dv(e.channel,t))),dy=g(2,(e,t)=>Av(pv(e.channel,t))),fy=g(2,(e,t)=>hv(e.channel,e=>{let n=0;return Xr({while:()=>n<e.length,body:()=>t(e[n++]),step:mt})})),py=g(2,(e,t)=>({[Symbol.asyncIterator](){let n=In(t),r=ar(t),i=va(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Er(y(t?g_(t):h,wa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(Xe(`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??E(_v(e.channel,i),e=>(a=e,e)));s=t;let d=await n(m_(t));if(s===t&&(s=void 0),ra(d))return o=d.value[Symbol.iterator](),o.next();if(qa(d.cause))return l(na);if(c&&Hi(d.cause))return c;throw await u(d),Wi(d.cause)},return(){return l(na)},async throw(e){throw await u(ta(e)),e}}}})),my=e=>py(e,ze()),hy=15e3,gy=45e3,_y=Th.check(fh(256)),vy=U.check(H(0)),yy=F({agentId:_y,sessionId:_y,name:_y}),by=F({id:_y,kind:Th.check(fh(64)),summary:Th.check(fh(200)),since:vy,expiresAt:j(vy),inbox:j(M(!1)),waitingOn:j(yy)}),xy=by.mapFields(e=>({...e,extensionId:_y})),Sy=4096,Cy=I(xy).check(fh(64)),wy=N.pipe(B(lh(1)),B(fh(256))),Ty=F({providerId:wy,modelId:wy,reasoning:j(R([`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]))}),Ey=k(z(Ty)),Dy=k(W(z(Ty))),Oy=R([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),ky=R([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),Ay=N.pipe(B(lh(1)),B(fh(256))),jy=F({_tag:M(`ShiitakeError`),boundary:Oy,cause:ky,message:N,requestId:A(Ay)}),G=class extends Error{boundary;requestId;_tag=`ShiitakeError`;cause;underlying;constructor(e,t,n,r,i){super(n),this.boundary=e,this.requestId=r,this.name=`ShiitakeError`,this.cause=t,this.underlying=i}},My=new TextEncoder;function Ny(e){return N.check(lh(1),fh(e),V(t=>My.encode(t).byteLength<=e))}var Py=/\p{Cs}/u,Fy=Ny(256).check(V(e=>!Py.test(e))),Iy=Ny(262144),Ly=F({type:M(`image`),data:N.check(lh(1),fh(1048576),jm()),mimeType:N.check(V(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),Ry=I(Ly).check(lh(1),fh(8)),zy=R([`steer`,`followUp`]),By=Fy,Vy=O(F({commandId:Fy,timeoutMs:U.check(H(0),Km(3e4))}),{onExcessProperty:`error`});O(F({commandId:Fy,timeoutMs:kh.check(Ym(),qm({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Hy=O(Ny(512)),Uy=F({requestId:Fy}),Wy=F({delivery:zy,requestId:Fy,type:M(`prompt`),text:N.check(fh(262144),V(e=>My.encode(e).byteLength<=262144)),images:A(Ry)}).check(V(e=>(e.text.length>0||(e.images?.length??0)>0)&&My.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),Gy=F({type:M(`abort`)}),Ky=F({commandId:Fy,onlyIfPending:j(nm),type:M(`cancel`)}),qy=F({type:M(`operator`),requestId:Fy,author:R([`operator`,`party`]),text:Iy}),Jy=F({type:M(`branch`),entryId:Fy}),Yy=F({type:M(`fork`),entryId:Fy}),Xy=N.check(lh(1),fh(4096)),Zy=F({type:M(`compact`),requestId:Fy,instructions:A(Xy)}),Qy=L([Wy,Zy]),$y=N.check(V(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),eb=L([Wy,Gy,Ky,Jy,Yy,qy,Zy,F({type:M(`title`),title:z($y)})]),tb=F({command:eb}),nb=F({includeSandboxFailures:j(nm),limit:j(U.check(qm({minimum:1,maximum:200}))),before:j(Ny(512))}),rb=F({includeSandboxFailures:j(M(`true`)),limit:j(kh.check(Ym(),qm({minimum:1,maximum:200}))),before:j(Ny(512))}),ib=F({includeSandboxFailures:j(nm),after:j(N)}),ab=F({includeSandboxFailures:j(M(`true`)),mode:j(M(`subscribe`)),after:j(N),limit:j(kh.check(Ym(),qm({minimum:1,maximum:200})))}),ob={onExcessProperty:`error`},sb=O(By,ob),cb=O(Uy,ob),lb=O(Qy,ob);O(Fy);var ub=O(eb,ob);O(tb,ob);var db=O(L([nb,tm]),ob);O(rb,ob);var fb=O(ib,ob);O(ab,ob);function pb(e){let t=sb(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session id is invalid`);return t.success}function mb(e){let t=Hy(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function hb(e){let t=cb(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function gb(e){let t=db(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Read options are invalid`);let n=t.success??{},r={limit:n.limit??200};return n.before!==void 0&&(r={...r,before:n.before}),n.includeSandboxFailures!==void 0&&(r={...r,includeSandboxFailures:n.includeSandboxFailures}),Object.freeze(r)}function _b(e){let t=fb(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Subscribe options are invalid`);let n={};return t.success.after!==void 0&&(n={...n,after:t.success.after}),t.success.includeSandboxFailures!==void 0&&(n={...n,includeSandboxFailures:t.success.includeSandboxFailures}),Object.freeze(n)}function vb(e,t){if(pe(e))throw new G(`contract`,`invalid`,t);return e.success}var yb=nn();function bb(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function xb(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 Sb(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 Cb(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var wb=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function Tb(e){return wb.has(e)}function Eb(e){let t=[],n=n=>{n!==e&&n.length>=3&&!t.includes(n)&&t.push(n)};return e.endsWith(`ing`)&&e.length>4&&n(e.slice(0,-3)),e.endsWith(`ed`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`ation`)&&e.length>6&&n(`${e.slice(0,-3)}e`),e.endsWith(`ies`)&&e.length>4&&(n(e.slice(0,-3)),n(`${e.slice(0,-3)}y`)),e.endsWith(`es`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`s`)&&!e.endsWith(`ss`)&&e.length>3&&n(e.slice(0,-1)),t}function Db(e){let t=8997,n=33826,r=40164,i=52210;for(let a=0;a<e.length;a+=1){let o=t^e.charCodeAt(a),s=o*435,c=n*435+(s>>>16),l=r*435+(c>>>16)+(o<<8),u=i*435+(l>>>16)+(n<<8);t=s&65535,n=c&65535,r=l&65535,i=u&65535}return i.toString(16).padStart(4,`0`)+r.toString(16).padStart(4,`0`)+n.toString(16).padStart(4,`0`)+t.toString(16).padStart(4,`0`)}function Ob(e){return e.slice(e.indexOf(`.`)+1)}function kb(e){return e.slice(0,e.indexOf(`.`))}var Ab=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,jb=1e3,Mb=221;function Nb(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Nb(r,t+1));return n}if(!bb(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Nb(r,t+1));return n}var Pb=C(()=>Cn(T(),nn()).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`}),Nb(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Fb=C(()=>Zn({query:T().max(200),maxResults:dr().int().min(1).max(50).default(50)})),Ib=C(()=>Zn({path:T().max(160),detail:Te([`index`,`full`]).default(`full`),methods:pn(T().max(80)).max(50).optional()})),Lb=Zn({cursor:T().max(400).optional(),limit:dr().int().min(1).max(50).default(50),namespace:T().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),Rb=C(()=>Zn({path:T().max(160),capabilityNotes:T().max(500).optional()})),zb=Zn({path:T().max(160),description:T().max(1e3).optional(),score:dr().min(0).max(Mb),matchReason:T().max(500).optional(),sample:Pb.optional(),capabilityNotes:T().max(500).optional(),peers:pn(Rb).max(1e3).optional()}),Bb=C(()=>Zn({results:pn(zb).max(50),total:dr().int().min(0).max(jb),truncated:xr(),topScore:dr().min(0).max(Mb),margin:dr().min(0).max(Mb),catalogStamp:T().length(16).regex(/^[0-9a-f]{16}$/)})),Vb=Zn({results:pn(zb).max(50),total:dr().int().min(0).max(jb),nextCursor:T().max(400).nullable(),catalogStamp:T().length(16).regex(/^[0-9a-f]{16}$/)}),Hb=C(()=>Zn({path:T().max(160),description:T().max(1e3).optional(),types:T().max(2e4),inputSchema:nn().refine(e=>JSON.stringify(e).length<=2e4&&Nb(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:Te([`module`,`operation`]),usage:T().max(300).optional()}));C(()=>Zn({code:Te([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:T().max(1e3)}));var Ub=C(()=>Zn({"~standard":Zn({jsonSchema:Zn({input:Ot(Function),output:Ot(Function)})})})),Wb=C(()=>Nn(e=>Ub.safeParse(e).success,`Expected a Standard JSON Schema`)),Gb=C(()=>Zn({path:T().min(3).max(160).regex(Ab),description:T().max(1e3).optional(),input:Wb,output:Wb.optional(),capabilityNotes:T().max(500).optional(),instructions:T().max(1e3).optional()})),Kb=C(()=>Zn({revision:T().min(1).max(160),operations:pn(Gb).max(jb)})),qb=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}}},Jb=Qr([ln({$ref:T().optional(),$defs:Cn(T(),lt()).optional(),definitions:Cn(T(),lt()).optional(),const:lt().optional(),enum:pn(lt()).optional(),oneOf:pn(lt()).optional(),anyOf:pn(lt()).optional(),allOf:pn(lt()).optional(),type:Qr([T(),pn(T())]).optional(),properties:Cn(T(),lt()).optional(),additionalProperties:lt().optional(),required:pn(T()).optional(),prefixItems:pn(lt()).optional(),items:lt().optional(),examples:pn(lt()).optional(),default:lt().optional()}),xr()]),Yb=new WeakMap;function Xb(e,t){let n=Yb.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`})}catch{throw new qb(`invalid_input`,`Schema cannot be projected to JSON Schema`)}$b(i);let a={raw:i};return n===void 0&&(n={},Yb.set(e,n)),n[t]=a,a}function Zb(e,t){return Xb(e,t).raw}function Qb(e,t){let n=Xb(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new qb(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function $b(e){let t=Jb.safeParse(e);if(!t.success)throw new qb(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var ex=256,tx=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function nx(e,t,n){let r=tx.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>ex)throw new qb(`invalid_input`,`Schema references expand more than ${String(ex)} times; flatten its shared definitions`);return ix($b(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function rx(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=tx.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&rx($b(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 ix(e,t,n){if(t>12||e===!0||e===!1)return`unknown`;let r=n??{definitions:{...e.definitions,...e.$defs},expanding:new Set,budget:{expansions:0}};if(e.$ref)return nx(e.$ref,t,r);if(e.const!==void 0)return JSON.stringify(e.const);if(e.enum)return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(e.oneOf)return e.oneOf.map(e=>ix($b(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>ix($b(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=$b(e),i=ix(n,t+1,r);return rx(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>xb(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${ix($b(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
4
- ${n.map(([e,n])=>{let a=ix($b(n),t+1,r),o=i.has(e)?``:`?`,s=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e);return`${` `.repeat(t+1)}${s}${o}: ${a};`}).join(`
5
- `)}
6
- ${` `.repeat(t)}}`}if(e.type===`array`){let n=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>ix($b(e),t+1,r));return n!==void 0&&n!==!0&&!Array.isArray(n)&&i.push(`...${ix($b(n),t+1,r)}[]`),`[${i.join(`, `)}]`}if(n!==void 0&&Array.isArray(n))return`[${n.map(e=>ix($b(e),t+1,r)).join(`, `)}][]`;let i=n===void 0||$b(n),a=ix(i,t+1,r);return`${i!==!0&&i!==!1&&(i.oneOf!==void 0||i.anyOf!==void 0||i.allOf!==void 0)?`(${a})`:a}[]`}switch(e.type){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`unknown`}}function ax(e,t=`input`){return ix($b(Zb(e,t)),0)}function ox(e){return e.replace(/[^A-Za-z0-9_$]/g,`_`)}function sx(e,t,n){let r=`(input: ${t}) => Promise<${n}>`;for(let t of e.split(`.`).reverse())r=`{ [${JSON.stringify(t)}]: ${r} }`;return r}function cx(e){return e.length===0?``:`export declare const env: ${e.map(e=>e.indexEnvironment).join(` & `)};`}function lx(e){let t=e.map(e=>e.types).join(`
7
-
8
- `);return e.length===0?t:`${t}\nexport declare const env: ${e.map(e=>e.environment).join(` & `)};`}var ux=new WeakMap;function dx(e){let t=ux.get(e);if(t!==void 0)return t;let n=ox(e.path.replace(/\./g,`$`)),r=ax(e.input,`input`),i=e.output?ax(e.output,`output`):`unknown`,a=Object.freeze({indexEnvironment:sx(e.path,r,i),environment:sx(e.path,`${n}_Input`,`${n}_Output`),types:`export type ${n}_Input = ${r};\nexport type ${n}_Output = ${i};`});return ux.set(e,a),a}function fx(e){let t=$b(Zb(e,`input`));if(t===!0||t===!1||!t.properties)return;let n={},r=!1,i=Object.entries(t.properties).sort(([e],[t])=>xb(e,t));for(let[e,t]of i){let i=$b(t);if(i===!0||i===!1)continue;let a=i.examples;if(a&&a.length>0){let t=yb.safeParse(a[0]);t.success&&(n[e]=t.data,r=!0)}else if(i.default!==void 0){let t=yb.safeParse(i.default);t.success&&(n[e]=t.data,r=!0)}}return r?n:void 0}function px(e){return e&&e.length>0?e:void 0}function mx(e){let t=Hb.safeParse(e);if(!t.success)throw new qb(`invalid_input`,`Description output exceeded its bounds`);return t.data}function hx(e,t){let n=e.find(e=>e.path===t.path);if(n){let e=`env.${n.path}`,t=yb.safeParse(Zb(n.input,`input`));if(!t.success)throw new qb(`invalid_input`,`Schema cannot be projected to JSON Schema`);let r={path:n.path,description:px(n.description),types:lx([dx(n)]),kind:`operation`,inputSchema:t.data,usage:`await ${e}({ ... })`};if(r.types.length>2e4)throw new qb(`invalid_input`,`Operation description exceeds the bounded output`);return mx(r)}let r=`${t.path}.`,i=e.filter(e=>e.path.startsWith(r)).sort((e,t)=>xb(e.path,t.path));if(i.length===0)throw new qb(`unknown_target`,`Unknown target: ${t.path}`);let a=i[0];if(!a)throw new qb(`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?cx(i.map(dx)):lx((o.length>0?o:i).map(dx)),s.length>2e4)throw new qb(`invalid_input`,`Description types exceed the bounded output`);return mx({path:t.path,description:px(a.instructions),types:s,kind:`module`})}function gx(e){let t=Qb(e.input,`input`),n=e.output?Qb(e.output,`output`):``;return Object.freeze({...e,fingerprint:Db(t+`
9
- `+n),inputBytes:t.length,outputBytes:n.length,sample:fx(e.input)})}var _x={exact:14,startsWith:9,phrase:6,token:4,prefix:2,substring:2,includes:1},vx={path:12,namespace:8,method:10,description:5},yx=25,bx=10,xx=8,Sx=20,Cx=Math.max(yx,bx)+xx+Sx,wx=1+Math.max(...Object.values(_x))*Math.max(...Object.values(vx))+Cx;function Tx(e){return Db([...e].sort((e,t)=>xb(e.path,t.path)).map(e=>JSON.stringify([e.path,e.description??null,e.capabilityNotes??null,e.instructions??null,e.fingerprint])).join(`
10
- `))}function Ex(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=Cb(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 Dx(e,t,n){let r=Sb(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...Eb(e)],s=`none`;for(let e of n){let t=Ex(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=_x[s]*vx[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function Ox(e,t){let n=Sb(e);return[t,...Eb(t)].some(e=>n.includes(e))}function kx(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 Ax(e){let t=Bb.safeParse(e);if(!t.success)throw new qb(`invalid_input`,`Search output exceeded its bounds`);return t.data}function jx(e){return[Ob(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Mx(e){return Ax({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Nx(e,t,n){let r=kb(e.path),i=Ob(e.path),a=e.description??``,o=[e.path,r,i,a],s=Dx(e.path,`path`,t),c=Dx(r,`namespace`,t),l=Dx(i,`method`,t),u=Dx(a,`description`,t),d=n.filter(e=>o.some(t=>Ox(t,e))).length;if(d===0)return;let f=d/n.length,p=Math.max(s.score,c.score,l.score,u.score);if(p===0)return;let m=d===n.length?yx:f*bx,ee=n[0];ee&&o.some(e=>Ox(e,ee))&&(m+=xx),(s.level===`exact`||l.level===`exact`)&&(m+=Sx);let h={path:e.path,score:d+(p+m)/wx};a&&(h.description=a);let te=kx([[`method`,l],[`description`,u],[`path`,s],[`namespace`,c]]);return te&&(h.matchReason=te),e.sample&&(h.sample=e.sample),e.capabilityNotes&&(h.capabilityNotes=e.capabilityNotes),{result:h,cluster:jx(e),pathScore:s.score}}function Px(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||xb(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>xb(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||xb(e.path,t.path))}function Fx(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return Ax({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function Ix(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=Cb(Sb(t)),o=a.filter(e=>!Tb(e));if(o.length===0)return Mx(r);let s=[];for(let t of e){let e=Nx(t,a,o);e&&s.push(e)}return Fx(Px(s),i,r)}var Lx=Vt({catalogStamp:Vb.shape.catalogStamp,namespace:Lb.shape.namespace.unwrap().nullable(),after:zb.shape.path});function Rx(e,t,n){let r=Lb.safeParse(n);if(!r.success)throw new qb(`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)=>xb(kb(e.path),kb(t.path))||xb(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=Lx.parse(JSON.parse(i.cursor))}catch(e){throw new qb(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new qb(`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 qb(`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 Vb.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 zx=1e6;function Bx(e,t=0){if(t>=16)return e.length===0?t:t+1;let n=t;for(let r=e.length-1;r>=0;--r){let i=e[r],a=t+1;if(Array.isArray(i)?a=Bx(i,a):It(i)&&(a=Bx(Object.values(i),a)),n=Math.max(n,a),n>16)return n}return n}function Vx(e){let t=Kb.safeParse(e);if(!t.success)throw new qb(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new qb(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>xb(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new qb(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),Qb(e.input,`input`).length>2e4||Bx(Object.values(Zb(e.input,`input`)))>16)throw new qb(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?Qb(e.output,`output`).length:0)>2e4||e.output!==void 0&&Bx(Object.values(Zb(e.output,`output`)))>16)throw new qb(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=gx(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||Nb(n,0)>16))throw new qb(`invalid_input`,`Schema projection is too large: ${e.path}`);if(i.push(t),a+=t.inputBytes+t.outputBytes+o+e.path.length,a+=e.description?.length??0,a+=e.capabilityNotes?.length??0,a+=e.instructions?.length??0,a>zx)throw new qb(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function Hx(e){let t=Vx(e),n=Object.freeze(t.operations),r=Tx(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=Fb.safeParse(e);if(!t.success)throw new qb(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new qb(`empty_query`,`Search query must not be empty`);return Ix(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Ib.safeParse(e);if(!t.success)throw new qb(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new qb(`empty_query`,`Description target must not be empty`);return hx(n,t.data)},list:e=>Rx(i,r,e),stamp:()=>r})}var Ux=C(()=>T().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),Wx=C(()=>Cn(T(),nn()));C(()=>Qr([Wx,xr()]));var Gx=C(()=>Zn({tool:Ux,title:T().max(120),description:T().max(1e3),input:Cn(T(),nn()),output:Cn(T(),nn()),call:Cn(T(),nn())}).catchall(nn()));C(()=>Kt(`kind`,[Vt({kind:Lr(`unindexed`)}),Vt({kind:Lr(`ready`),tools:pn(Gx).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var Kx=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:Fb,output:Bb}),qx=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Ib,output:Hb}),Jx=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:Lb,output:Vb});Object.freeze({createCatalog:Hx,forageSearchDefinition:Kx,forageDescribeDefinition:qx,forageListDefinition:Jx});var Yx=`invalid_definition`,Xx=`runtime_closed`,Zx=`source_failure`,K=class extends Error{code=Yx;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},Qx=class extends Error{code=Xx;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},$x=class extends Error{sourceId;phase;code=Zx;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`}},eS=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},tS=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},nS=class extends Fi(`SourceInvalid`){},rS=class extends Fi(`GuestThrew`){},iS=class extends Fi(`DeadlineExceeded`){},aS=class extends Fi(`SandboxBusy`){code=`sandbox-busy`},oS=class extends Fi(`Cancelled`){},sS=class extends Fi(`DispatchLost`){},cS=class extends Fi(`SandboxCrashed`){},lS=class extends Fi(`BadResponse`){},uS=class extends Fi(`ResultTooLarge`){},dS=class extends Fi(`ResultNotJson`){},fS=class extends Fi(`CapabilityFailed`){constructor(e){super(e),this.message=hS(this)}},pS=class extends Fi(`Unknown`){};function mS(e,t){switch(e._tag){case`SourceInvalid`:return new nS({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new rS({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new iS({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new aS({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new oS({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new sS({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new cS({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new lS({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new uS({size:e.size,ref:t});case`ResultNotJson`:return new dS({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new fS({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new pS({rawCause:e.rawCause,ref:t})}}function hS(e,t=!0){let n;switch(e._tag){case`SourceInvalid`:n=`SyntaxError in submitted source line ${String(e.line)}, column ${String(e.column)}: ${e.excerpt.slice(0,160)}. Nothing ran. Fix quote/heredoc nesting: quote multi-line shell text with a JavaScript template literal or \\n escapes; escape backticks and \${ inside it. If a nested heredoc is hard to quote, write the script with Files, then execute it.`;break;case`GuestThrew`:{let t=e.name.slice(0,80),r=e.message.slice(0,512),i=e.missingVariable;n=`${t}: ${r}${i===void 0?``:`. Declare ${i} with const or let before assigning it; this sandbox does not create implicit globals. Each execute call has its own variables.`}`;break}case`DeadlineExceeded`:n=`execute hit its ${String(e.limitMs)} ms deadline after ${String(e.elapsedMs)} ms; split the work or persist progress${e.acknowledged===!1?`; sandbox did not acknowledge cancellation`:``}`;break;case`SandboxBusy`:n=`sandbox-busy: all ${String(e.capacity)} sandbox slots remained occupied after waiting ${String(e.waitedMs)} ms. Nothing ran; retry this call after capacity becomes available.`;break;case`Cancelled`:n=e.acknowledged===!1?`Sandbox did not acknowledge cancellation`:`Execution was cancelled`;break;case`DispatchLost`:n=`The sandbox lost contact after ${String(e.elapsedMs)} ms; a running command may still be running; check its effects before retrying`;break;case`SandboxCrashed`:n=`The sandbox process stopped before answering; check effects before retrying`;break;case`BadResponse`:n=`The sandbox returned an unreadable result; retry once, split the call if it recurs`;break;case`ResultTooLarge`:n=`Sandbox result exceeds 256 KiB`;break;case`ResultNotJson`:n=`Sandbox returned non-JSON data`;break;case`CapabilityFailed`:n=e.cause.message.slice(0,1e3);break;case`Unknown`:return`The sandbox failed for an unrecognized reason${t?` (ref ${e.ref??`unavailable`})`:``}`}return!t||e.ref===void 0?n:`${n} (ref ${e.ref})`}var gS=C(()=>Qr([Ot(nS),Ot(rS),Ot(iS),Ot(aS),Ot(oS),Ot(sS),Ot(cS),Ot(lS),Ot(uS),Ot(dS),Ot(fS),Ot(pS)])),_S=C(()=>lt().pipe(Qr([Ot(Error).transform(e=>({kind:`error`,value:e})),Lt().transform(e=>({kind:`null`,value:e})),tt().transform(e=>({kind:`undefined`,value:e})),T().transform(e=>({kind:`string`,value:e})),xr().transform(e=>({kind:`boolean`,value:e})),Qr([dr(),yn(),Lr(1/0),Lr(-1/0)]).transform(e=>({kind:`number`,value:e})),tr().transform(e=>({kind:`bigint`,value:e})),ri().transform(e=>({kind:`symbol`,value:e})),Ot(Function).transform(e=>({kind:`function`,value:e})),pn(lt()).transform(e=>({kind:`array`,value:e})),Qr([Ot(Object),Cn(T(),lt())]).transform(e=>({kind:`object`,value:e})),lt().transform(()=>({kind:`opaque`}))])));function vS(e){return gS.safeParse(e).success}function yS(e){let t=gS.safeParse(e);return t.success?t.data:new pS({rawCause:e})}function bS(e){let t=_S.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}C(()=>nn().optional());function xS(e){return SS(e,new Set)}function SS(e,t){let n=_S.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=>SS(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,SS(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=SS(r.cause,t)),r instanceof AggregateError&&(e.errors=SS(r.errors,t))}return e}finally{t.delete(e)}}}}var CS=C(()=>Zn({name:Lr(`ReferenceError`),message:T().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));C(()=>Qr([CS,Zn({name:T(),message:T()})]).and(Zn({transportMessage:T().max(512).optional()})));var wS=C(()=>Vt({v:Lr(1),kind:Lr(`sandbox_failure`),tag:Te([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:T().min(1).max(32),message:T().max(160)})),TS=O(W($p)),ES=C(()=>T().transform((e,t)=>{let n=TS(e);return pe(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),gn):n.success})).pipe(wS);Vt({error:ES}),C(()=>lt().pipe(Qr([Lr(`Execution timed out`).transform(()=>({kind:`deadline`})),lt().transform(e=>({kind:`bad_response`,rawCause:e}))])));var DS=Vt({sandboxCapacity:Dr().positive().optional(),admissionWaitMs:Dr().min(1).max(9e5).optional()});function OS(e,t){let n=DS.safeParse(e??{}),r=Dr().positive().safeParse(t??2);if(!n.success||!r.success)throw new K(`Sandbox admission policy is invalid`);return Object.freeze({capacity:n.data.sandboxCapacity??Math.min(32,Math.max(2,r.data)),waitMs:n.data.admissionWaitMs??18e4})}var kS=[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],AS=[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],jS=`‌‍·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࢗ-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ-᫝᫠-᫫ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,MS=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-࢏ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚ౜ౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ೜-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-ᲊᲐ-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-Ƛ꟱-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,NS={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`},PS=`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`,FS={5:PS,"5module":PS+` export import`,6:PS+` const class extends export import super`},IS=/^in(stanceof)?$/,LS=RegExp(`[`+MS+`]`),RS=RegExp(`[`+MS+jS+`]`);function zS(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 BS(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&LS.test(String.fromCharCode(e)):t!==!1&&zS(e,AS)}function VS(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&&RS.test(String.fromCharCode(e)):t===!1?!1:zS(e,AS)||zS(e,kS)}var HS=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 US(e,t){return new HS(e,{beforeExpr:!0,binop:t})}var WS={beforeExpr:!0},GS={startsExpr:!0},KS={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,KS[e]=new HS(e,t)}var J={num:new HS(`num`,GS),regexp:new HS(`regexp`,GS),string:new HS(`string`,GS),name:new HS(`name`,GS),privateId:new HS(`privateId`,GS),eof:new HS(`eof`),bracketL:new HS(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new HS(`]`),braceL:new HS(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new HS(`}`),parenL:new HS(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new HS(`)`),comma:new HS(`,`,WS),semi:new HS(`;`,WS),colon:new HS(`:`,WS),dot:new HS(`.`),question:new HS(`?`,WS),questionDot:new HS(`?.`),arrow:new HS(`=>`,WS),template:new HS(`template`),invalidTemplate:new HS(`invalidTemplate`),ellipsis:new HS(`...`,WS),backQuote:new HS("`",GS),dollarBraceL:new HS("${",{beforeExpr:!0,startsExpr:!0}),eq:new HS(`=`,{beforeExpr:!0,isAssign:!0}),assign:new HS(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new HS(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new HS(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:US(`||`,1),logicalAND:US(`&&`,2),bitwiseOR:US(`|`,3),bitwiseXOR:US(`^`,4),bitwiseAND:US(`&`,5),equality:US(`==/!=/===/!==`,6),relational:US(`</>/<=/>=`,7),bitShift:US(`<</>>/>>>`,8),plusMin:new HS(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:US(`%`,10),star:US(`*`,10),slash:US(`/`,10),starstar:new HS(`**`,{beforeExpr:!0}),coalesce:US(`??`,1),_break:q(`break`),_case:q(`case`,WS),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,WS),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,WS),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,GS),_if:q(`if`),_return:q(`return`,WS),_switch:q(`switch`),_throw:q(`throw`,WS),_try:q(`try`),_var:q(`var`),_const:q(`const`),_while:q(`while`,{isLoop:!0}),_with:q(`with`),_new:q(`new`,{beforeExpr:!0,startsExpr:!0}),_this:q(`this`,GS),_super:q(`super`,GS),_class:q(`class`,GS),_extends:q(`extends`,WS),_export:q(`export`),_import:q(`import`,GS),_null:q(`null`,GS),_true:q(`true`,GS),_false:q(`false`,GS),_in:q(`in`,{beforeExpr:!0,binop:7}),_instanceof:q(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:q(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:q(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:q(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},qS=/\r\n?|\n|\u2028|\u2029/,JS=new RegExp(qS.source,`g`);function YS(e){return e===10||e===13||e===8232||e===8233}function XS(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(YS(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var ZS=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,QS=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,$S=Object.prototype,eC=$S.hasOwnProperty,tC=$S.toString,nC=Object.hasOwn||(function(e,t){return eC.call(e,t)}),rC=Array.isArray||(function(e){return tC.call(e)===`[object Array]`}),iC=Object.create(null);function aC(e){return iC[e]||(iC[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function oC(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var sC=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,cC=function(e,t){this.line=e,this.column=t};cC.prototype.offset=function(e){return new cC(this.line,this.column+e)};var lC=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function uC(e,t){for(var n=1,r=0;;){var i=XS(e,r,t);if(i<0)return new cC(n,t-r);++n,r=i}}var dC={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},fC=!1;function pC(e){var t={};for(var n in dC)t[n]=e&&nC(e,n)?e[n]:dC[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!fC&&typeof console==`object`&&console.warn&&(fC=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
11
- Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=11):t.ecmaVersion>=2015&&(t.ecmaVersion-=2009),t.allowReserved??=t.ecmaVersion<5,(!e||e.allowHashBang==null)&&(t.allowHashBang=t.ecmaVersion>=14),rC(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}if(rC(t.onComment)&&(t.onComment=mC(t,t.onComment)),t.sourceType===`commonjs`&&t.allowAwaitOutsideFunction)throw Error(`Cannot use allowAwaitOutsideFunction with sourceType: commonjs`);return t}function mC(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 lC(this,o,s)),e.ranges&&(c.range=[i,a]),t.push(c)}}var hC=1,gC=2,_C=4,vC=8,yC=16,bC=32,xC=64,SC=128,CC=256,wC=512,TC=1024,EC=hC|gC|CC;function DC(e,t){return gC|(e?_C:0)|(t?vC:0)}var OC=0,kC=1,AC=2,jC=3,MC=4,NC=5,PC=function(e,t,n){this.options=e=pC(e),this.sourceFile=e.sourceFile,this.keywords=aC(FS[e.ecmaVersion>=6?6:e.sourceType===`module`?`5module`:5]);var r=``;e.allowReserved!==!0&&(r=NS[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType===`module`&&(r+=` await`)),this.reservedWords=aC(r);var i=(r?r+` `:``)+NS.strict;this.reservedWordsStrict=aC(i),this.reservedWordsStrictBind=aC(i+` `+NS.strictBind),this.input=String(t),this.containsEsc=!1,this.pos=n||0,this.curLine=1,e.startLocation?(this.lineStart=this.pos-e.startLocation.column,this.curLine=e.startLocation.line):n?(this.lineStart=this.input.lastIndexOf(`
12
- `,n-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(qS).length)):this.lineStart=0,this.type=J.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType===`module`,this.strict=this.inModule||e.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)===`#!`&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType===`commonjs`?gC:hC),this.regexpState=null,this.privateNameStack=[]},FC={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}};PC.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},FC.inFunction.get=function(){return(this.currentVarScope().flags&gC)>0},FC.inGenerator.get=function(){return(this.currentVarScope().flags&vC)>0},FC.inAsync.get=function(){return(this.currentVarScope().flags&_C)>0},FC.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(CC|wC))return!1;if(t&gC)return(t&_C)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},FC.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&hC)},FC.allowSuper.get=function(){return(this.currentThisScope().flags&xC)>0||this.options.allowSuperOutsideMethod},FC.allowDirectSuper.get=function(){return(this.currentThisScope().flags&SC)>0},FC.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},FC.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(CC|wC)||t&gC&&!(t&yC))return!0}return!1},FC.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&TC||!this.inModule&&e&hC)},FC.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&CC)>0},PC.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},PC.parse=function(e,t){return new this(t,e).parse()},PC.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},PC.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(PC.prototype,FC);var IC=PC.prototype,LC=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;IC.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){QS.lastIndex=e,e+=QS.exec(this.input)[0].length;var t=LC.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){QS.lastIndex=e+t[0].length;var n=QS.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||qS.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,QS.lastIndex=e,e+=QS.exec(this.input)[0].length,this.input[e]===`;`&&e++}},IC.eat=function(e){return this.type===e&&(this.next(),!0)},IC.isContextual=function(e){return this.type===J.name&&this.value===e&&!this.containsEsc},IC.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},IC.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}},IC.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},IC.canInsertSemicolon=function(){return this.type===J.eof||this.type===J.braceR||qS.test(this.input.slice(this.lastTokEnd,this.start))},IC.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},IC.semicolon=function(){!this.eat(J.semi)&&!this.insertSemicolon()&&this.unexpected()},IC.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},IC.expect=function(e){this.eat(e)||this.unexpected()},IC.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var RC=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};IC.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`)}},IC.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`)},IC.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`)},IC.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var Y=PC.prototype;Y.parseTopLevel=function(e){var t=Object.create(null);for(e.body||=[];this.type!==J.eof;){var n=this.parseStatement(null,!0,t);e.body.push(n)}if(this.inModule)for(var r=0,i=Object.keys(this.undefinedExports);r<i.length;r+=1){var a=i[r];this.raiseRecoverable(this.undefinedExports[a].start,`Export '`+a+`' is not defined`)}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType===`commonjs`?`script`:this.options.sourceType,this.finishNode(e,`Program`)};var zC={kind:`loop`},BC={kind:`switch`};Y.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;QS.lastIndex=this.pos;var t=QS.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(BS(r)){var i=n;do n+=r<=65535?1:2;while(VS(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!IS.test(a))return!0}return!1},Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;QS.lastIndex=this.pos;var e=QS.exec(this.input),t=this.pos+e[0].length,n;return!qS.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(VS(n=this.fullCharCodeAt(t+8))||n===92))},Y.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;QS.lastIndex=this.pos;var n=QS.exec(this.input),r=this.pos+n[0].length;if(qS.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||VS(a=this.fullCharCodeAt(i))||a===92)return!1;QS.lastIndex=i;var o=QS.exec(this.input);if(r=i+o[0].length,o&&qS.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!BS(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(VS(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(IS.test(l))return!1;if(t&&!e&&l===`of`){QS.lastIndex=r;var u=QS.exec(this.input);if(r+=u[0].length,this.input.charCodeAt(r)!==61||(s=this.input.charCodeAt(r+1))===61||s===62)return!1}return!0},Y.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},Y.isUsing=function(e){return this.isUsingKeyword(!1,e)},Y.parseStatement=function(e,t,n){var r=this.type,i=this.startNode(),a;switch(this.isLet(e)&&(r=J._var,a=`let`),r){case J._break:case J._continue:return this.parseBreakContinueStatement(i,r.keyword);case J._debugger:return this.parseDebuggerStatement(i);case J._do:return this.parseDoStatement(i);case J._for:return this.parseForStatement(i);case J._function:return e&&(this.strict||e!==`if`&&e!==`label`)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case J._class:return e&&this.unexpected(),this.parseClass(i,!0);case J._if:return this.parseIfStatement(i);case J._return:return this.parseReturnStatement(i);case J._switch:return this.parseSwitchStatement(i);case J._throw:return this.parseThrowStatement(i);case J._try:return this.parseTryStatement(i);case J._const:case J._var:return a||=this.value,e&&a!==`var`&&this.unexpected(),this.parseVarStatement(i,a);case J._while:return this.parseWhileStatement(i);case J._with:return this.parseWithStatement(i);case J.braceL:return this.parseBlock(!0,i);case J.semi:return this.parseEmptyStatement(i);case J._export:case J._import:if(this.options.ecmaVersion>10&&r===J._import){QS.lastIndex=this.pos;var o=QS.exec(this.input),s=this.pos+o[0].length,c=this.input.charCodeAt(s);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,`'import' and 'export' may only appear at the top level`),this.inModule||this.raise(this.start,`'import' and 'export' may appear only with 'sourceType: module'`)),r===J._import?this.parseImport(i):this.parseExport(i,n);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.isAwaitUsing(!1)?`await using`:this.isUsing(!1)?`using`:null;if(l)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,`Using declaration is not allowed in single-statement positions`),l===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.next(),this.parseVar(i,!1,l),this.semicolon(),this.finishNode(i,`VariableDeclaration`);var u=this.value,d=this.parseExpression();return r===J.name&&d.type===`Identifier`&&this.eat(J.colon)?this.parseLabeledStatement(i,u,d,e):this.parseExpressionStatement(i,d)}},Y.parseBreakContinueStatement=function(e,t){var n=t===`break`;this.next(),this.eat(J.semi)||this.insertSemicolon()?e.label=null:this.type===J.name?(e.label=this.parseIdent(),this.semicolon()):this.unexpected();for(var r=0;r<this.labels.length;++r){var i=this.labels[r];if((e.label==null||i.name===e.label.name)&&(i.kind!=null&&(n||i.kind===`loop`)||e.label&&n))break}return r===this.labels.length&&this.raise(e.start,`Unsyntactic `+t),this.finishNode(e,n?`BreakStatement`:`ContinueStatement`)},Y.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,`DebuggerStatement`)},Y.parseDoStatement=function(e){return this.next(),this.labels.push(zC),e.body=this.parseStatement(`do`),this.labels.pop(),this.expect(J._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(J.semi):this.semicolon(),this.finishNode(e,`DoWhileStatement`)},Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual(`await`)?this.lastTokStart:-1;if(this.labels.push(zC),this.enterScope(0),this.expect(J.parenL),this.type===J.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var n=this.isLet();if(this.type===J._var||this.type===J._const||n){var r=this.startNode(),i=n?`let`:this.value;return this.next(),this.parseVar(r,!0,i),this.finishNode(r,`VariableDeclaration`),this.parseForAfterInit(e,r,t)}var a=this.isContextual(`let`),o=!1,s=this.isUsing(!0)?`using`:this.isAwaitUsing(!0)?`await using`:null;if(s){var c=this.startNode();return this.next(),s===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.parseVar(c,!0,s),this.finishNode(c,`VariableDeclaration`),this.parseForAfterInit(e,c,t)}var l=this.containsEsc,u=new RC,d=this.start,f=t>-1?this.parseExprSubscripts(u,`await`):this.parseExpression(!0,u);return this.type===J._in||(o=this.options.ecmaVersion>=6&&this.isContextual(`of`))?(t>-1?(this.type===J._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(f.start===d&&!l&&f.type===`Identifier`&&f.name===`async`?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),a&&o&&this.raise(f.start,`The left-hand side of a for-of loop may not start with 'let'.`),this.toAssignable(f,!1,u),this.checkLValPattern(f),this.parseForIn(e,f)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,f))},Y.parseForAfterInit=function(e,t,n){return(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))&&t.declarations.length===1?(this.type===J._in?((t.kind===`using`||t.kind===`await using`)&&!t.declarations[0].init&&this.raise(this.start,`Using declaration is not allowed in for-in loops`),this.options.ecmaVersion>=9&&n>-1&&this.unexpected(n)):this.options.ecmaVersion>=9&&(e.await=n>-1),this.parseForIn(e,t)):(n>-1&&this.unexpected(n),this.parseFor(e,t))},Y.parseFunctionStatement=function(e,t,n){return this.next(),this.parseFunction(e,HC|(n?0:UC),!1,t)},Y.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(`if`),e.alternate=this.eat(J._else)?this.parseStatement(`if`):null,this.finishNode(e,`IfStatement`)},Y.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,`'return' outside of function`),this.next(),this.eat(J.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,`ReturnStatement`)},Y.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(J.braceL),this.labels.push(BC),this.enterScope(TC);for(var t,n=!1;this.type!==J.braceR;)if(this.type===J._case||this.type===J._default){var r=this.type===J._case;t&&this.finishNode(t,`SwitchCase`),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,`Multiple default clauses`),n=!0,t.test=null),this.expect(J.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,`SwitchCase`),this.next(),this.labels.pop(),this.finishNode(e,`SwitchStatement`)},Y.parseThrowStatement=function(e){return this.next(),qS.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 VC=[];Y.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?bC:0),this.checkLValPattern(e,t?MC:AC),this.expect(J.parenR),e},Y.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===J._catch){var t=this.startNode();this.next(),this.eat(J.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,`CatchClause`)}return e.finalizer=this.eat(J._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,`Missing catch or finally clause`),this.finishNode(e,`TryStatement`)},Y.parseVarStatement=function(e,t,n){return this.next(),this.parseVar(e,!1,t,n),this.semicolon(),this.finishNode(e,`VariableDeclaration`)},Y.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(zC),e.body=this.parseStatement(`while`),this.labels.pop(),this.finishNode(e,`WhileStatement`)},Y.parseWithStatement=function(e){return this.strict&&this.raise(this.start,`'with' in strict mode`),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(`with`),this.finishNode(e,`WithStatement`)},Y.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,`EmptyStatement`)},Y.parseLabeledStatement=function(e,t,n,r){for(var i=0,a=this.labels;i<a.length;i+=1)a[i].name===t&&this.raise(n.start,`Label '`+t+`' is already declared`);for(var o=this.type.isLoop?`loop`:this.type===J._switch?`switch`:null,s=this.labels.length-1;s>=0;s--){var c=this.labels[s];if(c.statementStart===e.start)c.statementStart=this.start,c.kind=o;else break}return this.labels.push({name:t,kind:o,statementStart:this.start}),e.body=this.parseStatement(r?r.indexOf(`label`)===-1?r+`label`:r:`label`),this.labels.pop(),e.label=n,this.finishNode(e,`LabeledStatement`)},Y.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,`ExpressionStatement`)},Y.parseBlock=function(e,t,n){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(J.braceL),e&&this.enterScope(0);this.type!==J.braceR;){var r=this.parseStatement(null);t.body.push(r)}return n&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,`BlockStatement`)},Y.parseFor=function(e,t){return e.init=t,this.expect(J.semi),e.test=this.type===J.semi?null:this.parseExpression(),this.expect(J.semi),e.update=this.type===J.parenR?null:this.parseExpression(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,`ForStatement`)},Y.parseForIn=function(e,t){var n=this.type===J._in;return this.next(),t.type===`VariableDeclaration`&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!==`var`||t.declarations[0].id.type!==`Identifier`)&&this.raise(t.start,(n?`for-in`:`for-of`)+` loop variable declaration may not have an initializer`),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssign(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,n?`ForInStatement`:`ForOfStatement`)},Y.parseVar=function(e,t,n,r){for(e.declarations=[],e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(J.eq)?i.init=this.parseMaybeAssign(t):!r&&n===`const`&&!(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))?this.unexpected():!r&&(n===`using`||n===`await using`)&&this.options.ecmaVersion>=17&&this.type!==J._in&&!this.isContextual(`of`)?this.raise(this.lastTokEnd,`Missing initializer in `+n+` declaration`):!r&&i.id.type!==`Identifier`&&!(t&&(this.type===J._in||this.isContextual(`of`)))?this.raise(this.lastTokEnd,`Complex binding patterns require an initialization value`):i.init=null,e.declarations.push(this.finishNode(i,`VariableDeclarator`)),!this.eat(J.comma))break}return e},Y.parseVarId=function(e,t){e.id=t===`using`||t===`await using`?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t===`var`?kC:AC,!1)};var HC=1,UC=2,WC=4;Y.parseFunction=function(e,t,n,r,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===J.star&&t&UC&&this.unexpected(),e.generator=this.eat(J.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&HC&&(e.id=t&WC&&this.type!==J.name?null:this.parseIdent(),e.id&&!(t&UC)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?kC:AC:jC));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(DC(e.async,e.generator)),t&HC||(e.id=this.type===J.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n,!1,i),this.yieldPos=a,this.awaitPos=o,this.awaitIdentPos=s,this.finishNode(e,t&HC?`FunctionDeclaration`:`FunctionExpression`)},Y.parseFunctionParams=function(e){this.expect(J.parenL),e.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),i=this.startNode(),a=!1;for(i.body=[],this.expect(J.braceL);this.type!==J.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type===`MethodDefinition`&&o.kind===`constructor`?(a&&this.raiseRecoverable(o.start,`Duplicate constructor in the same class`),a=!0):o.key&&o.key.type===`PrivateIdentifier`&&GC(r,o)&&this.raiseRecoverable(o.key.start,`Identifier '#`+o.key.name+`' has already been declared`))}return this.strict=n,this.next(),e.body=this.finishNode(i,`ClassBody`),this.exitClassBody(),this.finishNode(e,t?`ClassDeclaration`:`ClassExpression`)},Y.parseClassElement=function(e){if(this.eat(J.semi))return null;var t=this.options.ecmaVersion,n=this.startNode(),r=``,i=!1,a=!1,o=`method`,s=!1;if(this.eatContextual(`static`)){if(t>=13&&this.eat(J.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===J.star?s=!0:r=`static`}if(n.static=s,!r&&t>=8&&this.eatContextual(`async`)&&((this.isClassElementNameStart()||this.type===J.star)&&!this.canInsertSemicolon()?a=!0:r=`async`),!r&&(t>=9||!a)&&this.eat(J.star)&&(i=!0),!r&&!a&&!i){var c=this.value;(this.eatContextual(`get`)||this.eatContextual(`set`))&&(this.isClassElementNameStart()?o=c:r=c)}if(r?(n.computed=!1,n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),n.key.name=r,this.finishNode(n.key,`Identifier`)):this.parseClassElementName(n),t<13||this.type===J.parenL||o!==`method`||i||a){var l=!n.static&&KC(n,`constructor`),u=l&&e;l&&o!==`method`&&this.raise(n.key.start,`Constructor can't have get/set modifier`),n.kind=l?`constructor`:o,this.parseClassMethod(n,i,a,u)}else this.parseClassField(n);return n},Y.isClassElementNameStart=function(){return this.type===J.name||this.type===J.privateId||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword},Y.parseClassElementName=function(e){this.type===J.privateId?(this.value===`constructor`&&this.raise(this.start,`Classes can't have an element named '#constructor'`),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},Y.parseClassMethod=function(e,t,n,r){var i=e.key;e.kind===`constructor`?(t&&this.raise(i.start,`Constructor can't be a generator`),n&&this.raise(i.start,`Constructor can't be an async method`)):e.static&&KC(e,`prototype`)&&this.raise(i.start,`Classes may not have a static property named prototype`);var a=e.value=this.parseMethod(t,n,r);return e.kind===`get`&&a.params.length!==0&&this.raiseRecoverable(a.start,`getter should have no params`),e.kind===`set`&&a.params.length!==1&&this.raiseRecoverable(a.start,`setter should have exactly one param`),e.kind===`set`&&a.params[0].type===`RestElement`&&this.raiseRecoverable(a.params[0].start,`Setter cannot use rest params`),this.finishNode(e,`MethodDefinition`)},Y.parseClassField=function(e){return KC(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&KC(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(J.eq)?(this.enterScope(wC|xC),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,`PropertyDefinition`)},Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(CC|xC);this.type!==J.braceR;){var n=this.parseStatement(null);e.body.push(n)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,`StaticBlock`)},Y.parseClassId=function(e,t){this.type===J.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,AC,!1)):(t===!0&&this.unexpected(),e.id=null)},Y.parseClassSuper=function(e){e.superClass=this.eat(J._extends)?this.parseExprSubscripts(null,!1):null},Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},Y.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,n=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,i=r===0?null:this.privateNameStack[r-1],a=0;a<n.length;++a){var o=n[a];nC(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function GC(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 KC(e,t){var n=e.computed,r=e.key;return!n&&(r.type===`Identifier`&&r.name===t||r.type===`Literal`&&r.value===t)}Y.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual(`as`)?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual(`from`),this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ExportAllDeclaration`)},Y.parseExport=function(e,t){if(this.next(),this.eat(J.star))return this.parseExportAllDeclaration(e,t);if(this.eat(J._default))return this.checkExport(t,`default`,this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,`ExportDefaultDeclaration`);if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type===`VariableDeclaration`?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual(`from`))this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var n=0,r=e.specifiers;n<r.length;n+=1){var i=r[n];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type===`Literal`&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,`ExportNamedDeclaration`)},Y.parseExportDeclaration=function(e){return this.parseStatement(null)},Y.parseExportDefaultDeclaration=function(){var e;if(this.type===J._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,HC|WC,!1,e)}if(this.type===J._class){var n=this.startNode();return this.parseClass(n,`nullableID`)}var r=this.parseMaybeAssign();return this.semicolon(),r},Y.checkExport=function(e,t,n){e&&(typeof t!=`string`&&(t=t.type===`Identifier`?t.name:t.value),nC(e,t)&&this.raiseRecoverable(n,`Duplicate export '`+t+`'`),e[t]=!0)},Y.checkPatternExport=function(e,t){var n=t.type;if(n===`Identifier`)this.checkExport(e,t,t.start);else if(n===`ObjectPattern`)for(var r=0,i=t.properties;r<i.length;r+=1){var a=i[r];this.checkPatternExport(e,a)}else if(n===`ArrayPattern`)for(var o=0,s=t.elements;o<s.length;o+=1){var c=s[o];c&&this.checkPatternExport(e,c)}else n===`Property`?this.checkPatternExport(e,t.value):n===`AssignmentPattern`?this.checkPatternExport(e,t.left):n===`RestElement`&&this.checkPatternExport(e,t.argument)},Y.checkVariableExport=function(e,t){if(e)for(var n=0,r=t;n<r.length;n+=1){var i=r[n];this.checkPatternExport(e,i.id)}},Y.shouldParseExportStatement=function(){return this.type.keyword===`var`||this.type.keyword===`const`||this.type.keyword===`class`||this.type.keyword===`function`||this.isLet()||this.isAsyncFunction()},Y.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual(`as`)?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,`ExportSpecifier`)},Y.parseExportSpecifiers=function(e){var t=[],n=!0;for(this.expect(J.braceL);!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;t.push(this.parseExportSpecifier(e))}return t},Y.parseImport=function(e){return this.next(),this.type===J.string?(e.specifiers=VC,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual(`from`),e.source=this.type===J.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ImportDeclaration`)},Y.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual(`as`)?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,AC),this.finishNode(e,`ImportSpecifier`)},Y.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,AC),this.finishNode(e,`ImportDefaultSpecifier`)},Y.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual(`as`),e.local=this.parseIdent(),this.checkLValSimple(e.local,AC),this.finishNode(e,`ImportNamespaceSpecifier`)},Y.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===J.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(J.comma)))return e;if(this.type===J.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(J.braceL);!this.eat(J.braceR);){if(t)t=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;e.push(this.parseImportSpecifier())}return e},Y.parseWithClause=function(){var e=[];if(!this.eat(J._with))return e;this.expect(J.braceL);for(var t={},n=!0;!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;var r=this.parseImportAttribute(),i=r.key.type===`Identifier`?r.key.name:r.key.value;nC(t,i)&&this.raiseRecoverable(r.key.start,`Duplicate attribute key '`+i+`'`),t[i]=!0,e.push(r)}return e},Y.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`),this.expect(J.colon),this.type!==J.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,`ImportAttribute`)},Y.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===J.string){var e=this.parseLiteral(this.value);return sC.test(e.value)&&this.raise(e.start,`An export name cannot include a lone surrogate.`),e}return this.parseIdent(!0)},Y.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},Y.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&e.type===`ExpressionStatement`&&e.expression.type===`Literal`&&typeof e.expression.value==`string`&&(this.input[e.start]===`"`||this.input[e.start]===`'`)};var qC=PC.prototype;qC.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},qC.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},qC.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},qC.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==J.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,`RestElement`)},qC.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case J.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(J.bracketR,!0,!0),this.finishNode(e,`ArrayPattern`);case J.braceL:return this.parseObj(!0)}return this.parseIdent()},qC.parseBindingList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);)if(a?a=!1:this.expect(J.comma),t&&this.type===J.comma)i.push(null);else if(n&&this.afterTrailingComma(e))break;else if(this.type===J.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.expect(e);break}else i.push(this.parseAssignableListItem(r));return i},qC.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},qC.parseBindingListItem=function(e){return e},qC.parseMaybeDefault=function(e,t,n){if(n||=this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(J.eq))return n;var r=this.startNodeAt(e,t);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,`AssignmentPattern`)},qC.checkLValSimple=function(e,t,n){t===void 0&&(t=OC);var r=t!==OC;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===AC&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(nC(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==NC&&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`)}},qC.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=OC),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)}},qC.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=OC),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 JC=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},YC={b_stat:new JC(`{`,!1),b_expr:new JC(`{`,!0),b_tmpl:new JC("${",!1),p_stat:new JC(`(`,!1),p_expr:new JC(`(`,!0),q_tmpl:new JC("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new JC(`function`,!1),f_expr:new JC(`function`,!0),f_expr_gen:new JC(`function`,!0,!1,null,!0),f_gen:new JC(`function`,!1,!1,null,!0)},XC=PC.prototype;XC.initialContext=function(){return[YC.b_stat]},XC.curContext=function(){return this.context[this.context.length-1]},XC.braceIsBlock=function(e){var t=this.curContext();return t===YC.f_expr||t===YC.f_stat?!0:e===J.colon&&(t===YC.b_stat||t===YC.b_expr)?!t.isExpr:e===J._return||e===J.name&&this.exprAllowed?qS.test(this.input.slice(this.lastTokEnd,this.start)):e===J._else||e===J.semi||e===J.eof||e===J.parenR||e===J.arrow?!0:e===J.braceL?t===YC.b_stat:e===J._var||e===J._const||e===J.name?!1:!this.exprAllowed},XC.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},XC.updateContext=function(e){var t,n=this.type;n.keyword&&e===J.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},XC.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},J.parenR.updateContext=J.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===YC.b_stat&&this.curContext().token===`function`&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},J.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?YC.b_stat:YC.b_expr),this.exprAllowed=!0},J.dollarBraceL.updateContext=function(){this.context.push(YC.b_tmpl),this.exprAllowed=!0},J.parenL.updateContext=function(e){var t=e===J._if||e===J._for||e===J._with||e===J._while;this.context.push(t?YC.p_stat:YC.p_expr),this.exprAllowed=!0},J.incDec.updateContext=function(){},J._function.updateContext=J._class.updateContext=function(e){e.beforeExpr&&e!==J._else&&(e!==J.semi||this.curContext()===YC.p_stat)&&!(e===J._return&&qS.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==J.colon&&e!==J.braceL||this.curContext()!==YC.b_stat)?this.context.push(YC.f_expr):this.context.push(YC.f_stat),this.exprAllowed=!1},J.colon.updateContext=function(){this.curContext().token===`function`&&this.context.pop(),this.exprAllowed=!0},J.backQuote.updateContext=function(){this.curContext()===YC.q_tmpl?this.context.pop():this.context.push(YC.q_tmpl),this.exprAllowed=!1},J.star.updateContext=function(e){if(e===J._function){var t=this.context.length-1;this.context[t]===YC.f_expr?this.context[t]=YC.f_expr_gen:this.context[t]=YC.f_gen}this.exprAllowed=!0},J.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==J.dot&&(this.value===`of`&&!this.exprAllowed||this.value===`yield`&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var X=PC.prototype;X.checkPropClash=function(e,t,n){if(!(this.options.ecmaVersion>=9&&e.type===`SpreadElement`)&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var r=e.key,i;switch(r.type){case`Identifier`:i=r.name;break;case`Literal`:i=String(r.value);break;default:return}var a=e.kind;if(this.options.ecmaVersion>=6){i===`__proto__`&&a===`init`&&(t.proto&&(n?n.doubleProto<0&&(n.doubleProto=r.start):this.raiseRecoverable(r.start,`Redefinition of __proto__ property`)),t.proto=!0);return}i=`$`+i;var o=t[i];o?(a===`init`?this.strict&&o.init||o.get||o.set:o.init||o[a])&&this.raiseRecoverable(r.start,`Redefinition of property`):o=t[i]={init:!1,get:!1,set:!1},o[a]=!0}},X.parseExpression=function(e,t){var n=this;return this.catchStackOverflow(function(){var r=n.start,i=n.startLoc,a=n.parseMaybeAssign(e,t);if(n.type===J.comma){var o=n.startNodeAt(r,i);for(o.expressions=[a];n.eat(J.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return n.finishNode(o,`SequenceExpression`)}return a})},X.parseMaybeAssign=function(e,t,n){if(this.isContextual(`yield`)){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var r=!1,i=-1,a=-1,o=-1;t?(i=t.parenthesizedAssign,a=t.trailingComma,o=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new RC,r=!0);var s=this.start,c=this.startLoc;(this.type===J.parenL||this.type===J.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=e===`await`);var l=this.parseMaybeConditional(e,t);if(n&&(l=n.call(this,l,s,c)),this.type.isAssign){var u=this.startNodeAt(s,c);return u.operator=this.value,this.type===J.eq&&(l=this.toAssignable(l,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=l.start&&(t.shorthandAssign=-1),this.type===J.eq?this.checkLValPattern(l):this.checkLValSimple(l),u.left=l,this.next(),u.right=this.parseMaybeAssign(e),o>-1&&(t.doubleProto=o),this.finishNode(u,`AssignmentExpression`)}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),a>-1&&(t.trailingComma=a),l},X.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if((i.type!==`ArrowFunctionExpression`||i.start!==n)&&this.eat(J.question)){var a=this.startNodeAt(n,r);return a.test=i,a.consequent=this.parseMaybeAssign(),this.expect(J.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,`ConditionalExpression`)}return i},X.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===n&&i.type===`ArrowFunctionExpression`?i:this.parseExprOp(i,n,r,-1,e)},X.parseExprOp=function(e,t,n,r,i){var a=this.type.binop;if(a!=null&&(!i||this.type!==J._in)&&a>r){var o=this.type===J.logicalOR||this.type===J.logicalAND,s=this.type===J.coalesce;s&&(a=J.logicalAND.binop);var c=this.value;this.next();var l=this.start,u=this.startLoc,d=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),l,u,a,i),f=this.buildBinary(t,n,e,d,c,o||s);return(o&&this.type===J.coalesce||s&&(this.type===J.logicalOR||this.type===J.logicalAND))&&this.raiseRecoverable(this.start,`Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses`),this.parseExprOp(f,t,n,r,i)}return e},X.buildBinary=function(e,t,n,r,i,a){r.type===`PrivateIdentifier`&&this.raise(r.start,`Private identifier can only be left side of binary expression`);var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,a?`LogicalExpression`:`BinaryExpression`)},X.parseMaybeUnary=function(e,t,n,r){var i=this.start,a=this.startLoc,o;if(this.isContextual(`await`)&&this.canAwait)o=this.parseAwait(r),t=!0;else if(this.type.prefix){var s=this.startNode(),c=this.type===J.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0,c,r),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(s.argument):this.strict&&s.operator===`delete`&&ZC(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&QC(s.argument)?this.raiseRecoverable(s.start,`Private fields can not be deleted`):t=!0,o=this.finishNode(s,c?`UpdateExpression`:`UnaryExpression`)}else if(!t&&this.type===J.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==J._in&&this.unexpected();else{if(o=this.parseExprSubscripts(e,r),this.checkExpressionErrors(e))return o;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(i,a);l.operator=this.value,l.prefix=!1,l.argument=o,this.checkLValSimple(o),this.next(),o=this.finishNode(l,`UpdateExpression`)}}if(!n&&(o.type!==`ArrowFunctionExpression`||o.start!==i)&&this.eat(J.starstar)){if(t)this.unexpected(this.lastTokStart);else return this.buildBinary(i,a,o,this.parseMaybeUnary(null,!1,!1,r),`**`,!1)}else return o};function ZC(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&&ZC(e.expression)}function QC(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&QC(e.expression)||e.type===`ParenthesizedExpression`&&QC(e.expression)}X.parseExprSubscripts=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprAtom(e,t);if(i.type===`ArrowFunctionExpression`&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==`)`)return i;var a=this.parseSubscripts(i,n,r,!1,t);return e&&a.type===`MemberExpression`&&(e.parenthesizedAssign>=a.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=a.start&&(e.parenthesizedBind=-1),e.trailingComma>=a.start&&(e.trailingComma=-1)),a},X.parseSubscripts=function(e,t,n,r,i){for(var a=this.options.ecmaVersion>=8&&e.type===`Identifier`&&e.name===`async`&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.potentialArrowAt===e.start,o=!1;;){var s=this.parseSubscript(e,t,n,r,a,o,i);if(s.optional&&(o=!0),s===e||s.type===`ArrowFunctionExpression`){if(o){var c=this.startNodeAt(t,n);c.expression=s,s=this.finishNode(c,`ChainExpression`)}return s}e=s}},X.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(J.arrow)},X.parseSubscriptAsyncArrow=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!0,r)},X.parseSubscript=function(e,t,n,r,i,a,o){var s=this.options.ecmaVersion>=11,c=s&&this.eat(J.questionDot);r&&c&&this.raise(this.lastTokStart,`Optional chaining cannot appear in the callee of new expressions`);var l=this.eat(J.bracketL);if(l||c&&this.type!==J.parenL&&this.type!==J.backQuote||this.eat(J.dot)){var u=this.startNodeAt(t,n);u.object=e,l?(u.property=this.parseExpression(),this.expect(J.bracketR)):u.property=this.type===J.privateId&&e.type!==`Super`?this.parsePrivateIdent():this.parseIdent(this.options.allowReserved!==`never`),u.computed=!!l,s&&(u.optional=c),e=this.finishNode(u,`MemberExpression`)}else if(!r&&this.eat(J.parenL)){var d=new RC,f=this.yieldPos,p=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var ee=this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1,d);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,`Cannot use 'await' as identifier inside an async function`),this.yieldPos=f,this.awaitPos=p,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,n,ee,o);this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var h=this.startNodeAt(t,n);h.callee=e,h.arguments=ee,s&&(h.optional=c),e=this.finishNode(h,`CallExpression`)}else if(this.type===J.backQuote){(c||a)&&this.raise(this.start,`Optional chaining cannot appear in the tag of tagged template expressions`);var te=this.startNodeAt(t,n);te.tag=e,te.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(te,`TaggedTemplateExpression`)}return e},X.parseExprAtom=function(e,t,n){this.type===J.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case J._super:return this.allowSuper||this.raise(this.start,`'super' keyword outside a method`),r=this.startNode(),this.next(),this.type===J.parenL&&!this.allowDirectSuper&&this.raise(r.start,`super() call outside constructor of a subclass`),this.type!==J.dot&&this.type!==J.bracketL&&this.type!==J.parenL&&this.unexpected(),this.finishNode(r,`Super`);case J._this:return r=this.startNode(),this.next(),this.finishNode(r,`ThisExpression`);case J.name:var a=this.start,o=this.startLoc,s=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!s&&c.name===`async`&&!this.canInsertSemicolon()&&this.eat(J._function))return this.overrideContext(YC.f_expr),this.parseFunction(this.startNodeAt(a,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(J.arrow))return this.parseArrowExpression(this.startNodeAt(a,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name===`async`&&this.type===J.name&&!s&&(!this.potentialArrowInForAwait||this.value!==`of`||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(J.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,o),[c],!0,t)}return c;case J.regexp:var l=this.value;return r=this.parseLiteral(l.value),r.regex={pattern:l.pattern,flags:l.flags},r;case J.num:case J.string:return this.parseLiteral(this.value);case J._null:case J._true:case J._false:return r=this.startNode(),r.value=this.type===J._null?null:this.type===J._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,`Literal`);case J.parenL:var u=this.start,d=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)&&(e.parenthesizedAssign=u),e.parenthesizedBind<0&&(e.parenthesizedBind=u)),d;case J.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(J.bracketR,!0,!0,e),this.finishNode(r,`ArrayExpression`);case J.braceL:return this.overrideContext(YC.b_expr),this.parseObj(!1,e);case J._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case J._class:return this.parseClass(this.startNode(),!1);case J._new:return this.parseNew();case J.backQuote:return this.parseTemplate();case J._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}},X.parseExprAtomDefault=function(){this.unexpected()},X.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword import`),this.next(),this.type===J.parenL&&!e)return this.parseDynamicImport(t);if(this.type===J.dot){var n=this.startNodeAt(t.start,t.loc&&t.loc.start);return n.name=`import`,t.meta=this.finishNode(n,`Identifier`),this.parseImportMeta(t)}this.unexpected()},X.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(J.parenR)?e.options=null:(this.expect(J.comma),this.afterTrailingComma(J.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(J.parenR)||(this.expect(J.comma),this.afterTrailingComma(J.parenR)||this.unexpected())));else if(!this.eat(J.parenR)){var t=this.start;this.eat(J.comma)&&this.eat(J.parenR)?this.raiseRecoverable(t,`Trailing comma is not allowed in import()`):this.unexpected(t)}return this.finishNode(e,`ImportExpression`)},X.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`meta`&&this.raiseRecoverable(e.property.start,`The only valid meta property for import is 'import.meta'`),t&&this.raiseRecoverable(e.start,`'import.meta' must not contain escaped characters`),this.options.sourceType!==`module`&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,`Cannot use 'import.meta' outside a module`),this.finishNode(e,`MetaProperty`)},X.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value==null?t.raw.slice(0,-1).replace(/_/g,``):t.value.toString()),this.next(),this.finishNode(t,`Literal`)},X.parseParenExpression=function(){this.expect(J.parenL);var e=this.parseExpression();return this.expect(J.parenR),e},X.shouldParseArrow=function(e){return!this.canInsertSemicolon()},X.parseParenAndDistinguishExpression=function(e,t){var n=this.start,r=this.startLoc,i,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc,c=[],l=!0,u=!1,d=new RC,f=this.yieldPos,p=this.awaitPos,m;for(this.yieldPos=0,this.awaitPos=0;this.type!==J.parenR;){if(l?l=!1:this.expect(J.comma),a&&this.afterTrailingComma(J.parenR,!0)){u=!0;break}if(this.type===J.ellipsis){m=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`);break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var ee=this.lastTokEnd,h=this.lastTokEndLoc;if(this.expect(J.parenR),e&&this.shouldParseArrow(c)&&this.eat(J.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=p,this.parseParenArrowList(n,r,c,t);(!c.length||u)&&this.unexpected(this.lastTokStart),m&&this.unexpected(m),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,c.length>1?(i=this.startNodeAt(o,s),i.expressions=c,this.finishNodeAt(i,`SequenceExpression`,ee,h)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var te=this.startNodeAt(n,r);return te.expression=i,this.finishNode(te,`ParenthesizedExpression`)}return i},X.parseParenItem=function(e){return e},X.parseParenArrowList=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!1,r)};var $C=[];X.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword new`);var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===J.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name=`new`,e.meta=this.finishNode(t,`Identifier`),this.next();var n=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`target`&&this.raiseRecoverable(e.property.start,`The only valid meta property for new is 'new.target'`),n&&this.raiseRecoverable(e.start,`'new.target' must not contain escaped characters`),this.allowNewDotTarget||this.raiseRecoverable(e.start,`'new.target' can only be used in functions and class static block`),this.finishNode(e,`MetaProperty`)}var r=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,i,!0,!1),e.callee.type===`Super`&&this.raiseRecoverable(r,`Invalid use of 'super'`),e.arguments=this.eat(J.parenL)?this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1):$C,this.finishNode(e,`NewExpression`)},X.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===J.invalidTemplate?(t||this.raiseRecoverable(this.start,`Bad escape sequence in untagged template literal`),n.value={raw:this.value.replace(/\r\n?/g,`
13
- `),cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
14
- `),cooked:this.value},this.next(),n.tail=this.type===J.backQuote,this.finishNode(n,`TemplateElement`)},X.parseTemplate=function(e){e===void 0&&(e={});var t=e.isTagged;t===void 0&&(t=!1);var n=this.startNode();this.next(),n.expressions=[];var r=this.parseTemplateElement({isTagged:t});for(n.quasis=[r];!r.tail;)this.type===J.eof&&this.raise(this.pos,`Unterminated template literal`),this.expect(J.dollarBraceL),n.expressions.push(this.parseExpression()),this.expect(J.braceR),n.quasis.push(r=this.parseTemplateElement({isTagged:t}));return this.next(),this.finishNode(n,`TemplateLiteral`)},X.isAsyncProp=function(e){return!e.computed&&e.key.type===`Identifier`&&e.key.name===`async`&&(this.type===J.name||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword||this.options.ecmaVersion>=9&&this.type===J.star)&&!qS.test(this.input.slice(this.lastTokEnd,this.start))},X.parseObj=function(e,t){var n=this.startNode(),r=!0,i={};for(n.properties=[],this.next();!this.eat(J.braceR);){if(r)r=!1;else if(this.expect(J.comma),this.options.ecmaVersion>=5&&this.afterTrailingComma(J.braceR))break;var a=this.parseProperty(e,t);e||this.checkPropClash(a,i,t),n.properties.push(a)}return this.finishNode(n,e?`ObjectPattern`:`ObjectExpression`)},X.parseProperty=function(e,t){var n=this.startNode(),r,i,a,o;if(this.options.ecmaVersion>=9&&this.eat(J.ellipsis))return e?(n.argument=this.parseIdent(!1),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.finishNode(n,`RestElement`)):(n.argument=this.parseMaybeAssign(!1,t),this.type===J.comma&&t&&t.trailingComma<0&&(t.trailingComma=this.start),this.finishNode(n,`SpreadElement`));this.options.ecmaVersion>=6&&(n.method=!1,n.shorthand=!1,(e||t)&&(a=this.start,o=this.startLoc),e||(r=this.eat(J.star)));var s=this.containsEsc;return this.parsePropertyName(n),!e&&!s&&this.options.ecmaVersion>=8&&!r&&this.isAsyncProp(n)?(i=!0,r=this.options.ecmaVersion>=9&&this.eat(J.star),this.parsePropertyName(n)):i=!1,this.parsePropertyValue(n,e,r,i,a,o,t,s),this.finishNode(n,`Property`)},X.parseGetterSetter=function(e){var t=e.key.name;this.parsePropertyName(e),e.value=this.parseMethod(!1),e.kind=t;var n=e.kind===`get`?0:1;if(e.value.params.length!==n){var r=e.value.start;e.kind===`get`?this.raiseRecoverable(r,`getter should have no params`):this.raiseRecoverable(r,`setter should have exactly one param`)}else e.kind===`set`&&e.value.params[0].type===`RestElement`&&this.raiseRecoverable(e.value.params[0].start,`Setter cannot use rest params`)},X.parsePropertyValue=function(e,t,n,r,i,a,o,s){(n||r)&&this.type===J.colon&&this.unexpected(),this.eat(J.colon)?(e.value=t?this.parseMaybeDefault(this.start,this.startLoc):this.parseMaybeAssign(!1,o),e.kind=`init`):this.options.ecmaVersion>=6&&this.type===J.parenL?(t&&this.unexpected(),e.method=!0,e.value=this.parseMethod(n,r),e.kind=`init`):!t&&!s&&this.options.ecmaVersion>=5&&!e.computed&&e.key.type===`Identifier`&&(e.key.name===`get`||e.key.name===`set`)&&this.type!==J.comma&&this.type!==J.braceR&&this.type!==J.eq?((n||r)&&this.unexpected(),this.parseGetterSetter(e)):this.options.ecmaVersion>=6&&!e.computed&&e.key.type===`Identifier`?((n||r)&&this.unexpected(),this.checkUnreserved(e.key),e.key.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=i),t?e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key)):this.type===J.eq&&o?(o.shorthandAssign<0&&(o.shorthandAssign=this.start),e.value=this.parseMaybeDefault(i,a,this.copyNode(e.key))):e.value=this.copyNode(e.key),e.kind=`init`,e.shorthand=!0):this.unexpected()},X.parsePropertyName=function(e){if(this.options.ecmaVersion>=6){if(this.eat(J.bracketL))return e.computed=!0,e.key=this.parseMaybeAssign(),this.expect(J.bracketR),e.key;e.computed=!1}return e.key=this.type===J.num||this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`)},X.initFunction=function(e){e.id=null,this.options.ecmaVersion>=6&&(e.generator=e.expression=!1),this.options.ecmaVersion>=8&&(e.async=!1)},X.parseMethod=function(e,t,n){var r=this.startNode(),i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.initFunction(r),this.options.ecmaVersion>=6&&(r.generator=e),this.options.ecmaVersion>=8&&(r.async=!!t),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(DC(t,r.generator)|xC|(n?SC:0)),this.expect(J.parenL),r.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams(),this.parseFunctionBody(r,!1,!0,!1),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(r,`FunctionExpression`)},X.parseArrowExpression=function(e,t,n,r){var i=this.yieldPos,a=this.awaitPos,o=this.awaitIdentPos;return this.enterScope(DC(n,!1)|yC),this.initFunction(e),this.options.ecmaVersion>=8&&(e.async=!!n),this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,e.params=this.toAssignableList(t,!0),this.parseFunctionBody(e,!0,!1,r),this.yieldPos=i,this.awaitPos=a,this.awaitIdentPos=o,this.finishNode(e,`ArrowFunctionExpression`)},X.parseFunctionBody=function(e,t,n,r){var i=t&&this.type!==J.braceL,a=this.strict,o=!1;if(i)e.body=this.parseMaybeAssign(r),e.expression=!0,this.checkParams(e,!1);else{var s=this.options.ecmaVersion>=7&&!this.isSimpleParamList(e.params);(!a||s)&&(o=this.strictDirective(this.end),o&&s&&this.raiseRecoverable(e.start,`Illegal 'use strict' directive in function with non-simple parameter list`));var c=this.labels;this.labels=[],o&&(this.strict=!0),this.checkParams(e,!a&&!o&&!t&&!n&&this.isSimpleParamList(e.params)),this.strict&&e.id&&this.checkLValSimple(e.id,NC),e.body=this.parseBlock(!1,void 0,o&&!a),e.expression=!1,this.adaptDirectivePrologue(e.body.body),this.labels=c}this.exitScope()},X.isSimpleParamList=function(e){for(var t=0,n=e;t<n.length;t+=1)if(n[t].type!==`Identifier`)return!1;return!0},X.checkParams=function(e,t){for(var n=Object.create(null),r=0,i=e.params;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,kC,t?null:n)}},X.parseExprList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);){if(a)a=!1;else if(this.expect(J.comma),t&&this.afterTrailingComma(e))break;var o=void 0;n&&this.type===J.comma?o=null:this.type===J.ellipsis?(o=this.parseSpread(r),r&&this.type===J.comma&&r.trailingComma<0&&(r.trailingComma=this.start)):o=this.parseMaybeAssign(!1,r),i.push(o)}return i},X.checkUnreserved=function(e){var t=e.start,n=e.end,r=e.name;this.inGenerator&&r===`yield`&&this.raiseRecoverable(t,`Cannot use 'yield' as identifier inside a generator`),this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use 'await' as identifier inside an async function`),!(this.currentThisScope().flags&EC)&&r===`arguments`&&this.raiseRecoverable(t,`Cannot use 'arguments' in class field initializer`),this.inClassStaticBlock&&(r===`arguments`||r===`await`)&&this.raise(t,`Cannot use `+r+` in class static initialization block`),this.keywords.test(r)&&this.raise(t,`Unexpected keyword '`+r+`'`),!(this.options.ecmaVersion<6&&this.input.slice(t,n).indexOf(`\\`)!==-1)&&(this.strict?this.reservedWordsStrict:this.reservedWords).test(r)&&(!this.inAsync&&r===`await`&&this.raiseRecoverable(t,`Cannot use keyword 'await' outside an async function`),this.raiseRecoverable(t,`The keyword '`+r+`' is reserved`))},X.parseIdent=function(e){var t=this.parseIdentNode();return this.next(!!e),this.finishNode(t,`Identifier`),e||(this.checkUnreserved(t),t.name===`await`&&!this.awaitIdentPos&&(this.awaitIdentPos=t.start)),t},X.parseIdentNode=function(){var e=this.startNode();return this.type===J.name?e.name=this.value:this.type.keyword?(e.name=this.type.keyword,(e.name===`class`||e.name===`function`)&&(this.lastTokEnd!==this.lastTokStart+1||this.input.charCodeAt(this.lastTokStart)!==46)&&this.context.pop(),this.type=J.name):this.unexpected(),e},X.parsePrivateIdent=function(){var e=this.startNode();return this.type===J.privateId?e.name=this.value:this.unexpected(),this.next(),this.finishNode(e,`PrivateIdentifier`),this.options.checkPrivateFields&&(this.privateNameStack.length===0?this.raise(e.start,`Private field '#`+e.name+`' must be declared in an enclosing class`):this.privateNameStack[this.privateNameStack.length-1].used.push(e)),e},X.parseYield=function(e){this.yieldPos||=this.start;var t=this.startNode();return this.next(),this.type===J.semi||this.canInsertSemicolon()||this.type!==J.star&&!this.type.startsExpr?(t.delegate=!1,t.argument=null):(t.delegate=this.eat(J.star),t.argument=this.parseMaybeAssign(e)),this.finishNode(t,`YieldExpression`)},X.parseAwait=function(e){this.awaitPos||=this.start;var t=this.startNode();return this.next(),t.argument=this.parseMaybeUnary(null,!0,!1,e),this.finishNode(t,`AwaitExpression`)};var ew=PC.prototype;ew.raise=function(e,t){var n=uC(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},ew.raiseRecoverable=ew.raise,ew.curPosition=function(){if(this.options.locations)return new cC(this.curLine,this.pos-this.lineStart)};var tw=PC.prototype,nw=function(e){this.flags=e,this.var=[],this.lexical=[],this.functions=[]};tw.enterScope=function(e){this.scopeStack.push(new nw(e))},tw.exitScope=function(){this.scopeStack.pop()},tw.treatFunctionsAsVarInScope=function(e){return e.flags&gC||!this.inModule&&e.flags&hC},tw.declareName=function(e,t,n){var r=!1;if(t===AC){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&hC&&delete this.undefinedExports[e]}else if(t===MC)this.currentScope().lexical.push(e);else if(t===jC){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&bC&&s.lexical[0]===e)||!this.treatFunctionsAsVarInScope(s)&&s.functions.indexOf(e)>-1){r=!0;break}if(s.var.push(e),this.inModule&&s.flags&hC&&delete this.undefinedExports[e],s.flags&EC)break}r&&this.raiseRecoverable(n,`Identifier '`+e+`' has already been declared`)},tw.checkLocalExport=function(e){this.scopeStack[0].lexical.indexOf(e.name)===-1&&this.scopeStack[0].var.indexOf(e.name)===-1&&(this.undefinedExports[e.name]=e)},tw.currentScope=function(){return this.scopeStack[this.scopeStack.length-1]},tw.currentVarScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(EC|wC|CC))return t}},tw.currentThisScope=function(){for(var e=this.scopeStack.length-1;;e--){var t=this.scopeStack[e];if(t.flags&(EC|wC|CC)&&!(t.flags&yC))return t}};var rw=function(e,t,n){this.type=``,this.start=t,this.end=0,e.options.locations&&(this.loc=new lC(e,n)),e.options.directSourceFile&&(this.sourceFile=e.options.directSourceFile),e.options.ranges&&(this.range=[t,0])},iw=PC.prototype;iw.startNode=function(){return new rw(this,this.start,this.startLoc)},iw.startNodeAt=function(e,t){return new rw(this,e,t)};function aw(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}iw.finishNode=function(e,t){return aw.call(this,e,t,this.lastTokEnd,this.lastTokEndLoc)},iw.finishNodeAt=function(e,t,n,r){return aw.call(this,e,t,n,r)},iw.copyNode=function(e){var t=new rw(this,e.start,this.startLoc);for(var n in e)t[n]=e[n];return t};var ow=`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`,sw=`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`,cw=sw+` Extended_Pictographic`,lw=cw,uw=lw+` EBase EComp EMod EPres ExtPict`,dw=uw,fw={9:sw,10:cw,11:lw,12:uw,13:dw,14:dw},pw={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`},mw=`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`,hw=`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`,gw=hw+` Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd`,_w=gw+` Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho`,vw=_w+` Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi`,yw=vw+` Cypro_Minoan Cpmn Old_Uyghur Ougr Tangsa Tnsa Toto Vithkuqi Vith`,bw={9:hw,10:gw,11:_w,12:vw,13:yw,14:yw+` `+ow},xw={};function Sw(e){var t=xw[e]={binary:aC(fw[e]+` `+mw),binaryOfStrings:aC(pw[e]),nonBinary:{General_Category:aC(mw),Script:aC(bw[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 Cw=0,ww=[9,10,11,12,13,14];Cw<ww.length;Cw+=1){var Tw=ww[Cw];Sw(Tw)}var Z=PC.prototype,Ew=function(e,t){this.parent=e,this.base=t||this};Ew.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},Ew.prototype.sibling=function(){return new Ew(this.parent,this.base)};var Dw=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=xw[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};Dw.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)},Dw.prototype.raise=function(e){this.parser.raiseRecoverable(this.start,`Invalid regular expression: /`+this.source+`/: `+e)},Dw.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},Dw.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},Dw.prototype.current=function(e){return e===void 0&&(e=!1),this.at(this.pos,e)},Dw.prototype.lookahead=function(e){return e===void 0&&(e=!1),this.at(this.nextIndex(this.pos,e),e)},Dw.prototype.advance=function(e){e===void 0&&(e=!1),this.pos=this.nextIndex(this.pos,e)},Dw.prototype.eat=function(e,t){return t===void 0&&(t=!1),this.current(t)===e&&(this.advance(t),!0)},Dw.prototype.eatChars=function(e,t){t===void 0&&(t=!1);for(var n=this.pos,r=0,i=e;r<i.length;r+=1){var a=i[r],o=this.at(n,t);if(o===-1||o!==a)return!1;n=this.nextIndex(n,t)}return this.pos=n,!0},Z.validateRegExpFlags=function(e){for(var t=e.validFlags,n=e.flags,r=!1,i=!1,a=0;a<n.length;a++){var o=n.charAt(a);t.indexOf(o)===-1&&this.raise(e.start,`Invalid regular expression flag`),n.indexOf(o,a+1)>-1&&this.raise(e.start,`Duplicate regular expression flag`),o===`u`&&(r=!0),o===`v`&&(i=!0)}this.options.ecmaVersion>=15&&r&&i&&this.raise(e.start,`Invalid regular expression flag`)};function Ow(e){for(var t in e)return!0;return!1}Z.validateRegExpPattern=function(e){this.regexp_pattern(e),!e.switchN&&this.options.ecmaVersion>=9&&Ow(e.groupNames)&&(e.switchN=!0,this.regexp_pattern(e))},Z.regexp_pattern=function(e){e.pos=0,e.lastIntValue=0,e.lastStringValue=``,e.lastAssertionIsQuantifiable=!1,e.numCapturingParens=0,e.maxBackReference=0,e.groupNames=Object.create(null),e.backReferenceNames.length=0,e.branchID=null,this.regexp_disjunction(e),e.pos!==e.source.length&&(e.eat(41)&&e.raise(`Unmatched ')'`),(e.eat(93)||e.eat(125))&&e.raise(`Lone quantifier brackets`)),e.maxBackReference>e.numCapturingParens&&e.raise(`Invalid escape`);for(var t=0,n=e.backReferenceNames;t<n.length;t+=1){var r=n[t];e.groupNames[r]||e.raise(`Invalid named capture referenced`)}},Z.regexp_disjunction=function(e){var t=this.options.ecmaVersion>=16;for(t&&(e.branchID=new Ew(e.branchID,null)),this.regexp_alternative(e);e.eat(124);)t&&(e.branchID=e.branchID.sibling()),this.regexp_alternative(e);t&&(e.branchID=e.branchID.parent),this.regexp_eatQuantifier(e,!0)&&e.raise(`Nothing to repeat`),e.eat(123)&&e.raise(`Lone quantifier brackets`)},Z.regexp_alternative=function(e){for(;e.pos<e.source.length&&this.regexp_eatTerm(e););},Z.regexp_eatTerm=function(e){return this.regexp_eatAssertion(e)?(e.lastAssertionIsQuantifiable&&this.regexp_eatQuantifier(e)&&e.switchU&&e.raise(`Invalid quantifier`),!0):(e.switchU?this.regexp_eatAtom(e):this.regexp_eatExtendedAtom(e))?(this.regexp_eatQuantifier(e),!0):!1},Z.regexp_eatAssertion=function(e){var t=e.pos;if(e.lastAssertionIsQuantifiable=!1,e.eat(94)||e.eat(36))return!0;if(e.eat(92)){if(e.eat(66)||e.eat(98))return!0;e.pos=t}if(e.eat(40)&&e.eat(63)){var n=!1;if(this.options.ecmaVersion>=9&&(n=e.eat(60)),e.eat(61)||e.eat(33))return this.regexp_disjunction(e),e.eat(41)||e.raise(`Unterminated group`),e.lastAssertionIsQuantifiable=!n,!0}return e.pos=t,!1},Z.regexp_eatQuantifier=function(e,t){return t===void 0&&(t=!1),this.regexp_eatQuantifierPrefix(e,t)?(e.eat(63),!0):!1},Z.regexp_eatQuantifierPrefix=function(e,t){return e.eat(42)||e.eat(43)||e.eat(63)||this.regexp_eatBracedQuantifier(e,t)},Z.regexp_eatBracedQuantifier=function(e,t){var n=e.pos;if(e.eat(123)){var r=0,i=-1;if(this.regexp_eatDecimalDigits(e)&&(r=e.lastIntValue,e.eat(44)&&this.regexp_eatDecimalDigits(e)&&(i=e.lastIntValue),e.eat(125)))return i!==-1&&i<r&&!t&&e.raise(`numbers out of order in {} quantifier`),!0;e.switchU&&!t&&e.raise(`Incomplete quantifier`),e.pos=n}return!1},Z.regexp_eatAtom=function(e){return this.regexp_eatPatternCharacters(e)||e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)},Z.regexp_eatReverseSolidusAtomEscape=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatAtomEscape(e))return!0;e.pos=t}return!1},Z.regexp_eatUncapturingGroup=function(e){var t=e.pos;if(e.eat(40)){if(e.eat(63)){if(this.options.ecmaVersion>=16){var n=this.regexp_eatModifiers(e),r=e.eat(45);if(n||r){for(var i=0;i<n.length;i++){var a=n.charAt(i);n.indexOf(a,i+1)>-1&&e.raise(`Duplicate regular expression modifiers`)}if(r){var o=this.regexp_eatModifiers(e);!n&&!o&&e.current()===58&&e.raise(`Invalid regular expression modifiers`);for(var s=0;s<o.length;s++){var c=o.charAt(s);(o.indexOf(c,s+1)>-1||n.indexOf(c)>-1)&&e.raise(`Duplicate regular expression modifiers`)}}}}if(e.eat(58)){if(this.regexp_disjunction(e),e.eat(41))return!0;e.raise(`Unterminated group`)}}e.pos=t}return!1},Z.regexp_eatCapturingGroup=function(e){if(e.eat(40)){if(this.options.ecmaVersion>=9?this.regexp_groupSpecifier(e):e.current()===63&&e.raise(`Invalid group`),this.regexp_disjunction(e),e.eat(41))return e.numCapturingParens+=1,!0;e.raise(`Unterminated group`)}return!1},Z.regexp_eatModifiers=function(e){for(var t=``,n=0;(n=e.current())!==-1&&kw(n);)t+=oC(n),e.advance();return t};function kw(e){return e===105||e===109||e===115}Z.regexp_eatExtendedAtom=function(e){return e.eat(46)||this.regexp_eatReverseSolidusAtomEscape(e)||this.regexp_eatCharacterClass(e)||this.regexp_eatUncapturingGroup(e)||this.regexp_eatCapturingGroup(e)||this.regexp_eatInvalidBracedQuantifier(e)||this.regexp_eatExtendedPatternCharacter(e)},Z.regexp_eatInvalidBracedQuantifier=function(e){return this.regexp_eatBracedQuantifier(e,!0)&&e.raise(`Nothing to repeat`),!1},Z.regexp_eatSyntaxCharacter=function(e){var t=e.current();return Aw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Aw(e){return e===36||e>=40&&e<=43||e===46||e===63||e>=91&&e<=94||e>=123&&e<=125}Z.regexp_eatPatternCharacters=function(e){for(var t=e.pos,n=0;(n=e.current())!==-1&&!Aw(n);)e.advance();return e.pos!==t},Z.regexp_eatExtendedPatternCharacter=function(e){var t=e.current();return t!==-1&&t!==36&&!(t>=40&&t<=43)&&t!==46&&t!==63&&t!==91&&t!==94&&t!==124&&(e.advance(),!0)},Z.regexp_groupSpecifier=function(e){if(e.eat(63)){this.regexp_eatGroupName(e)||e.raise(`Invalid group`);var t=this.options.ecmaVersion>=16,n=e.groupNames[e.lastStringValue];if(n){if(t)for(var r=0,i=n;r<i.length;r+=1)i[r].separatedFrom(e.branchID)||e.raise(`Duplicate capture group name`);else e.raise(`Duplicate capture group name`)}t?(n||(e.groupNames[e.lastStringValue]=[])).push(e.branchID):e.groupNames[e.lastStringValue]=!0}},Z.regexp_eatGroupName=function(e){if(e.lastStringValue=``,e.eat(60)){if(this.regexp_eatRegExpIdentifierName(e)&&e.eat(62))return!0;e.raise(`Invalid capture group name`)}return!1},Z.regexp_eatRegExpIdentifierName=function(e){if(e.lastStringValue=``,this.regexp_eatRegExpIdentifierStart(e)){for(e.lastStringValue+=oC(e.lastIntValue);this.regexp_eatRegExpIdentifierPart(e);)e.lastStringValue+=oC(e.lastIntValue);return!0}return!1},Z.regexp_eatRegExpIdentifierStart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),jw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function jw(e){return BS(e,!0)||e===36||e===95}Z.regexp_eatRegExpIdentifierPart=function(e){var t=e.pos,n=this.options.ecmaVersion>=11,r=e.current(n);return e.advance(n),r===92&&this.regexp_eatRegExpUnicodeEscapeSequence(e,n)&&(r=e.lastIntValue),Mw(r)?(e.lastIntValue=r,!0):(e.pos=t,!1)};function Mw(e){return VS(e,!0)||e===36||e===95||e===8204||e===8205}Z.regexp_eatAtomEscape=function(e){return this.regexp_eatBackReference(e)||this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)||e.switchN&&this.regexp_eatKGroupName(e)?!0:(e.switchU&&(e.current()===99&&e.raise(`Invalid unicode escape`),e.raise(`Invalid escape`)),!1)},Z.regexp_eatBackReference=function(e){var t=e.pos;if(this.regexp_eatDecimalEscape(e)){var n=e.lastIntValue;if(e.switchU)return n>e.maxBackReference&&(e.maxBackReference=n),!0;if(n<=e.numCapturingParens)return!0;e.pos=t}return!1},Z.regexp_eatKGroupName=function(e){if(e.eat(107)){if(this.regexp_eatGroupName(e))return e.backReferenceNames.push(e.lastStringValue),!0;e.raise(`Invalid named reference`)}return!1},Z.regexp_eatCharacterEscape=function(e){return this.regexp_eatControlEscape(e)||this.regexp_eatCControlLetter(e)||this.regexp_eatZero(e)||this.regexp_eatHexEscapeSequence(e)||this.regexp_eatRegExpUnicodeEscapeSequence(e,!1)||!e.switchU&&this.regexp_eatLegacyOctalEscapeSequence(e)||this.regexp_eatIdentityEscape(e)},Z.regexp_eatCControlLetter=function(e){var t=e.pos;if(e.eat(99)){if(this.regexp_eatControlLetter(e))return!0;e.pos=t}return!1},Z.regexp_eatZero=function(e){return e.current()===48&&!Ww(e.lookahead())&&(e.lastIntValue=0,e.advance(),!0)},Z.regexp_eatControlEscape=function(e){var t=e.current();return t===116?(e.lastIntValue=9,e.advance(),!0):t===110?(e.lastIntValue=10,e.advance(),!0):t===118?(e.lastIntValue=11,e.advance(),!0):t===102?(e.lastIntValue=12,e.advance(),!0):t===114&&(e.lastIntValue=13,e.advance(),!0)},Z.regexp_eatControlLetter=function(e){var t=e.current();return Nw(t)?(e.lastIntValue=t%32,e.advance(),!0):!1};function Nw(e){return e>=65&&e<=90||e>=97&&e<=122}Z.regexp_eatRegExpUnicodeEscapeSequence=function(e,t){t===void 0&&(t=!1);var n=e.pos,r=t||e.switchU;if(e.eat(117)){if(this.regexp_eatFixedHexDigits(e,4)){var i=e.lastIntValue;if(r&&i>=55296&&i<=56319){var a=e.pos;if(e.eat(92)&&e.eat(117)&&this.regexp_eatFixedHexDigits(e,4)){var o=e.lastIntValue;if(o>=56320&&o<=57343)return e.lastIntValue=(i-55296)*1024+(o-56320)+65536,!0}e.pos=a,e.lastIntValue=i}return!0}if(r&&e.eat(123)&&this.regexp_eatHexDigits(e)&&e.eat(125)&&Pw(e.lastIntValue))return!0;r&&e.raise(`Invalid unicode escape`),e.pos=n}return!1};function Pw(e){return e>=0&&e<=1114111}Z.regexp_eatIdentityEscape=function(e){if(e.switchU)return this.regexp_eatSyntaxCharacter(e)?!0:e.eat(47)?(e.lastIntValue=47,!0):!1;var t=e.current();return t!==99&&(!e.switchN||t!==107)&&(e.lastIntValue=t,e.advance(),!0)},Z.regexp_eatDecimalEscape=function(e){e.lastIntValue=0;var t=e.current();if(t>=49&&t<=57){do e.lastIntValue=10*e.lastIntValue+(t-48),e.advance();while((t=e.current())>=48&&t<=57);return!0}return!1};var Fw=0,Iw=1,Lw=2;Z.regexp_eatCharacterClassEscape=function(e){var t=e.current();if(Rw(t))return e.lastIntValue=-1,e.advance(),Iw;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===Lw&&e.raise(`Invalid property name`),r;e.raise(`Invalid property name`)}return Fw};function Rw(e){return e===100||e===68||e===115||e===83||e===119||e===87}Z.regexp_eatUnicodePropertyValueExpression=function(e){var t=e.pos;if(this.regexp_eatUnicodePropertyName(e)&&e.eat(61)){var n=e.lastStringValue;if(this.regexp_eatUnicodePropertyValue(e)){var r=e.lastStringValue;return this.regexp_validateUnicodePropertyNameAndValue(e,n,r),Iw}}if(e.pos=t,this.regexp_eatLoneUnicodePropertyNameOrValue(e)){var i=e.lastStringValue;return this.regexp_validateUnicodePropertyNameOrValue(e,i)}return Fw},Z.regexp_validateUnicodePropertyNameAndValue=function(e,t,n){nC(e.unicodeProperties.nonBinary,t)||e.raise(`Invalid property name`),e.unicodeProperties.nonBinary[t].test(n)||e.raise(`Invalid property value`)},Z.regexp_validateUnicodePropertyNameOrValue=function(e,t){if(e.unicodeProperties.binary.test(t))return Iw;if(e.switchV&&e.unicodeProperties.binaryOfStrings.test(t))return Lw;e.raise(`Invalid property name`)},Z.regexp_eatUnicodePropertyName=function(e){var t=0;for(e.lastStringValue=``;zw(t=e.current());)e.lastStringValue+=oC(t),e.advance();return e.lastStringValue!==``};function zw(e){return Nw(e)||e===95}Z.regexp_eatUnicodePropertyValue=function(e){var t=0;for(e.lastStringValue=``;Bw(t=e.current());)e.lastStringValue+=oC(t),e.advance();return e.lastStringValue!==``};function Bw(e){return zw(e)||Ww(e)}Z.regexp_eatLoneUnicodePropertyNameOrValue=function(e){return this.regexp_eatUnicodePropertyValue(e)},Z.regexp_eatCharacterClass=function(e){if(e.eat(91)){var t=e.eat(94),n=this.regexp_classContents(e);return e.eat(93)||e.raise(`Unterminated character class`),t&&n===Lw&&e.raise(`Negated character class may contain strings`),!0}return!1},Z.regexp_classContents=function(e){return e.current()===93?Iw:e.switchV?this.regexp_classSetExpression(e):(this.regexp_nonEmptyClassRanges(e),Iw)},Z.regexp_nonEmptyClassRanges=function(e){for(;this.regexp_eatClassAtom(e);){var t=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassAtom(e)){var n=e.lastIntValue;e.switchU&&(t===-1||n===-1)&&e.raise(`Invalid character class`),t!==-1&&n!==-1&&t>n&&e.raise(`Range out of order in character class`)}}},Z.regexp_eatClassAtom=function(e){var t=e.pos;if(e.eat(92)){if(this.regexp_eatClassEscape(e))return!0;if(e.switchU){var n=e.current();(n===99||qw(n))&&e.raise(`Invalid class escape`),e.raise(`Invalid escape`)}e.pos=t}var r=e.current();return r!==93&&(e.lastIntValue=r,e.advance(),!0)},Z.regexp_eatClassEscape=function(e){var t=e.pos;if(e.eat(98))return e.lastIntValue=8,!0;if(e.switchU&&e.eat(45))return e.lastIntValue=45,!0;if(!e.switchU&&e.eat(99)){if(this.regexp_eatClassControlLetter(e))return!0;e.pos=t}return this.regexp_eatCharacterClassEscape(e)||this.regexp_eatCharacterEscape(e)},Z.regexp_classSetExpression=function(e){var t=Iw,n;if(!this.regexp_eatClassSetRange(e)){if(n=this.regexp_eatClassSetOperand(e)){n===Lw&&(t=Lw);for(var r=e.pos;e.eatChars([38,38]);){if(e.current()!==38&&(n=this.regexp_eatClassSetOperand(e))){n!==Lw&&(t=Iw);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===Lw&&(t=Lw)}},Z.regexp_eatClassSetRange=function(e){var t=e.pos;if(this.regexp_eatClassSetCharacter(e)){var n=e.lastIntValue;if(e.eat(45)&&this.regexp_eatClassSetCharacter(e)){var r=e.lastIntValue;return n!==-1&&r!==-1&&n>r&&e.raise(`Range out of order in character class`),!0}e.pos=t}return!1},Z.regexp_eatClassSetOperand=function(e){return this.regexp_eatClassSetCharacter(e)?Iw:this.regexp_eatClassStringDisjunction(e)||this.regexp_eatNestedClass(e)},Z.regexp_eatNestedClass=function(e){var t=e.pos;if(e.eat(91)){var n=e.eat(94),r=this.regexp_classContents(e);if(e.eat(93))return n&&r===Lw&&e.raise(`Negated character class may contain strings`),r;e.pos=t}if(e.eat(92)){var i=this.regexp_eatCharacterClassEscape(e);if(i)return i;e.pos=t}return null},Z.regexp_eatClassStringDisjunction=function(e){var t=e.pos;if(e.eatChars([92,113])){if(e.eat(123)){var n=this.regexp_classStringDisjunctionContents(e);if(e.eat(125))return n}else e.raise(`Invalid escape`);e.pos=t}return null},Z.regexp_classStringDisjunctionContents=function(e){for(var t=this.regexp_classString(e);e.eat(124);)this.regexp_classString(e)===Lw&&(t=Lw);return t},Z.regexp_classString=function(e){for(var t=0;this.regexp_eatClassSetCharacter(e);)t++;return t===1?Iw:Lw},Z.regexp_eatClassSetCharacter=function(e){var t=e.pos;if(e.eat(92))return this.regexp_eatCharacterEscape(e)||this.regexp_eatClassSetReservedPunctuator(e)?!0:e.eat(98)?(e.lastIntValue=8,!0):(e.pos=t,!1);var n=e.current();return n<0||n===e.lookahead()&&Vw(n)||Hw(n)?!1:(e.advance(),e.lastIntValue=n,!0)};function Vw(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 Hw(e){return e===40||e===41||e===45||e===47||e>=91&&e<=93||e>=123&&e<=125}Z.regexp_eatClassSetReservedPunctuator=function(e){var t=e.current();return Uw(t)?(e.lastIntValue=t,e.advance(),!0):!1};function Uw(e){return e===33||e===35||e===37||e===38||e===44||e===45||e>=58&&e<=62||e===64||e===96||e===126}Z.regexp_eatClassControlLetter=function(e){var t=e.current();return Ww(t)||t===95?(e.lastIntValue=t%32,e.advance(),!0):!1},Z.regexp_eatHexEscapeSequence=function(e){var t=e.pos;if(e.eat(120)){if(this.regexp_eatFixedHexDigits(e,2))return!0;e.switchU&&e.raise(`Invalid escape`),e.pos=t}return!1},Z.regexp_eatDecimalDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;Ww(n=e.current());)e.lastIntValue=10*e.lastIntValue+(n-48),e.advance();return e.pos!==t};function Ww(e){return e>=48&&e<=57}Z.regexp_eatHexDigits=function(e){var t=e.pos,n=0;for(e.lastIntValue=0;Gw(n=e.current());)e.lastIntValue=16*e.lastIntValue+Kw(n),e.advance();return e.pos!==t};function Gw(e){return e>=48&&e<=57||e>=65&&e<=70||e>=97&&e<=102}function Kw(e){return e>=65&&e<=70?10+(e-65):e>=97&&e<=102?10+(e-97):e-48}Z.regexp_eatLegacyOctalEscapeSequence=function(e){if(this.regexp_eatOctalDigit(e)){var t=e.lastIntValue;if(this.regexp_eatOctalDigit(e)){var n=e.lastIntValue;e.lastIntValue=t<=3&&this.regexp_eatOctalDigit(e)?t*64+n*8+e.lastIntValue:t*8+n}else e.lastIntValue=t;return!0}return!1},Z.regexp_eatOctalDigit=function(e){var t=e.current();return qw(t)?(e.lastIntValue=t-48,e.advance(),!0):(e.lastIntValue=0,!1)};function qw(e){return e>=48&&e<=55}Z.regexp_eatFixedHexDigits=function(e,t){var n=e.pos;e.lastIntValue=0;for(var r=0;r<t;++r){var i=e.current();if(!Gw(i))return e.pos=n,!1;e.lastIntValue=16*e.lastIntValue+Kw(i),e.advance()}return!0};var Jw=function(e){this.type=e.type,this.value=e.value,this.start=e.start,this.end=e.end,e.options.locations&&(this.loc=new lC(e,e.startLoc,e.endLoc)),e.options.ranges&&(this.range=[e.start,e.end])},Q=PC.prototype;Q.next=function(e){!e&&this.type.keyword&&this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword `+this.type.keyword),this.options.onToken&&this.options.onToken(new Jw(this)),this.lastTokEnd=this.end,this.lastTokStart=this.start,this.lastTokEndLoc=this.endLoc,this.lastTokStartLoc=this.startLoc,this.nextToken()},Q.getToken=function(){return this.next(),new Jw(this)},typeof Symbol<`u`&&(Q[Symbol.iterator]=function(){var e=this;return{next:function(){var t=e.getToken();return{done:t.type===J.eof,value:t}}}}),Q.nextToken=function(){var e=this.curContext();if((!e||!e.preserveSpace)&&this.skipSpace(),this.start=this.pos,this.options.locations&&(this.startLoc=this.curPosition()),this.pos>=this.input.length)return this.finishToken(J.eof);if(e.override)return e.override(this);this.readToken(this.fullCharCodeAtPos())},Q.readToken=function(e){return BS(e,this.options.ecmaVersion>=6)||e===92?this.readWord():this.getTokenFromCode(e)},Q.fullCharCodeAt=function(e){var t=this.input.charCodeAt(e);if(t<=55295||t>=56320)return t;var n=this.input.charCodeAt(e+1);return n<=56319||n>=57344?t:(t<<10)+n-56613888},Q.fullCharCodeAtPos=function(){return this.fullCharCodeAt(this.pos)},Q.skipBlockComment=function(){var e=this.options.onComment&&this.curPosition(),t=this.pos,n=this.input.indexOf(`*/`,this.pos+=2);if(n===-1&&this.raise(this.pos-2,`Unterminated comment`),this.pos=n+2,this.options.locations)for(var r=void 0,i=t;(r=XS(this.input,i,this.pos))>-1;)++this.curLine,i=this.lineStart=r;this.options.onComment&&this.options.onComment(!0,this.input.slice(t+2,n),t,this.pos,e,this.curPosition())},Q.skipLineComment=function(e){for(var t=this.pos,n=this.options.onComment&&this.curPosition(),r=this.input.charCodeAt(this.pos+=e);this.pos<this.input.length&&!YS(r);)r=this.input.charCodeAt(++this.pos);this.options.onComment&&this.options.onComment(!1,this.input.slice(t+e,this.pos),t,this.pos,n,this.curPosition())},Q.skipSpace=function(){loop:for(;this.pos<this.input.length;){var e=this.input.charCodeAt(this.pos);switch(e){case 32:case 160:++this.pos;break;case 13:this.input.charCodeAt(this.pos+1)===10&&++this.pos;case 10:case 8232:case 8233:++this.pos,this.options.locations&&(++this.curLine,this.lineStart=this.pos);break;case 47:switch(this.input.charCodeAt(this.pos+1)){case 42:this.skipBlockComment();break;case 47:this.skipLineComment(2);break;default:break loop}break;default:if(e>8&&e<14||e>=5760&&ZS.test(String.fromCharCode(e)))++this.pos;else break loop}}},Q.finishToken=function(e,t){this.end=this.pos,this.options.locations&&(this.endLoc=this.curPosition());var n=this.type;this.type=e,this.value=t,this.updateContext(n)},Q.readToken_dot=function(){var e=this.input.charCodeAt(this.pos+1);if(e>=48&&e<=57)return this.readNumber(!0);var t=this.input.charCodeAt(this.pos+2);return this.options.ecmaVersion>=6&&e===46&&t===46?(this.pos+=3,this.finishToken(J.ellipsis)):(++this.pos,this.finishToken(J.dot))},Q.readToken_slash=function(){var e=this.input.charCodeAt(this.pos+1);return this.exprAllowed?(++this.pos,this.readRegexp()):e===61?this.finishOp(J.assign,2):this.finishOp(J.slash,1)},Q.readToken_mult_modulo_exp=function(e){var t=this.input.charCodeAt(this.pos+1),n=1,r=e===42?J.star:J.modulo;return this.options.ecmaVersion>=7&&e===42&&t===42&&(++n,r=J.starstar,t=this.input.charCodeAt(this.pos+2)),t===61?this.finishOp(J.assign,n+1):this.finishOp(r,n)},Q.readToken_pipe_amp=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?this.options.ecmaVersion>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(e===124?J.logicalOR:J.logicalAND,2):t===61?this.finishOp(J.assign,2):this.finishOp(e===124?J.bitwiseOR:J.bitwiseAND,1)},Q.readToken_caret=function(){return this.input.charCodeAt(this.pos+1)===61?this.finishOp(J.assign,2):this.finishOp(J.bitwiseXOR,1)},Q.readToken_plus_min=function(e){var t=this.input.charCodeAt(this.pos+1);return t===e?t===45&&!this.inModule&&this.input.charCodeAt(this.pos+2)===62&&(this.lastTokEnd===0||qS.test(this.input.slice(this.lastTokEnd,this.pos)))?(this.skipLineComment(3),this.skipSpace(),this.nextToken()):this.finishOp(J.incDec,2):t===61?this.finishOp(J.assign,2):this.finishOp(J.plusMin,1)},Q.readToken_lt_gt=function(e){var t=this.input.charCodeAt(this.pos+1),n=1;return t===e?(n=e===62&&this.input.charCodeAt(this.pos+2)===62?3:2,this.input.charCodeAt(this.pos+n)===61?this.finishOp(J.assign,n+1):this.finishOp(J.bitShift,n)):t===33&&e===60&&!this.inModule&&this.input.charCodeAt(this.pos+2)===45&&this.input.charCodeAt(this.pos+3)===45?(this.skipLineComment(4),this.skipSpace(),this.nextToken()):(t===61&&(n=2),this.finishOp(J.relational,n))},Q.readToken_eq_excl=function(e){var t=this.input.charCodeAt(this.pos+1);return t===61?this.finishOp(J.equality,this.input.charCodeAt(this.pos+2)===61?3:2):e===61&&t===62&&this.options.ecmaVersion>=6?(this.pos+=2,this.finishToken(J.arrow)):this.finishOp(e===61?J.eq:J.prefix,1)},Q.readToken_question=function(){var e=this.options.ecmaVersion;if(e>=11){var t=this.input.charCodeAt(this.pos+1);if(t===46){var n=this.input.charCodeAt(this.pos+2);if(n<48||n>57)return this.finishOp(J.questionDot,2)}if(t===63)return e>=12&&this.input.charCodeAt(this.pos+2)===61?this.finishOp(J.assign,3):this.finishOp(J.coalesce,2)}return this.finishOp(J.question,1)},Q.readToken_numberSign=function(){var e=this.options.ecmaVersion,t=35;if(e>=13&&(++this.pos,t=this.fullCharCodeAtPos(),BS(t,!0)||t===92))return this.finishToken(J.privateId,this.readWord1());this.raise(this.pos,`Unexpected character '`+oC(t)+`'`)},Q.getTokenFromCode=function(e){switch(e){case 46:return this.readToken_dot();case 40:return++this.pos,this.finishToken(J.parenL);case 41:return++this.pos,this.finishToken(J.parenR);case 59:return++this.pos,this.finishToken(J.semi);case 44:return++this.pos,this.finishToken(J.comma);case 91:return++this.pos,this.finishToken(J.bracketL);case 93:return++this.pos,this.finishToken(J.bracketR);case 123:return++this.pos,this.finishToken(J.braceL);case 125:return++this.pos,this.finishToken(J.braceR);case 58:return++this.pos,this.finishToken(J.colon);case 96:if(this.options.ecmaVersion<6)break;return++this.pos,this.finishToken(J.backQuote);case 48:var t=this.input.charCodeAt(this.pos+1);if(t===120||t===88)return this.readRadixNumber(16);if(this.options.ecmaVersion>=6){if(t===111||t===79)return this.readRadixNumber(8);if(t===98||t===66)return this.readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.readNumber(!1);case 34:case 39:return this.readString(e);case 47:return this.readToken_slash();case 37:case 42:return this.readToken_mult_modulo_exp(e);case 124:case 38:return this.readToken_pipe_amp(e);case 94:return this.readToken_caret();case 43:case 45:return this.readToken_plus_min(e);case 60:case 62:return this.readToken_lt_gt(e);case 61:case 33:return this.readToken_eq_excl(e);case 63:return this.readToken_question();case 126:return this.finishOp(J.prefix,1);case 35:return this.readToken_numberSign()}this.raise(this.pos,`Unexpected character '`+oC(e)+`'`)},Q.finishOp=function(e,t){var n=this.input.slice(this.pos,this.pos+t);return this.pos+=t,this.finishToken(e,n)},Q.readRegexp=function(){for(var e,t,n=this.pos;;){this.pos>=this.input.length&&this.raise(n,`Unterminated regular expression`);var r=this.input.charAt(this.pos);if(qS.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 Dw(this);s.reset(n,i,o),this.validateRegExpFlags(s),this.validateRegExpPattern(s);var c=null;try{c=new RegExp(i,o)}catch{}return this.finishToken(J.regexp,{pattern:i,flags:o,value:c})},Q.readInt=function(e,t,n){for(var r=this.options.ecmaVersion>=12&&t===void 0,i=n&&this.input.charCodeAt(this.pos)===48,a=this.pos,o=0,s=0,c=0,l=t??1/0;c<l;++c,++this.pos){var u=this.input.charCodeAt(this.pos),d=void 0;if(r&&u===95){i&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed in legacy octal numeric literals`),s===95&&this.raiseRecoverable(this.pos,`Numeric separator must be exactly one underscore`),c===0&&this.raiseRecoverable(this.pos,`Numeric separator is not allowed at the first of digits`),s=u;continue}if(d=u>=97?u-97+10:u>=65?u-65+10:u>=48&&u<=57?u-48:1/0,d>=e)break;s=u,o=o*e+d}return r&&s===95&&this.raiseRecoverable(this.pos-1,`Numeric separator is not allowed at the last of digits`),this.pos===a||t!=null&&this.pos-a!==t?null:o};function Yw(e,t){return t?parseInt(e,8):parseFloat(e.replace(/_/g,``))}function Xw(e){return typeof BigInt==`function`?BigInt(e.replace(/_/g,``)):null}Q.readRadixNumber=function(e){var t=this.pos;this.pos+=2;var n=this.readInt(e);return n??this.raise(this.start+2,`Expected number in radix `+e),this.options.ecmaVersion>=11&&this.input.charCodeAt(this.pos)===110?(n=Xw(this.input.slice(t,this.pos)),++this.pos):BS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,n)},Q.readNumber=function(e){var t=this.pos;!e&&this.readInt(10,void 0,!0)===null&&this.raise(t,`Invalid number`);var n=this.pos-t>=2&&this.input.charCodeAt(t)===48;n&&this.strict&&this.raise(t,`Invalid number`);var r=this.input.charCodeAt(this.pos);if(!n&&!e&&this.options.ecmaVersion>=11&&r===110){var i=Xw(this.input.slice(t,this.pos));return++this.pos,BS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`),this.finishToken(J.num,i)}n&&/[89]/.test(this.input.slice(t,this.pos))&&(n=!1),r===46&&!n&&(++this.pos,this.readInt(10),r=this.input.charCodeAt(this.pos)),(r===69||r===101)&&!n&&(r=this.input.charCodeAt(++this.pos),(r===43||r===45)&&++this.pos,this.readInt(10)===null&&this.raise(t,`Invalid number`)),BS(this.fullCharCodeAtPos())&&this.raise(this.pos,`Identifier directly after number`);var a=Yw(this.input.slice(t,this.pos),n);return this.finishToken(J.num,a)},Q.readCodePoint=function(){var e=this.input.charCodeAt(this.pos),t;if(e===123){this.options.ecmaVersion<6&&this.unexpected();var n=++this.pos;t=this.readHexChar(this.input.indexOf(`}`,this.pos)-this.pos),++this.pos,t>1114111&&this.invalidStringToken(n,`Code point out of bounds`)}else t=this.readHexChar(4);return t},Q.readString=function(e){for(var t=``,n=++this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated string constant`);var r=this.input.charCodeAt(this.pos);if(r===e)break;r===92?(t+=this.input.slice(n,this.pos),t+=this.readEscapedChar(!1),n=this.pos):r===8232||r===8233?(this.options.ecmaVersion<10&&this.raise(this.start,`Unterminated string constant`),++this.pos,this.options.locations&&(this.curLine++,this.lineStart=this.pos)):(YS(r)&&this.raise(this.start,`Unterminated string constant`),++this.pos)}return t+=this.input.slice(n,this.pos++),this.finishToken(J.string,t)};var Zw={};Q.tryReadTemplateToken=function(){this.inTemplateElement=!0;try{this.readTmplToken()}catch(e){if(e===Zw)this.readInvalidTemplateToken();else throw e}this.inTemplateElement=!1},Q.invalidStringToken=function(e,t){if(this.inTemplateElement&&this.options.ecmaVersion>=9)throw Zw;this.raise(e,t)},Q.readTmplToken=function(){for(var e=``,t=this.pos;;){this.pos>=this.input.length&&this.raise(this.start,`Unterminated template`);var n=this.input.charCodeAt(this.pos);if(n===96||n===36&&this.input.charCodeAt(this.pos+1)===123)return this.pos===this.start&&(this.type===J.template||this.type===J.invalidTemplate)?n===36?(this.pos+=2,this.finishToken(J.dollarBraceL)):(++this.pos,this.finishToken(J.backQuote)):(e+=this.input.slice(t,this.pos),this.finishToken(J.template,e));if(n===92)e+=this.input.slice(t,this.pos),e+=this.readEscapedChar(!0),t=this.pos;else if(YS(n)){switch(e+=this.input.slice(t,this.pos),++this.pos,n){case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:e+=`
15
- `;break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},Q.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case`\\`:++this.pos;break;case`$`:if(this.input[this.pos+1]!==`{`)break;case"`":return this.finishToken(J.invalidTemplate,this.input.slice(this.start,this.pos));case`\r`:this.input[this.pos+1]===`
16
- `&&++this.pos;case`
17
- `:case`\u2028`:case`\u2029`:++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,`Unterminated template`)},Q.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
18
- `;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return oC(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 YS(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},Q.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},Q.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(VS(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?BS:VS)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=oC(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},Q.readWord=function(){var e=this.readWord1(),t=J.name;return this.keywords.test(e)&&(t=KS[e]),this.finishToken(t,e)},PC.acorn={Parser:PC,version:`8.18.0`,defaultOptions:dC,Position:cC,SourceLocation:lC,getLineInfo:uC,Node:rw,TokenType:HS,tokTypes:J,keywordTypes:KS,TokContext:JC,tokContexts:YC,isIdentifierChar:VS,isIdentifierStart:BS,Token:Jw,isNewLine:YS,lineBreak:qS,lineBreakG:JS,nonASCIIwhitespace:ZS};function Qw(e,t){return PC.parse(e,t)}C(()=>Kt(`ok`,[Vt({ok:Lr(!0),value:lt()}),Vt({ok:Lr(!1),error:Vt({kind:Lr(`guest_threw`),name:T().max(80),message:T().max(512),transportMessage:T().max(512).optional()})})]));var $w=C(()=>T().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),eT=$w.refine(e=>{if(e===`env`)return!1;try{return Qw(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);C(()=>Cn(eT,pn($w).min(1))),C(()=>Cn(eT,pn(T().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var tT=R([`read`,`write`]),nT=nm,rT=F({access:j(tT),confirm:j(nT)}),iT=R([`none`,`read`,`write`]),aT=O(rT),oT=O(iT);function sT(e){let t=aT({access:e.access,confirm:e.confirm});if(pe(t))throw new K(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function cT(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 lT(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:cT(e,t)})}function uT(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=oT(i[n]);return Ae(a)?a.success:`none`}async function dT(e,t,n,r,i){let a=await fT(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function fT(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=pT(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?lT(`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(),pT(e,t,n)):lT(`declined`,n)}function pT(e,t,n){let r=uT(e,t,n.module);if(r===`none`)return lT(`not-granted`,n);if(r===`read`&&n.access!==`read`)return lT(`read-only`,n)}function mT(e,t,n){let r={module:e.module,operation:e.descriptor.name,...sT(e)};return{...e,prepare:i=>si({try:e=>dT(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(E(t=>t===void 0?e.prepare(i):b({execute:()=>zv({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var hT=_s();async function gT(e){let t=await Tr(e);if(ra(t))return{value:t.value};let n=Gi(t.cause);if(pe(n))throw Wi(t.cause);return{issues:hT(n.success.issue).issues}}function _T(e){let t=Wh(e),n=Pp(t)[`~standard`].jsonSchema,r=Ip(t),i=Vp(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>gT(r(e)),encode:e=>gT(i(e))})}function vT(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function yT(e){return Jp(e)?_T(e):vT(e)}var bT=Symbol(`mycelium.operation`),xT=Symbol(`mycelium.module`),ST=new WeakMap,CT=new WeakMap;function wT(e){let t=Object.freeze({[bT]:!0}),n=yT(e.input),r=e.output===void 0?void 0:yT(e.output),i={replay:e.replay??`unsafe`,...sT(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new eS(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 lS({reason:`Capability output failed its declared schema`,rawCause:new tS(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 ST.set(t,a),t}function TT(e){let t=pn($w).safeParse(e.namespace??[]);if(!t.success)throw new K(`Invalid module namespace`);let n=Object.freeze({[xT]:!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 CT.set(n,i),n}function ET(e){return CT.has(e)}function DT(e){return ST.get(e)}function OT(e){return CT.get(e)}function kT(e,t,n){let r=OT(e);if(r===void 0)throw new K(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(ET(a)){let n=OT(a);if(n===void 0)throw new K(`Unknown child module registration`);i[e]=kT(a,t,[r,...n.namespace].join(`.`));continue}let o=DT(a);if(o===void 0)throw new K(`Unknown operation registration: ${e}`);let s=Object.freeze({[bT]:!0});ST.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 AT(TT(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 AT(e,t){let n=OT(e);if(n===void 0)throw new K(`Unknown module registration`);let r=Object.freeze({[xT]:!0});return CT.set(r,Object.freeze({...n,grantKey:t})),r}function jT(e,t){if(t.length===0||t.length>160)throw new K(`Grant key must be non-empty and bounded`);return AT(e,t)}function MT(e,t){return kT(e,t,``)}function NT(e,t){return e<t?-1:+(e>t)}function PT(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var FT=160;function IT(e){if(e.length===0||e.length>FT)throw new K(`Module id must be non-empty and bounded`)}function LT(e){if(!e.split(`.`).every(e=>$w.safeParse(e).success))throw new K(`Operation key must be a path segment or a dotted relative path`)}function RT(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function zT(e){let t=RT(e);return eT.safeParse(t).success?t:`module_${t}`}function BT(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`?RT(i.name):zT(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 VT=14695981039346656037n,HT=1099511628211n,UT=18446744073709551615n;function WT(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*HT&UT,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*HT&UT,n=(n^BigInt(r>>>8&255))*HT&UT}return n}function GT(e,t,n){let r=WT(VT,e),i=[...t.entries()].sort(([e],[t])=>NT(e,t));for(let[e,t]of i)r=WT(r,e),r=WT(r,t);let a=[...n].sort((e,t)=>NT(e.id,t.id));for(let e of a)r=WT(r,e.id),r=WT(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function KT(){return[qx,Kx,Jx]}function qT(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(LT(t),ET(o)){let s=OT(o);if(s===void 0)throw new K(`Unknown child module registration`);return qT(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=DT(o);if(s===void 0)throw new K(`Unknown operation registration: ${[...r,t].join(`.`)}`);return[Object.freeze({grantKey:e,path:[...r,t].join(`.`),namespace:n,name:[...a,t].join(`.`),moduleDescription:i,operation:s})]})}function JT(e,t=[]){let n=e.map(e=>{let t=OT(e);if(t===void 0)throw new K(`Unknown module registration`);return IT(t.id),t}).sort((e,t)=>NT(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new K(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=BT(n,`transport`),a=BT(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new K(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new K(`Missing logical alias: ${e.id}`);return[t,Object.freeze([...e.namespace,n])]}))),s=n.flatMap(e=>{let t=i.get(e.id);if(t===void 0)throw new K(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new K(`Missing namespace path: ${e.id}`);return qT(e.grantKey,e,t,n,e.description)}).sort((e,t)=>NT(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new K(`Duplicate operation path`);for(let e of KT()){if(c.has(e.path))throw new K(`Reserved intrinsic path: ${e.path}`);c.add(e.path)}for(let e of c){let t=e.split(`.`);for(let n=1;n<t.length;n+=1)if(c.has(t.slice(0,n).join(`.`)))throw new K(`Operation conflicts with namespace: ${e}`)}let l;try{l=Hx({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}),...KT()]})}catch(e){throw new K(PT(e))}let u=GT(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 YT(){return null}var XT=nn(),ZT=C(()=>Qr([Lt(),T(),xr(),dr()])),QT=C(()=>Cn(T(),lt())),$T=C(()=>DS.extend({timeoutMs:dr().int().min(1).max(9e5).optional(),abortGraceMs:dr().int().min(1).max(3e4).optional()}).optional()),eE=64,tE=262144,nE=new TextEncoder,rE=e=>{e(b(void 0))};function iE(e){let t=$T.safeParse(e);if(!t.success)throw new K(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...OS({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function aE(e){return S(function*(){let t=yield*w_(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=Kn(t=>e===0?(t(b(void 0)),w(()=>void 0)):(n.add(t),w(()=>n.delete(t))));return Object.freeze({start:r=>ft(i=>w(()=>{e+=1}).pipe(y(te(i(t.withPermits(1)(r)).pipe(Xn(w(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(rE)}}))))))),awaitIdle:r})}})})}function oE(e,t=0){if(t>eE)throw Error(`JSON value exceeds the nesting bound`);let n=ZT.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>oE(e,t+1));let r=QT.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,oE(n,t+1)]))}function sE(e){return XT.parse(oE(e))}function cE(e){let t=JSON.stringify(sE(e)),n=nE.encode(t).byteLength;if(n>tE)throw new uS({size:n});return Object.freeze({text:t})}function lE(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 sE(await r(i))}catch(t){throw vS(t)?t:t instanceof qb?new fS({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof eS?new fS({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${we({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function uE(e){return Kn(t=>{let n=t.bind(void 0,h);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),w(e.removeEventListener.bind(e,`abort`,n))})}function dE(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 fE(e,t,n){return e===`deadline_exceeded`?new iS({limitMs:t,elapsedMs:n??0}):new oS({by:`caller`})}function pE(e){return Ea.pipe(be(t=>t-e))}function mE(t){return Ea.pipe(E(n=>hr(()=>{let r=t.executionId,i=new AbortController,a=n,o={kind:`waiting`},s,c=e=>{s===void 0&&o.kind!==`refused`&&(s=e,i.abort())},l=e=>{let n=new aS({capacity:t.policy.capacity,waitedMs:Math.max(0,e-a)});return o={kind:`refused`,failure:n},n},u=()=>{if(i.signal.aborted)throw fE(s,t.policy.timeoutMs)},d=dE(t.callerSignal,()=>{c(`cancelled`)}),f=n+t.policy.timeoutMs,p={executionId:r,deadlineAt:f,signal:i.signal,images:t.images};t.toolCallId!==void 0&&Object.assign(p,{toolCallId:t.toolCallId}),t.output!==void 0&&Object.assign(p,{output:t.output});let m=Object.freeze(p),ee=hr(()=>Ea.pipe(E(e=>o.kind===`refused`?x(o.failure):(e>=f&&c(`deadline_exceeded`),i.signal.aborted?pE(n).pipe(E(e=>x(fE(s,t.policy.timeoutMs,e)))):e>=a+t.policy.waitMs?x(l(e)):(o={kind:`admitted`},t.sandbox.execute(Object.freeze({executionId:r,code:t.code,timeoutMs:t.policy.timeoutMs,bindings:lE(t.createBindings(m),u),modules:t.modules,namespacePaths:t.namespacePaths,sessionId:t.sessionId}),i.signal).pipe(Ir(e=>Hi(e)?Bt(e):x(yS(Wi(e)))))))))),te=e=>g_(e).pipe(Gr({duration:t.policy.abortGraceMs,orElse:()=>x(s===`deadline_exceeded`?new iS({limitMs:t.policy.timeoutMs,elapsedMs:t.policy.timeoutMs,acknowledged:!1}):new oS({by:`caller`,acknowledged:!1}))})),g,ne=!1,re=e=>(ne=!0,pE(n).pipe(E(n=>{let i=yS(e),a=i instanceof iS?new iS({limitMs:i.limitMs,elapsedMs:n,acknowledged:i.acknowledged}):i,o=mS(a,r),s=Cn(T(),nn()).parse(xS(a));s.ref=r;let c={kind:`sandbox_failure`,ref:r,executionId:r,adapter:t.sandbox.adapter??`effect`,buildSha:t.sandbox.buildSha??YT(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=hr(()=>t.sandbox.onFailure?.(c)??h);return Xe(`sandbox_failure`,c).pipe(or({executionId:r,ref:r,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),y(o._tag===`Unknown`?oo(so(ao(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(y(Xe(`sandbox_health_alert`).pipe(or({ref:r,adapter:c.adapter})))):h),y(l.pipe(Ir(e=>Xe(`sandbox_failure_record_failed`,e)))),Er(o))})));return S(function*(){if(i.signal.aborted){let e=yield*pE(n);return yield*x(fE(s,t.policy.timeoutMs,e))}a=yield*Ea,g=yield*t.backingWork.start(ee);let r=yield*Ea,u=fn(Math.max(0,a+t.policy.waitMs-r)).pipe(y(Ea),E(e=>o.kind===`admitted`?Tt:o.kind===`refused`?b({kind:`busy`,failure:o.failure}):i.signal.aborted?b({kind:`cancelled`}):e>=f?(c(`deadline_exceeded`),b({kind:`deadline`})):b({kind:`busy`,failure:l(e)}))),d=yield*e(m_(g).pipe(be(e=>Object.freeze({kind:`settled`,exit:e}))),e(fn(Math.max(0,f-r)).pipe(y(w(()=>(c(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),e(uE(i.signal).pipe(Er(Object.freeze({kind:`cancelled`}))),u))),p=o.kind===`refused`?o.failure:d.kind===`busy`?d.failure:void 0;if(p!==void 0)return yield*te(g).pipe(y(x(p)));if(d.kind===`settled`)return yield*ge(d.exit,{onFailure:e=>s===void 0?Bt(e):pE(n).pipe(E(e=>x(fE(s,t.policy.timeoutMs,e)))),onSuccess:e=>en({try:()=>cE(e),catch:t=>vS(t)?t:new dS({kind:bS(e),rawCause:t})})});d.kind===`deadline`&&c(`deadline_exceeded`);let m=yield*pE(n);return yield*te(g).pipe(y(x(fE(s,t.policy.timeoutMs,m))))}).pipe(Ce(()=>(c(`cancelled`),(g===void 0?h:g_(g).pipe(Gt(t.policy.abortGraceMs),tn)).pipe(y(hr(()=>ne?h:re(new oS({by:`operator`})).pipe(tn))))))).pipe(cn(e=>re(e).pipe(E(x))),Xn(w(d)))})))}var hE=pm(()=>L([tm,em,nm,P,N,Nh,wm(AbortSignal),I(hE),gE])),gE=om(N,hE);function _E(e){return k(gE)(e)}var vE=om(N,Gh),yE=k(F({samplingParams:A(vE),samplingParamsByThinkingLevel:A(F({off:A(vE),minimal:A(vE),low:A(vE),medium:A(vE),high:A(vE),xhigh:A(vE),max:A(vE)}))}));function bE(e){return{...e,...yE(e)}}function xE(e){if(e===void 0)return;let{onPayload:t,onProviderStreamEvent:n,onResponse:r,...i}=e,a={...i};return t!==void 0&&(a.onPayload=(e,n)=>t(_E(e),bE(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(_E(e),bE(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,bE(t))),a}var SE=async(e,t,n)=>{let{streamSimple:r}=await fi(async()=>{let{streamSimple:e}=await import(`./compat-tatm8WJ0.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,22]));return r(e,di(t),xE(n))},CE=F({error:F({code:j(N),type:j(N)})});Rp(F({type:M(`response.failed`),response:CE})),Rp(W(CE)),Rp(F({type:M(`error`),status:j(P.check(Ym(),qm({minimum:100,maximum:599}))),code:j(N),error:j(CE.fields.error)})),k(wm(Uint8Array)),Rp(kh.check(qm({minimum:0,maximum:60}))),Rp(kh.check(Ym(),qm({minimum:0,maximum:864e10}))),Rp(R([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Rp(M(`rejected`)),Rp(M(`0`)),Rp(Bh),Rp(F({type:M(`error`),error:F({type:M(`overloaded_error`)})}));var wE=[/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],TE=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,EE=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function DE(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!EE.some(t=>t.test(e.errorMessage))&&(wE.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&TE.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 OE(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function kE(e){return new RegExp(e.join(`|`),`i`)}var AE=kE([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`]),jE=kE(`overloaded,server_busy,servers are currently busy,currently experiencing high demand,model is at capacity,rate.?limit,too many requests,429,500,502,503,504,520,524,service.?(?:is.?)?(?:temporarily.?)?unavailable,server.?error,internal.?error,provider.?returned.?(?:an.?)?error,exceeded request buffer limit while retrying upstream,unable to forward upstream,network.?error,connection.?error,connection.?refused,connection.?lost,other side closed,fetch failed,getaddrinfo,ENOTFOUND,EAI_AGAIN,upstream.?connect,reset before headers,socket hang up,socket connection was closed,timed? out,timeout,terminated,websocket.?closed,websocket.?error,ended without,stream ended before message_stop,stream ended before a terminal response event,http2 request did not get a response,pending stream has been canceled,retry delay,you can retry your request,try your request again,please retry your request,ResourceExhausted,subscription_sharing_usage_unavailable,subscription_sharing_user_unavailable`.split(`,`)),ME=6e4;function NE(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 PE=class extends Error{constructor(){super(`Aborted`)}};function FE(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new PE);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new PE)},{once:!0})})}async function IE(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||!LE(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=NE(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await FE(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof PE){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function LE(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!AE.test(t)&&jE.test(t)}var RE={assign:0,create:0,clone:0,discard:0,update:0};function zE(e){return VE(e,null)}function BE(e){return VE(typeof e,`object`)&&!zE(e)}function VE(e,t){return e===t}function HE(e){return VE(e,`__proto__`)||VE(e,`constructor`)||VE(e,`prototype`)}function UE(e,t){return HE(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function WE(e){return Object.getOwnPropertyNames(e)}var GE={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function KE(){return GE}function qE(e){return KE().immutableTypes?Object.freeze(e):e}function JE(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 YE(e,t){return{...e,...t}}function XE(e,t,n={}){RE.create+=1;let r=YE(t,n);return qE(KE().enumerableKind?YE(r,e):JE(r,e))}function ZE(e){return BE(e)}function QE(e){return ZE(e)&&UE(e,`~optional`)}function $E(e){return WE(e).filter(t=>!QE(e[t]))}function eD(e,t={}){let n=$E(e);return XE({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var tD;(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`})(tD||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var nD=new Float64Array(1);new DataView(nD.buffer),new Uint8Array(nD.buffer),new TextEncoder;var rD=`-?(?:0|[1-9][0-9]*)`,iD=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function aD(e){return XE({"~kind":`String`},{type:`string`},e)}var oD=`^${rD}$`;`${iD}`;function sD(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var cD=[...sD(97,122),...sD(65,90)],lD=[`0`,...sD(49,57)];[...lD],[...cD,...lD],[...lD],new RegExp(oD);var uD={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},dD={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},fD=1e3,pD=Symbol(`Mule model limit`);function mD(e,t){return DE(e,t)}var hD=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),gD=(e,t)=>({kind:e,value:`mule_${e}_${ng()}`,parent:t}),_D=()=>h;function vD(e,t){let n={role:`toolResult`,toolCallId:e.id,toolName:e.name,content:t.content,isError:t.isError,timestamp:Date.now()};return t.usage!==void 0&&(n.usage=t.usage),n}var yD=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function bD(e,t){return e.find(e=>e.descriptor.name===t.name)}function xD(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function SD(e,t,n,r,i){let a=gD(`tool_call`,r);return S(function*(){if(yield*i({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:a,call:t}),e===void 0){let e=yD(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*xD(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*_n(e.prepare(t));if(pe(o)){let e=yD(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*xD(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function CD(e,t,n,r){return S(function*(){let i,a;yield*fy(Zv(e.tool.execute()),o=>pe(o)?(a=o.failure,h):i===void 0?o.success.type===`result`?(i=o.success.result,h):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):h);let o=a===void 0?i??yD(`Tool "${e.call.name}" returned no result`):yD(a.message),s={call:e.call,identity:e.identity,result:o};return yield*xD(s,t,n,r),s})}function wD(e,t,n,r){let i=vD(e.call,e.result),a=gD(`tool_result`,e.identity);return S(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:a,value:i}),yield*r({type:`message_end`,run:t,turn:n,message:a,value:i,data:e.result.data}),i})}function TD(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>bD(a,e)?.executionMode===`sequential`);return S(function*(){let t=e=>e.kind===`finalized`?b(e.value):CD(e,n,r,i),s=o?yield*Kr(e,e=>E(SD(bD(a,e),e,n,r,i),t)):yield*S(function*(){let o=yield*Kr(e,e=>SD(bD(a,e),e,n,r,i));return yield*Mn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*Kr(s,e=>wD(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var ED=e=>yD(`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 DD(e,t,n,r){return S(function*(){let i=yield*Kr(e,e=>S(function*(){let i=gD(`tool_call`,n),a={call:e,identity:i,result:ED(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*xD(a,t,n,r),a}));return yield*Kr(i,e=>wD(e,t,n,r))})}function OD(e,t){return si({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=>hD(`model`,`Pi model stream failed`,e)})}function kD(e,t,n){return e.pipe(Gr({duration:t,orElse:()=>x(hD(`model`,n(),pD))}))}function AD(e,t,n,r,i,a){let o=gD(`message`,r),s,c={started:!1,terminal:void 0};return sn(S(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??dD.firstEventMs,dD.firstEventMs),d=Math.min(l?.attemptMs??dD.attemptMs,dD.attemptMs),f=Math.min(l?.outputBytes??dD.outputBytes,dD.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*x(hD(`model`,`Model stream limits must be positive safe integers`));let p=Date.now(),m=p,ee=0,te=0,g=new TextEncoder,ne=!1,re=e=>hD(`model`,`Model ${e} after ${String(Date.now()-p)} ms (max provider gap ${String(Math.max(ee,Date.now()-m))} ms, streamed ${String(te)} bytes)`,pD),ie=t=>{let n=Date.now()-p,r=d-n,i=Math.min(ne?dD.idleMs:u,e.modelStreamIdleTimeoutMs??dD.idleMs)-(Date.now()-m),a=r<=i?`attempt timed out`:ne?`stream timed out (silence)`:`first event timed out`;return kD(t,Math.max(0,Math.min(r,i)),()=>re(a).message)},ae=new AbortController;yield*br(()=>w(()=>{ae.abort(`Mule model scope closed`)}));let oe=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,se={...e.streamOptions,maxRetries:0,signal:ae.signal};oe!==void 0&&(se.apiKey=oe);let ce=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*i({type:`model_prompt`,run:n,turn:r,attempt:a,systemPrompt:ce}));let le={systemPrompt:ce,messages:t},ue=(e.tools??[]).map(e=>e.descriptor);ue.length>0&&(le.tools=ue);let de=yield*ie(si({try:async()=>(e.stream??SE)(e.model,di(le),se),catch:e=>hD(`model`,`Pi model stream could not start`,e)})),fe=yield*jr(w(()=>de[Symbol.asyncIterator]()),e=>si({try:()=>(ae.abort(`Mule model stream closed`),new Promise(t=>{let n=setTimeout(t,fD);Promise.resolve(e.return?.()).then(()=>{clearTimeout(n),t()},()=>{clearTimeout(n),t()})})),catch:e=>hD(`model`,`Pi model stream failed`,e)}).pipe(Le)),pe=e=>{let a=Date.now();if(ee=Math.max(ee,a-m),m=a,ne=!0,(e.type===`text_delta`||e.type===`thinking_delta`||e.type===`toolcall_delta`)&&(te+=g.encode(e.delta).byteLength,te>f))return x(re(`output limit exceeded`));switch(`partial`in e&&(s=e.partial),e.type){case`start`:return t.push(e.partial),c.started=!0,i({type:`message_start`,run:n,turn:r,message:o,value:e.partial});case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:return c.started&&(t[t.length-1]=e.partial),i({type:`message_update`,run:n,turn:r,message:o,value:e.partial,event:e});case`done`:return c.terminal=e.message,h;case`error`:return c.terminal=e.error,h}},me=()=>ie(OD(fe,ae)),he=yield*me();for(;!he.done;)yield*pe(he.value),he=yield*me();let ge=c.terminal??(yield*ie(si({try:()=>de.result(),catch:e=>hD(`model`,`Pi model stream did not settle`,e)})));return c.started?t[t.length-1]=ge:(t.push(ge),yield*i({type:`message_start`,run:n,turn:r,message:o,value:ge})),yield*i({type:`message_end`,run:n,turn:r,message:o,value:ge}),{identity:o,message:ge}}).pipe(cn(l=>{if(l.cause!==pD)return x(l);let u={role:`assistant`,content:s?.content??[],api:e.model.api,provider:e.model.provider,model:e.model.id,usage:s?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,timestamp:Date.now(),errorMessage:e.retry?.enabled&&a>e.retry.maxRetries?`The model failed ${String(a)} times on this conversation: ${l.message}`:l.message};return S(function*(){return c.started?t[t.length-1]=u:(t.push(u),yield*i({type:`message_start`,run:n,turn:r,message:o,value:u})),yield*i({type:`message_end`,run:n,turn:r,message:o,value:u}),{identity:o,message:u,limitReached:!0}})})))}function jD(e,t,n,r,i){return S(function*(){let a=e.retry===void 0?void 0:{...e.retry};if(a?.enabled&&[a.maxRetries,a.baseDelayMs,a.maxAgentDelayMs??6e4].some(e=>!Number.isSafeInteger(e)||e<0))return yield*x(hD(`model`,`Retry policy requires non-negative safe-integer counts and delays`));let o,s=0,c=0,l=!1,u,d=t=>e.onRetry===void 0?h:e.onRetry(t),f=(e,t)=>S(function*(){l=!0,yield*d(t===void 0?{type:`retry_finished`,run:n,turn:r,attempt:c,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:c,success:e,finalError:t})});return yield*S(function*(){for(;;){if(o!==void 0){let e=t.indexOf(o.message);e!==-1&&t.splice(e,1)}o=yield*AD(e,t,n,r,i,++s);let l=o.message;if(l.stopReason!==`error`||a===void 0||!a.enabled||c>=a.maxRetries)return c>0&&(yield*f(l.stopReason!==`error`&&l.stopReason!==`aborted`,l.stopReason===`error`?l.errorMessage:void 0)),o;if(!(yield*en({try:()=>o?.limitReached===!0||e.retryable(l),catch:e=>hD(`model`,`Typed model retry decision failed`,e)})))return c>0&&(yield*f(!1,l.errorMessage)),o;c++,u=l.errorMessage??`Unknown error`;let p=yield*en({try:()=>e.retryAfterMs?.(l),catch:e=>hD(`model`,`Model retry delay observation failed`,e)}),m=Math.max(NE(a,c),p!==void 0&&Number.isSafeInteger(p)&&p>=0&&p<=6e4?p:0),ee=Math.min(1e3,m/4,Math.max(0,6e4-m)),h=m+Math.floor(Math.random()*ee);yield*d({type:`retry_scheduled`,run:n,turn:r,attempt:c,maxAttempts:a.maxRetries,delayMs:h,errorMessage:u}),yield*fn(h),yield*d({type:`retry_attempt_started`,run:n,turn:r,attempt:c})}}).pipe(Ce(()=>c===0||l?h:f(!1,u)))})}var MD=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function ND(e,t,n,r,i,a){return Kr(e,e=>S(function*(){let o=gD(`message`,i);t.push(e),n.push(e),yield*a({type:`message_start`,run:r,turn:i,message:o,value:e}),yield*a({type:`message_end`,run:r,turn:i,message:o,value:e})})).pipe(tn)}function PD(e,t,n,r,i,a,o){return S(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*ND(a,t,n,r,i,o);let s=yield*jD(e,t,r,i,o),c=MD(s.message)!==`completed`,l=s.message.content.filter(e=>e.type===`toolCall`),u=l.length===0||c?{messages:[],terminate:!1}:s.message.stopReason===`length`?{messages:yield*DD(l,r,i,o),terminate:!1}:yield*TD(l,e,r,i,o);t.push(...u.messages),n.push(s.message,...u.messages),yield*o({type:`turn_end`,run:r,turn:i,message:s.message,toolResults:u.messages});let d={message:s.message,toolResults:u.messages,terminate:u.terminate};return s.limitReached&&s.message.errorMessage!==void 0?{...d,modelLimitReason:s.message.errorMessage}:d})}function FD(e,t,n,r,i,a){let o=gD(`turn`,i);return S(function*(){if(MD(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*Kr(t.tools,n=>S(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=bD(e.tools??[],n.call),s;if(t.message.stopReason!==`length`&&(n.state===`pending`||n.state===`started`&&n.replay===`safe`&&r?.replay===`safe`)){let e=yield*SD(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*CD(e,i,o,a)}else s={call:n.call,identity:gD(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?ED(n.call):yD(`Interrupted by a restart; it may or may not have completed; check before retrying.`)},yield*a({type:`tool_execution_start`,replay:`unsafe`,run:i,turn:o,toolCall:s.identity,call:s.call}),yield*xD(s,i,o,a);return{message:yield*wD(s,i,o,a),terminate:s.result.terminate===!0,recorded:!1}})),c=s.filter(({recorded:e})=>!e).map(({message:e})=>e);return n.push(...c),r.push(...c),{message:t.message,toolResults:s.map(({message:e})=>e),terminate:s.length>0&&s.every(({terminate:e})=>e)}})}function ID(e,t,n,r){return S(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 LD(e,t,n,r,i,a,o){return S(function*(){yield*a({type:`run_end`,run:e,terminal:t,outcome:i});let s={status:i,run:e,terminal:t,message:n,messages:r};return o===void 0?s:{...s,modelLimitReason:o}})}function RD(e,t=_D){return S(function*(){let n=yield*w_(1),r={started:!1,ended:!1},i=e=>hr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(jn(()=>w(()=>{e.type===`run_start`&&(r.started=!0)}))),a=gD(`run`),o=gD(`terminal`,a);return yield*BD(e,i,a,o).pipe(Oe(e=>{let t=zD(e);return!r.started||r.ended||t===void 0?h:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Le)}))})}function zD(e){if(ra(e))return;if(Hi(e.cause))return`cancelled`;let t=Ki(e.cause);if(!(Fn(t)&&t.value.phase===`listener`))return`failed`}function BD(e,t,n,r){return S(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*FD(e,e.resume,i,a,n,t),c=MD(s.message),l=c===`completed`?yield*ID(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*LD(n,r,s.message,a,c,t);o.push(...l.pending)}do{let l=yield*PD(e,i,a,n,gD(`turn`,n),o,t);s=l.message;let u=MD(l.message);if(u!==`completed`)return yield*LD(n,r,l.message,a,u,t,l.modelLimitReason);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*ID(e,l,i,a);o=[...d.pending],c=d.continue}while(c);return yield*LD(n,r,s,a,`completed`,t)})}var VD={run:RD},HD=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 fS({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)}},UD=8192,WD=UD*4,GD=new TextEncoder,KD=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),qD=class e{wake;#e={stdout:{decoder:KD(),pending:new Uint8Array},stderr:{decoder:KD(),pending:new Uint8Array}};#t=KD();#n=Array.from({length:UD},()=>void 0);#r=0;#i=0;#a=0;#o=0;#s=0;#c=0;#l=!1;#u=!1;constructor(e){this.wake=e}static make(){return Pg({capacity:1,strategy:`dropping`}).pipe(be(t=>new e(t)))}write(e,t){if(this.#u||t.length===0)return;let n=this.#e[e];this.#c+=t.length;for(let e=0;e<t.length;e+=WD){let r=t.subarray(e,e+WD),i=n.decoder.decode(r,{stream:!0}),a=new Uint8Array(n.pending.length+r.length);a.set(n.pending),a.set(r,n.pending.length);let o=this.#f(a);n.pending=a.slice(a.length-o),this.#h(i,a.length-o,a)}this.#l=!0,Rg(this.wake,void 0)}#d(e,t){let n=this.#t.decode(e.subarray(0,t),{stream:!0});return this.#t.decode(),n}#f(e){for(let t=1;t<=Math.min(3,e.length);t++){let n=e.subarray(e.length-t);if(this.#d(n,n.length).length===0)return t}return 0}#p(){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);this.#n[this.#r]=void 0,this.#r=(this.#r+1)%UD,this.#i--,this.#a-=e.textBytes,this.#o-=e.newlines,this.#s+=e.rawBytes}#m(e,t,n){let r=e.raw;if(r===null){this.#p();return}let i=e=>{let i=this.#d(r,e);return GD.encode(i).length>=t&&i.split(`
19
- `).length-1>=n},a=Math.min(r.length,Math.max(4,t));for(;a<r.length&&!i(a);)a=Math.min(r.length,a*2);let o=0;for(;o<a;){let e=Math.floor((o+a)/2);i(e)?a=e:o=e+1}let s=this.#d(r,o);if(s.length===e.text.length){this.#p();return}let c=o-this.#f(r.subarray(0,o)),l=GD.encode(s).length,u=s.split(`
20
- `).length-1;e.raw=r.slice(c),e.text=this.#d(e.raw,e.raw.length),e.rawBytes-=c,e.textBytes-=l,e.newlines-=u,this.#a-=l,this.#o-=u,this.#s+=c}#h(e,t,n){if(e.length===0)return;let r={text:e,raw:n,rawBytes:t,textBytes:GD.encode(e).length,newlines:e.split(`
21
- `).length-1};for(this.#i===UD&&this.#p(),this.#n[(this.#r+this.#i)%UD]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>UD||this.#o>=200;){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);let t=Math.max(0,this.#a-UD),n=Math.max(0,this.#o-199);e.textBytes<=t||e.newlines<n?this.#p():this.#m(e,t,n)}}snapshot(){let e=``;for(let t=0;t<this.#i;t++){let n=this.#n[(this.#r+t)%UD];if(n===void 0)throw Error(`Missing output ring entry`);e+=n.text}return{tail:e,droppedBytes:this.#s,totalBytes:this.#c}}#g(){if(!this.#l)return;this.#l=!1;let{tail:e,...t}=this.snapshot();return{type:`update`,result:{isError:!1,content:[{type:`text`,text:e}],data:t}}}finish(){if(!this.#u){this.#u=!0;for(let e of[this.#e.stdout,this.#e.stderr]){let t=e.decoder.decode();this.#h(t,e.pending.length,null),e.pending=new Uint8Array,t.length>0&&(this.#l=!0)}return this.#g()}}get updates(){return Gv(this.wake).pipe(Xv(()=>fn(`100 millis`).pipe(be(()=>this.#u?void 0:this.#g()))),ay(e=>e!==void 0))}dispose(){this.#u=!0,this.#n.fill(void 0),this.#r=this.#i=this.#a=this.#o=0,this.#c=this.#s=0,this.#l=!1;for(let e of[this.#e.stdout,this.#e.stderr])e.decoder.decode(),e.pending=new Uint8Array}},JD=F({code:N}),YD='Inside execute, call forage.search, forage.list or forage.describe to discover operations and inspect their inputs. forage is available only there, not as a separate tool. Run async JavaScript in the sandbox. Each call is a fresh sandbox, not a REPL: nothing survives between calls, so redefine helpers or persist state to a file. Never shadow injected module names with local bindings. Find operations with await forage.search({ query }) using one short keyword such as read or shell, or page them all with forage.list({limit:50}), optionally by namespace, until nextCursor is null. Inspect input with await forage.describe({ path }) before calling; describe known paths directly. Call an operation as await env.<path>({ ... }) with the exact dotted path, for example await env.computers.local.exec({ command: "pwd" }); a bare computers.local.exec is not defined. Put multiline shell commands in a template literal. Code is JavaScript first, so double each backslash the shell needs (`\\\\(` passes `\\(`; `\\(` becomes `(`). For file edits, prefer Files operations when available. Explicitly return the final value. Before treating a shell or process result as success, check status, exitCode and stderr.';function XD(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await dT(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function ZD(e,t,n,r){let i=0,a=new Map;for(let o of e){let e=o.namespace,s=o.name,c=a.get(e)??new Map;c.set(s,e=>XD(o,Object.freeze({...t,operationOrdinal:i++}),n,r)(e)),a.set(e,c)}return Object.freeze(Object.fromEntries([...a].map(([e,t])=>[e,Object.freeze(Object.fromEntries(t))])))}function QD(e,t){let n=e.safeParse(t);if(!n.success)throw new eS(n.error.issues);return n.data}function $D(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(QD(Lb,t))),describe:t=>Promise.resolve().then(()=>e.describe(QD(Ib,t))),search:t=>Promise.resolve().then(()=>e.search(QD(Fb,t)))})}function eO(e,t,n,r,i){return Object.freeze({...ZD(e,n,r,i),forage:$D(t)})}function tO(e,t,n,r,i,a,o,s){let c=n.execution??iE(void 0),l=new HD,u=(u,d,f,p,m)=>mE({executionId:u,toolCallId:p,output:m,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>eO(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>hr(()=>{let n=ng();return u(n,e,t).pipe(Xn(w(()=>{l.dispose(n)})))}),f=(e,t,n)=>hr(()=>{let r=ng(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(vt({onSuccess:e=>b(nO({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof uS&&t.length>0?b(nO({text:hS(e),isError:!0},t)):x(rO(e))}}),Xn(w(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:YD,parameters:eD({code:aD()},{additionalProperties:!1})},prepare:e=>Ip(JD)(e.arguments).pipe(be(({code:t})=>({execute:()=>Jv(S(function*(){let n=yield*qD.make();yield*br(()=>w(()=>{n.dispose()}));let r=yield*Vn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return iy(n.updates,jv(m_(r)).pipe(Qv(e=>{let t=n.finish();return ty(Uv(t===void 0?[]:[t]),jv(e))})),{haltStrategy:`right`}).pipe(ly(e=>e.type===`result`))}))})),it(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function nO(e,t){let n=t.map(e=>({type:`image`,data:e.data,mimeType:e.mimeType})),r=[{type:`text`,text:e.text},...n];return t.length===0?{type:`result`,result:{content:r,isError:e.isError}}:{type:`result`,result:{content:r,data:{images:t.map(e=>({bytes:e.bytes,mimeType:e.mimeType,path:e.path}))},isError:e.isError}}}function rO(e){let t={_tag:`MuleError`,phase:`tool`,message:vS(e)?hS(e):e.message};return e instanceof aS?{...t,cause:e}:t}function iO(e,t){return e<t?-1:+(e>t)}var aO=128,oO=C(()=>T().min(1).max(160)),sO=C(()=>Zn({version:T().min(1).max(160),modules:pn(lt())})),cO=1e3;function lO(e){if(e.length>aO)throw new K(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>iO(e.id,t.id)),n=new Set;for(let e of t){if(!oO.safeParse(e.id).success)throw new K(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new K(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function uO(e){if(e>cO)throw new K(`Candidate module count exceeds bound`)}function dO(e,t){let n=sO.safeParse(e);if(!n.success)throw new K(`Capability source snapshot must have a non-empty bounded version`);uO(t+n.data.modules.length)}function fO(e,t,n,r,i){return ft(a=>S(function*(){let o=t=>si({try:()=>t.release(),catch:()=>new $x(e.id,`release`)}).pipe(cn(e=>w(()=>{n.push(e)}))),s=yield*en({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(i===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:i}).then(e=>Qi(e),()=>ea(new $x(e.id,`acquire`)))}},catch:()=>new $x(e.id,`acquire`)});yield*xa(t,Dt(()=>s.outcome).pipe(E(e=>ra(e)?o(e.value):h)));let c=yield*a(Dt(()=>s.outcome)).pipe(Ce(()=>w(()=>{s.controller.abort()})));return ia(c)?yield*Bt(c.cause):c.value}))}function pO(e){return S(function*(){let t=yield*en({try:()=>lO(e.sources),catch:e=>e instanceof K?e:new K(`Capability sources are invalid`)});yield*en({try:()=>{uO(e.modules.length)},catch:e=>e instanceof K?e:new K(`Static capability modules are invalid`)});let n=yield*_a(),r=[],i=!1,a=[...e.modules],o=[];return yield*S(function*(){for(let s of t){let t=yield*fO(s,n,r,()=>{i=!0},e.session);yield*en({try:()=>{dO(t.snapshot,a.length)},catch:e=>e instanceof K?e:new K(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*en({try:()=>JT(a,o),catch:e=>e instanceof K?e:new K(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=tO(s.operations,s.catalog,e.sandbox,c,s.moduleAliases,s.namespacePaths,e.session?.sessionId??null,e.access),u=!1;return Object.freeze({compiled:s,executeDoor:l,isStale:()=>i,close:()=>S(function*(){u||(u=!0,yield*c.awaitIdle,yield*wa(n,na));let e=r[0];e!==void 0&&(yield*x(e))})})}).pipe(Oe(e=>ra(e)?h:wa(n,e)))})}var mO=2;function hO(e){return S(function*(){for(let t=0;t<mO;t+=1){let t=yield*pO(e);if(!t.isStale())return t;yield*t.close()}return yield*x(new $x(void 0,`stale`))})}function gO(e,t,n){return ft(r=>r(e.take(1)).pipe(E(()=>w(t).pipe(Xn(e.release(1)))),E(n)))}function _O(e,t){return ni(e.candidate.close().pipe(vt({onFailure:t=>pa(e.settled,t).pipe(y(x(t))),onSuccess:()=>ma(e.settled,void 0).pipe(y(w(()=>{t.delete(e)})))})))}function vO(e,t){return e.runCleanup?_O(e.installed,t):da(e.installed.settled)}function yO(e,t){return Mn(e.map(e=>vO(e,t).pipe(Dn)),{concurrency:`unbounded`}).pipe(E(e=>{let t=e.find(ia);return t===void 0?h:Bt(t.cause)}))}function bO(e){return S(function*(){let t=yield*w_(1),n=yield*en({try:()=>iE(e.execution),catch:e=>e instanceof K?e:new K(`Execution policy is invalid`)}),r=yield*aE(n.capacity),i=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:n}),a=e.modules.length===0&&e.sources.length>0?void 0:yield*en({try:()=>JT(e.modules),catch:e=>e instanceof K?e:new K(`Capability compilation failed`)}),o=yield*en({try:()=>Object.freeze(e.tools.map(t=>mT(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof K?e:new K(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*hO({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*ua(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>gO(t,()=>(l=!0,[...c].map(e=>{e.retired=!0;let t=e.leases===0&&!e.closing;return t&&(e.closing=!0),{installed:e,runCleanup:t}})),e=>yO(e,c));return yield*br(()=>u().pipe(Mt)),Object.freeze({acquire:()=>t.withPermits(1)(S(function*(){if(l)return yield*x(new Qx);if(s===void 0||s.candidate.isStale()){let t=yield*hO({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*ua(),leases:0,retired:!1,closing:!1};s=a,c.add(a),n!==void 0&&(n.retired=!0,n.leases===0&&!n.closing&&(n.closing=!0,yield*_O(n,c)))}let n=s;n.leases+=1;let a,u=()=>gO(t,()=>{if(a!==void 0)return a?{installed:n,runCleanup:!1}:void 0;if(--n.leases,a=n.retired&&n.leases===0&&!n.closing,a)return n.closing=!0,{installed:n,runCleanup:!0}},e=>e===void 0?h:vO(e,c));return yield*br(()=>u().pipe(Mt)),Object.freeze({revision:n.candidate.compiled.revision,catalog:n.candidate.compiled.catalog,executeDoor:n.candidate.executeDoor,effectExecuteTool:n.candidate.executeDoor.effectTool,tools:o,release:u})})),close:u})})}function xO(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>ni(si({try:()=>e.execute(t,n),catch:yS}))})}function SO(e){return bO({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(be(e=>Object.freeze({acquire:()=>e.acquire().pipe(be(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function CO(e,t){let n=await Tr(e,t);if(ra(n))return n.value;let r=Ki(n.cause);if(Fn(r))throw r.value;if(Hi(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Wi(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function wO(e){let t=await CO(_a()),n=e.onSandboxFailure;try{let r=await CO(bO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:xO(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>Dt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(ya(t))),i=async e=>{let t=await CO(_a());try{let n=await CO(r.acquire().pipe(ya(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??=CO(n.release().pipe(Xn(wa(t,na)))),i)})}catch(e){throw await CO(wa(t,na)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=CO(r.close().pipe(Xn(wa(t,na)))),a)})}catch(e){throw await CO(wa(t,na)),e}}var TO=pm(()=>L([em,nm,Im,N,um(I(TO)),Yp(om(N,TO))])),EO=N.check(lh(1),fh(256)),DO=N.check(lh(1),fh(128)),OO=F({kind:M(`sandbox_failure`),ref:EO,executionId:EO,adapter:DO,buildSha:z(DO),tag:R([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:om(N,TO),healthAlert:nm});function kO(e){return wT(e)}function AO(e){return TT(e)}var jO=Object.freeze({module:AO,operation:kO,make:wO,gate:MT,grantAs:jT}),MO=Gh,NO=4096,PO=new TextEncoder,FO=MO.check(V(e=>PO.encode(JSON.stringify(e)).byteLength<=NO)),IO=O(FO);function LO(e,t){if(Jp(e))return Ae(O(e)(t));let n=e[`~standard`].validate(t);if(Rr(n,`then`))throw new G(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function RO(e,t){let n=IO(t);if(pe(n))throw new G(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!LO(e.schema,n.success))throw new G(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function zO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function BO(e,t){Fr(Xe(`shiitake_operation_failed`,jo(t)).pipe(or({operation:e,errorKind:t instanceof Error?`error`:`non-error`})))}var VO=64,HO=256,UO=new WeakMap,WO=new TextEncoder;function GO(e){let t=UO.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:WO.encode(n).byteLength});return UO.set(e,r),r}function KO(e){if(e.kind===`update`&&e.sandboxFailures!==void 0){let t={...e};return delete t.sandboxFailures,t}if(e.kind===`reset`&&e.baseline.sandboxFailures!==void 0){let t={...e.baseline};return delete t.sandboxFailures,{...e,baseline:t}}return e}function qO(e){let t=new Set,n=!1,r,i=e=>{Xt(Gg(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:Xt(Ig(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=hr(()=>o.closed?b(`closed`):r===void 0?o.lagged?b(`reset`):n?b(`closed`):Jg(o.frames).pipe(Ka(()=>b(`closed`)),E(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=GO(e).bytes),b(e)):x(r))):x(r));return Object.freeze({take:s,checkpoint:(e=-1)=>{i(o),o.lagged=!1,o.observed=e},close:()=>{o.closed||(o.closed=!0,i(o),t.delete(o),Hg(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=KO(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=GO(t);n.bytes+o>1048576||!Rg(n.frames,t)?(i(n),n.lagged=!0,Rg(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Hg(e.frames)}}}}var JO=new WeakMap;function YO(e,t){for(let n of JO.get(e)??[])if(n.observes(t))return!0;return!1}function XO(e,t){return e===`closed`||t===`closed`?`closed`:e===`reset`||t===`reset`?`reset`:e===`durable`||t===`durable`?`durable`:e===`activity`||t===`activity`?`activity`:`progress`}function ZO(e,t){if(e.pendingCount>=HO){e.pendingCount=0,e.pendingReason=void 0,e.reset=!0;return}e.pendingCount+=1,e.pendingReason=e.pendingReason===`durable`||t===`durable`?`durable`:e.pendingReason===`activity`||t===`activity`?`activity`:`progress`}function QO(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){ZO(e,t);return}e.wake=void 0;try{n(t)}catch(t){BO(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function $O(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&QO(n,`activity`)}function ek(e,t,n=`durable`){let r=JO.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){BO(`owner-observation-publish`,e);continue}}function tk(e){let t=JO.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){BO(`owner-execution-change-publish`,e)}}function nk(e){let t=new Map,n=new Set,r=JO.get(e)??new Set,i=!1,a=e=>{if(e.closed)return`closed`;if(e.reset)return e.reset=!1,`reset`;if(e.pendingCount===0)return;e.pendingCount=0;let t=e.pendingReason;return e.pendingReason=void 0,t??`progress`},o=e=>{if(e.closed)return;e.closed=!0,e.pendingCount=0,e.pendingReason=void 0,e.reset=!1;let r=e.wake;e.wake=void 0,n.delete(e);let i=t.get(e.sessionId);if(i?.delete(e),i?.size===0&&t.delete(e.sessionId),r!==void 0)try{r(`closed`)}catch(e){BO(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){$O(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&$O(n,e.sessionId);let r=e.sessionId===null?n:t.get(e.sessionId);if(r!==void 0)for(let t of r)t.settlementOnly&&e.reason!==`settlement`||QO(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),JO.set(e,r),Object.freeze({register:(e,r)=>hr(()=>{if(i)return x(new G(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=VO)return x(new G(`runtime`,`rejected`,`Observation capacity is exhausted`));let s={revision:0,sessionId:e,settlementOnly:r===`settlement`,closed:!1,pendingCount:0,pendingReason:void 0,queued:!0,reset:!1,wake:void 0},c=t.get(e)??new Set;c.add(s),t.set(e,c),n.add(s);let l=w(()=>a(s)),u=Kn(e=>{let t=a(s);if(t!==void 0){e(b(t));return}let n=t=>{e(b(t))};return s.wake=n,w(()=>{s.wake===n&&(s.wake=void 0)})});return b(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:w(()=>{if(!i){i=!0,r.delete(s),r.size===0&&JO.delete(e);for(let e of n)o(e)}})})}var rk=200,ik={onExcessProperty:`error`},ak=new TextEncoder,ok=U.pipe(B(H(0))),sk=N.pipe(B(lh(1)),B(V(e=>ak.encode(e).byteLength<=256)));O(F({limit:A(U.pipe(B(qm({minimum:1,maximum:rk})))),after:A(N)}),ik);var ck=W(cm([ok,sk]));O(ck),Kp(ck),O(F({session_id:sk,last_activity_at:ok,state:R([`needs_you`,`running`,`errored`,`done`]),bytes:U.pipe(B(H(0)))}),ik);var lk=k(F({extension_id:N,value_json:N})),uk=k(W(by)),dk=k(xy),fk=Kp(W(by));function pk(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
22
- extension_id TEXT PRIMARY KEY
23
- )`),e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention (
24
- session_id TEXT NOT NULL REFERENCES sessions(id),
25
- extension_id TEXT NOT NULL,
26
- id TEXT NOT NULL,
27
- value_json TEXT NOT NULL,
28
- PRIMARY KEY (session_id, extension_id, id)
29
- )`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_attention_owner ON session_attention(extension_id, session_id)`)}function mk(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=lk(e);return dk({...uk(t.value_json),extensionId:t.extension_id})})}function hk(e,t){return e.sql.exec(`SELECT 1 FROM session_attention a JOIN shiitake_extension_status s ON s.extension_id = a.extension_id AND s.status = 'running' JOIN session_attention_grants g ON g.extension_id = a.extension_id WHERE a.session_id = ? AND json_extract(a.value_json, '$.inbox') IS NOT 0 LIMIT 1`,t).toArray().length>0}function gk(e,t,n,r){if(k(F({count:U}))(e.sql.exec(`SELECT COUNT(*) AS count FROM session_attention WHERE session_id = ? AND NOT (extension_id = ? AND id = ?)`,t,n,r.id).one()).count>=64)throw new G(`contract`,`invalid`,`Session attention capacity reached`);if(k(F({count:U}))(e.sql.exec(`SELECT COUNT(*) AS count FROM session_attention WHERE extension_id = ? AND NOT (session_id = ? AND id = ?)`,n,t,r.id).one()).count>=4096)throw new G(`contract`,`invalid`,`Extension attention capacity reached`);e.sql.exec(`INSERT INTO session_attention (session_id, extension_id, id, value_json) VALUES (?, ?, ?, ?)
30
- ON CONFLICT (session_id, extension_id, id) DO UPDATE SET value_json = excluded.value_json`,t,n,r.id,fk(r))}function _k(e,t,n,r){e.sql.exec(`DELETE FROM session_attention WHERE session_id = ? AND extension_id = ? AND id = ?`,t,n,r)}function vk(e,t,n){let r=k(F({session_id:N}));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 yk(e,t){let n=k(F({extension_id:N})),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 bk=8,xk=k(F({agent_id:N,sender_session_id:N,name:N})),Sk=k(yy);function Ck(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_work_senders (
31
- session_id TEXT NOT NULL,
32
- work_id TEXT NOT NULL,
33
- agent_id TEXT NOT NULL,
34
- sender_session_id TEXT NOT NULL,
35
- name TEXT NOT NULL,
36
- PRIMARY KEY (session_id, work_id)
37
- )`)}function wk(e,t,n,r){e.sql.exec(`INSERT OR IGNORE INTO session_work_senders
38
- (session_id, work_id, agent_id, sender_session_id, name)
39
- VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function Tk(e,t,n){let r=e.sql.exec(`SELECT agent_id, sender_session_id, name FROM session_work_senders WHERE session_id = ? AND work_id = ?`,t,n).toArray()[0];if(r===void 0)return;let i=xk(r);return Sk({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function Ek(e,t,n){let r=Tk(e,t,n);return r===void 0?[]:Dk(e,t,[r])}function Dk(e,t,n){return mk(e,t).filter(e=>n.some(t=>e.waitingOn?.agentId===t.agentId&&e.waitingOn.sessionId===t.sessionId)).slice(0,bk).map(e=>({itemId:e.id,kind:e.kind,summary:e.summary}))}var Ok=F({status:R([`accepted`,`duplicate`]),cursor:U.check(H(0))});L([R([`accepted`,`duplicate`,`refused`]),Ok,F({status:R([`accepted`,`duplicate`,`refused`]),receipt:Gh})]),Fi(`PostError`);var kk=N.check(lh(1),fh(256));F({postKey:kk}),U.check(H(1),Km(64)),yg({family:`post`,version:1,kinds:{work:{prefix:`post_work`}}});var Ak=F({key:kk,kind:kk,address:$p,event:$p});W(L([F({state:M(`pending`),envelope:Ak,attempts:U.check(H(0)),nextAttemptAt:P.check(H(0)),deadlineAt:j(P.check(H(0))),jobId:j(kk),delivery:j(Ak),nextKey:j(kk)}),F({state:M(`delivered`),receipt:j(Gh),nextKey:j(kk)}),F({state:M(`dead`),envelope:Ak,attempts:U.check(H(0)),reason:R([`refused`,`exhausted`,`expired`]),deadlineAt:j(P.check(H(0))),receipt:j(Gh),delivery:j(Ak),nextKey:j(kk)})])),F({key:N,value:N}),F({due:z(P.check(H(0)))});var jk=N.check(lh(1),fh(256)),Mk=262144,Nk=N.check(V(e=>new TextEncoder().encode(e).byteLength<=Mk,{message:`Mail content must be at most ${String(Mk)} UTF-8 bytes`})),Pk=F({kind:M(`agent`),agentId:jk,sessionId:jk}),Fk=F({kind:M(`agent`),agentId:jk,sessionId:A(jk)}),Ik=F({kind:M(`system`),systemId:M(`hub`)}),Lk=F({itemId:jk,kind:N.check(lh(1),fh(64)),summary:N.check(lh(1),fh(200))}),Rk=F({commandId:jk,outcome:R([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:A(N.check(lh(1),fh(200))),waitingOnYou:A(I(Lk).check(lh(1),fh(8)))}),zk=R([`recipient_offline`,`recipient_left`]),Bk=F({outcome:M(`undeliverable`),reason:zk}),Vk=F({outcome:M(`accepted`),commandId:jk});L([Rk,Bk,Vk]);var Hk=L([Rk,Vk,F({outcome:M(`undeliverable`),reason:M(`recipient_left`)})]),Uk=`[redacted]`,Wk=/\b(bearer|basic)\s+[^\s"',;]+/giu,Gk=/\b((?:api[_-]?key|access[_-]?token|refresh[_-]?token|token|secret|password|authorization)["']?\s*[:=]\s*["']?)(?!(?:bearer|basic)\s)[^\s"',;&]+/giu,Kk=/[A-Za-z0-9][\w-]{23,}/gu;function qk(e){return e.replace(Wk,`$1 ${Uk}`).replace(Gk,`$1${Uk}`).replace(Kk,e=>/\d/u.test(e)&&/[A-Za-z]/u.test(e)?Uk:e)}function Jk(e){let t=qk(e.replace(/[\p{Cc}\p{Zl}\p{Zp}\s]+/gu,` `).trim()).slice(0,200).trimEnd();return t.length===0?void 0:t}var Yk={key:jk,to:Fk,replyTo:I(Pk),content:Nk,createdAt:P.check(H(0)),meta:A(Gh)},Xk=L([F({...Yk,from:Pk,reply:A(Hk)}),F({...Yk,from:Ik,reply:F({outcome:M(`undeliverable`),reason:M(`recipient_offline`)})})]),Zk=F({jobId:jk,sessionId:jk,commandFactId:jk,recovery:j(F({maxRecoveries:U.check(H(0))}))}),Qk=F({work:F({sessionId:jk,commandFactId:jk}),mail:j(Xk)}),$k=F({work:Zk,delivery:R([`steer`,`followUp`]),mail:j(Xk)}),eA=e=>{let t=k($k)(e),n={sessionId:t.work.sessionId,commandFactId:t.work.commandFactId},r=t.mail===void 0?{work:n}:{work:n,mail:t.mail},i={jobId:t.work.jobId,queue:t.work.sessionId,lane:`default`,priority:+(t.delivery===`steer`),payload:r,state:`queued`};return t.work.recovery===void 0?i:{...i,recovery:t.work.recovery}},tA=e=>k(Qk)(e.payload);function nA(e,t,n,r){let i=k(jk)(t),a=k(Pk)(e.from),o=k(Vk)({outcome:`accepted`,commandId:n});return{key:`${e.key}:accepted`,to:a,from:{...e.to,sessionId:i},replyTo:[],content:`Work accepted.`,createdAt:r,reply:o}}var rA=k(F({mail_key:N,agent_id:N,reply_to_json:W(I(Pk))})),iA=Kp(W(I(Pk)));function aA(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_delegators (
40
- session_id TEXT PRIMARY KEY,
41
- mail_key TEXT NOT NULL,
42
- agent_id TEXT NOT NULL,
43
- reply_to_json TEXT NOT NULL
44
- )`)}function oA(e,t,n){n!==void 0&&n.reply===void 0&&n.from.kind===`agent`&&n.replyTo.length!==0&&e.sql.exec(`INSERT OR IGNORE INTO session_delegators (session_id, mail_key, agent_id, reply_to_json) VALUES (?, ?, ?, ?)`,t,n.key,n.to.agentId,iA(n.replyTo))}function sA(e,t){let[n]=e.sql.exec(`SELECT mail_key, agent_id, reply_to_json FROM session_delegators WHERE session_id = ?`,t).toArray();if(n===void 0)return;let r=rA(n);return{key:r.mail_key,agentId:r.agent_id,replyTo:r.reply_to_json}}var cA=new TextEncoder,lA=new TextDecoder,uA=/^[A-Za-z0-9_-]+$/u,dA=F({v:M(1),generation:N.pipe(B(lh(1)),B(fh(128)),B(V(e=>cA.encode(e).byteLength<=128))),sequence:U.pipe(B(Wm(0)),B(Km(2**53-1)))}),fA={onExcessProperty:`error`},pA=O(dA,fA),mA=O(W(dA),fA);function hA(e){let t=pA({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(cA.encode(n).byteLength>384)return;let r=ks(n);return cA.encode(r).byteLength<=512?r:void 0}function gA(e){if(cA.encode(e).byteLength>512||!uA.test(e))return;let t=As(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=lA.decode(t.success),r=mA(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&ks(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var _A=N.check(lh(1),fh(256)),vA=L([F({agentId:_A,sessionId:_A,...Rk.fields}),F({agentId:_A,sessionId:A(_A),...Bk.fields})]),yA=`fungi_agent_reply`,bA=RegExp(`<(?=\\s*/?\\s*${yA})`,`giu`);function xA(e){return e.replace(bA,`&lt;`)}function SA(e){return e.replaceAll(`&`,`&amp;`).replaceAll(`"`,`&quot;`).replaceAll(`<`,`&lt;`).replaceAll(`>`,`&gt;`)}function CA(e){let t=[[`agent_id`,e.agentId]];return e.sessionId!==void 0&&t.push([`session_id`,e.sessionId]),e.outcome!==`undeliverable`&&t.push([`command_id`,e.commandId]),t.push([`outcome`,e.outcome]),e.outcome!==`undeliverable`&&e.diagnostic!==void 0&&t.push([`diagnostic`,e.diagnostic]),e.outcome!==`undeliverable`&&e.waitingOnYou!==void 0&&t.push([`waiting_on_you`,JSON.stringify(e.waitingOnYou)]),e.outcome===`undeliverable`&&t.push([`reason`,e.reason]),`<${yA} ${t.map(([e,t])=>`${e}="${SA(t)}"`).join(` `)}>`}function wA(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:xA(e.text)}:e):xA(e.content);if(t===void 0)return{...e,content:n};let r=CA(t),i=`</${yA}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var TA={onExcessProperty:`error`},EA=new TextEncoder,DA=e=>N.pipe(B(lh(1)),B(V(t=>EA.encode(t).byteLength<=e))),OA=DA(256),kA=DA(4096),AA=N.pipe(B(Om(/^[0-9a-f]{64}$/u))),jA=pm(()=>L([N,P,nm,em,I(jA),om(N,jA)])),MA=F({type:M(`text`),text:N,textSignature:A(N)}),NA=F({type:M(`thinking`),thinking:N,thinkingSignature:A(N),redacted:A(nm)}),PA=F({type:M(`image`),data:N,mimeType:N}),FA=F({type:M(`toolCall`),id:N,name:N,arguments:om(N,jA),thoughtSignature:A(N),namespace:A(N),argumentsError:A(N)}),IA=F({input:P,output:P,cacheRead:P,cacheWrite:P,cacheWrite1h:A(P),reasoning:A(P),totalTokens:P,cost:F({input:P,output:P,cacheRead:P,cacheWrite:P,total:P})}),LA=F({role:M(`user`),content:L([N,um(I(L([MA,PA])))]),timestamp:P}),RA=F({role:M(`user`),content:N,timestamp:P}),zA=F({name:N,description:N,parameters:om(N,jA),constrainedSampling:A(L([M(!1),F({type:M(`json_schema`),strict:R([`prefer`,`require`])}),F({type:M(`grammar`),variants:F({openai_lark:A(N),openai_regex:A(N)})})]))}),BA=L([F({role:M(`system`),content:L([N,um(I(MA))]),sections:A(om(N,L([N,em]))),toolsAdded:A(um(I(zA))),toolsRemoved:A(um(I(F({name:N})))),timestamp:P}),LA,F({role:M(`assistant`),content:um(I(L([MA,NA,FA]))),api:N,provider:N,model:N,responseModel:A(N),responseId:A(N),diagnostics:A(um(I(F({type:N,timestamp:P,error:A(F({name:A(N),message:N,stack:A(N),code:A(L([N,P]))})),details:A(om(N,jA))})))),usage:IA,stopReason:R([`pending`,`stop`,`length`,`toolUse`,`error`,`aborted`,`deferred`]),deferred:A(F({provider:N,modelId:N,api:N,id:N,expiresAt:A(P),pollAfterMs:A(P),data:A(jA)})),errorMessage:A(N),providerError:A(N),rawStopReason:A(N),providerThinkingLevel:A(N),endTurn:A(nm),timestamp:P,durationMs:A(P)}),F({role:M(`toolResult`),toolCallId:N,toolName:N,content:um(I(L([MA,PA]))),usage:A(IA),isError:nm,timestamp:P,durationMs:A(P)})]),VA=R([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),HA=pm(()=>F({kind:VA,value:OA,parent:j(HA)})),UA=L([F({type:M(`auto_retry_start`),run:HA,attempt:P,maxAttempts:P,delayMs:P,errorMessage:N}),F({type:M(`auto_retry_attempt`),run:HA,attempt:P}),F({type:M(`auto_retry_end`),run:HA,attempt:P,success:nm,finalError:A(N)})]),WA=F({core:AA,extensions:I(cm([OA,N.pipe(B(Om(/^sha256:[0-9a-f]{64}$/u)))])).pipe(B(fh(128)))}),GA=F({content:um(I(L([MA,PA]))),usage:j(IA),isError:nm,terminate:j(nm)}),KA={workId:OA},qA=R([`manual`,`threshold`,`overflow`]),JA=W(L([F({...KA,kind:M(`sandbox_failure`),event:OO}),F({kind:M(`document`),workId:em,extensionId:OA,name:OA,valueJson:N}),F({kind:M(`model_preference`),workId:em,preference:z(Ty)}),F({...KA,kind:M(`command`),meta:A(FO),reply:A(vA),delivery:A(R([`steer`,`followUp`])),requestId:OA,targetWorkId:A(OA),receiptId:OA,message:LA,contract:WA}),F({...KA,kind:M(`command`),work:M(`compact`),instructions:A(Xy),meta:A(FO),requestId:OA,receiptId:OA,timestamp:U.check(H(0)),contract:WA}),F({kind:M(`operator`),workId:em,requestId:OA,author:R([`operator`,`party`]),meta:A(FO),message:RA}),F({...KA,kind:M(`cancellation`),requestId:OA,receiptId:OA,targetWorkId:OA,meta:A(FO)}),F({...KA,kind:M(`model_selection`),provider:OA,model:OA,catalogRevision:OA,definitionRevision:OA,selectionPolicyRevision:OA}),F({...KA,kind:M(`run_started`),run:HA,contract:WA}),F({...KA,kind:M(`turn_started`),run:HA,turn:HA}),F({...KA,kind:M(`model_prompt`),run:HA,turn:HA,attempt:P.pipe(B(Ym()),B(Wm(0))),contract:WA,systemPrompt:N.pipe(B(V(e=>EA.encode(e).byteLength<=1048576)))}),F({...KA,kind:M(`message_start`),run:HA,turn:HA,message:HA,role:R([`assistant`,`system`,`toolResult`,`user`])}),F({...KA,kind:M(`message`),data:A(jA),run:HA,turn:HA,message:HA,value:BA}),F({...KA,kind:M(`tool_intent`),replay:R([`safe`,`unsafe`]).pipe(Sm(b(`unsafe`))),contract:WA,run:HA,turn:HA,toolCall:HA,call:FA}),F({...KA,kind:M(`tool_outcome`),data:A(jA),run:HA,turn:HA,toolCall:HA,call:FA,result:GA}),F({...KA,kind:M(`live_retry`),event:UA}),F({...KA,kind:M(`compaction`),head:OA,model:cm([LA]),data:F({reason:A(qA),resumesRun:nm,tokensBefore:P,tokensAfter:A(P),usage:IA,contextRevision:OA,receipt:A(kA),details:A(F({readFiles:I(N),modifiedFiles:I(N)}))})}),F({...KA,kind:M(`compaction_notice`),trigger:qA,result:M(`nothing_to_compact`),diagnostic:A(N.check(fh(200)))}),F({...KA,kind:M(`compaction_notice`),trigger:qA,result:M(`failed`),usage:A(IA),diagnostic:A(N.check(fh(200)))}),F({...KA,kind:M(`compaction_notice`),trigger:qA,result:M(`stale`),usage:A(IA)}),F({...KA,kind:M(`compaction_notice`),trigger:qA,result:M(`insufficient`),usage:A(IA)}),F({...KA,kind:M(`run_terminal`),run:HA,terminal:HA,diagnostic:A(N.check(fh(200))),outcome:R([`completed`,`cancelled`,`failed`])}),F({...KA,kind:M(`work_terminal`),diagnostic:A(N),outcome:R([`completed`,`interrupted`,`cancelled`,`failed`])})])),YA=W($p),XA=O(JA,TA),ZA=Kp(YA),QA=k(JA,TA);function $A(e){return`work`in e}function ej(e){return e.kind===`command`&&!$A(e)?e:void 0}function tj(e){return $A(e)?e.timestamp:e.message.timestamp}function nj(e){return wA(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 rj(e){return wA(e.message,e.reply)}function ij(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 aj(e){return _r(XA(e),e=>e.kind===`command`&&!$A(e)&&e.delivery===void 0?{...e,delivery:`followUp`}:e)}function oj(e){let t=ZA(e);return QA(t),t}var sj=N.pipe(B(lh(1))),cj=U.pipe(B(H(0))),lj={onExcessProperty:`error`},uj=F({value_json:N}),dj=F({state_version:U.pipe(B(H(1))),revision:sj}),fj=F({status:R([`running`,`stopped`]),reason:z(N),stopped_at:z(cj),revision:sj}),pj=F({extension_id:sj,key:sj,due_at:cj}),mj=F({collection:sj,key:sj,value_json:N}),hj=F({sequence:cj}),gj=F({due:R([0,1]),next_due_at:z(cj)});function _j(e){return new G(`store`,`unavailable`,e)}function vj(e,t,n){let r=O(e,lj);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw _j(n);return t.success})}function yj(e){e.transactionSync(()=>{e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_records (
45
- extension_id TEXT NOT NULL,
46
- collection TEXT NOT NULL,
47
- key TEXT NOT NULL,
48
- index_value TEXT,
49
- value_json TEXT NOT NULL,
50
- PRIMARY KEY (extension_id, collection, key)
51
- )`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_shiitake_extension_records_index
52
- ON shiitake_extension_records(extension_id, collection, index_value, key)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_state (
53
- extension_id TEXT PRIMARY KEY,
54
- state_version INTEGER NOT NULL CHECK (state_version >= 1),
55
- revision TEXT NOT NULL
56
- )`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_status (
57
- extension_id TEXT PRIMARY KEY,
58
- status TEXT NOT NULL CHECK (status IN ('running', 'stopped')),
59
- reason TEXT,
60
- stopped_at INTEGER,
61
- revision TEXT NOT NULL,
62
- CHECK ((status = 'running') = (reason IS NULL)),
63
- CHECK ((reason IS NULL) = (stopped_at IS NULL))
64
- )`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_timers (
65
- extension_id TEXT NOT NULL,
66
- key TEXT NOT NULL,
67
- due_at INTEGER NOT NULL CHECK (due_at >= 0),
68
- PRIMARY KEY (extension_id, key)
69
- )`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_shiitake_extension_timers_due
70
- ON shiitake_extension_timers(due_at, extension_id, key)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_settled_cursors (
71
- consumer TEXT PRIMARY KEY,
72
- sequence INTEGER NOT NULL CHECK (sequence >= 0)
73
- )`)})}function bj(e,t,n,r){return vj(uj,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
74
- WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r).toArray(),`Stored extension record is invalid`)[0]?.value_json}function xj(e,t,n,r){return vj(uj,e.sql.exec(`SELECT value_json FROM shiitake_extension_records
75
- WHERE extension_id = ? AND collection = ?
76
- AND (? IS NULL OR index_value = ?)
77
- AND (? IS NULL OR key > ?)
78
- 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 Sj(e,t,n,r,i,a){e.sql.exec(`INSERT INTO shiitake_extension_records
79
- (extension_id, collection, key, index_value, value_json)
80
- VALUES (?, ?, ?, ?, ?)
81
- ON CONFLICT(extension_id, collection, key) DO UPDATE SET
82
- index_value = excluded.index_value, value_json = excluded.value_json`,t,n,r,i,a)}function Cj(e,t,n,r){e.sql.exec(`DELETE FROM shiitake_extension_records
83
- WHERE extension_id = ? AND collection = ? AND key = ?`,t,n,r)}function wj(e,t){return vj(mj,e.sql.exec(`SELECT collection, key, value_json FROM shiitake_extension_records
84
- 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 Tj(e,t){e.sql.exec(`DELETE FROM shiitake_extension_records WHERE extension_id = ?`,t)}function Ej(e,t){let n=vj(dj,e.sql.exec(`SELECT state_version, revision FROM shiitake_extension_state
85
- WHERE extension_id = ?`,t).toArray(),`Extension ledger is invalid`)[0];return n===void 0?void 0:{version:n.state_version,revision:n.revision}}function Dj(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_state (extension_id, state_version, revision)
86
- VALUES (?, ?, ?)
87
- ON CONFLICT(extension_id) DO UPDATE SET
88
- state_version = excluded.state_version, revision = excluded.revision`,t,n,r)}function Oj(e,t){let n=vj(fj,e.sql.exec(`SELECT status, reason, stopped_at, revision FROM shiitake_extension_status
89
- 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 kj(e,t,n){e.sql.exec(`INSERT INTO shiitake_extension_status
90
- (extension_id, status, reason, stopped_at, revision)
91
- VALUES (?, ?, ?, ?, ?)
92
- ON CONFLICT(extension_id) DO UPDATE SET status = excluded.status,
93
- reason = excluded.reason, stopped_at = excluded.stopped_at,
94
- revision = excluded.revision`,t,n.status,n.reason,n.stoppedAt,n.revision)}function Aj(e,t,n,r){e.sql.exec(`INSERT INTO shiitake_extension_timers (extension_id, key, due_at)
95
- VALUES (?, ?, ?)
96
- ON CONFLICT(extension_id, key) DO UPDATE SET due_at = excluded.due_at`,t,n,r)}function jj(e,t,n){e.sql.exec(`DELETE FROM shiitake_extension_timers WHERE extension_id = ? AND key = ?`,t,n)}function Mj(e,t){e.sql.exec(`DELETE FROM shiitake_extension_timers WHERE extension_id = ?`,t)}function Nj(e,t,n){return vj(pj,e.sql.exec(`SELECT extension_id, key, due_at FROM shiitake_extension_timers
97
- WHERE extension_id = ? AND key = ?`,t,n).toArray(),`Extension timer is invalid`)[0]?.due_at}function Pj(e){return e.map(()=>`?`).join(`, `)}function Fj(e,t,n,r){return t.length===0?[]:vj(pj,e.sql.exec(`SELECT extension_id, key, due_at FROM shiitake_extension_timers
98
- WHERE due_at <= ? AND extension_id IN (${Pj(t)})
99
- 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 Ij(e,t,n){if(t.length===0)return{due:!1,nextWakeAt:null};let r=Pj(t),i=vj(gj,e.sql.exec(`SELECT
100
- EXISTS (SELECT 1 FROM shiitake_extension_timers
101
- WHERE due_at <= ? AND extension_id IN (${r})) AS due,
102
- (SELECT MIN(due_at) FROM shiitake_extension_timers
103
- 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 _j(`Extension timer is unavailable`);return{due:i.due===1,nextWakeAt:i.next_due_at}}function Lj(e,t){return vj(hj,e.sql.exec(`SELECT sequence FROM shiitake_settled_cursors WHERE consumer = ?`,t).toArray(),`Settled cursor is invalid`)[0]?.sequence}function Rj(e,t,n){e.sql.exec(`INSERT INTO shiitake_settled_cursors (consumer, sequence) VALUES (?, ?)
104
- ON CONFLICT(consumer) DO UPDATE SET sequence = MAX(sequence, excluded.sequence)`,t,n)}var zj=F({extension_id:N,name:N,initial_json:N,fork:R([`inherit-at-fork-point`,`current`,`fresh`]),max_bytes:U.pipe(B(Wm(0)))});function Bj(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_document_specs (
105
- extension_id TEXT NOT NULL, name TEXT NOT NULL, initial_json TEXT NOT NULL,
106
- fork TEXT NOT NULL, max_bytes INTEGER NOT NULL,
107
- PRIMARY KEY (extension_id, name)
108
- )`)}function Vj(e,t){e.sql.exec(`INSERT INTO session_document_specs
109
- (extension_id, name, initial_json, fork, max_bytes) VALUES (?, ?, ?, ?, ?)
110
- ON CONFLICT(extension_id, name) DO UPDATE SET initial_json = excluded.initial_json,
111
- fork = excluded.fork, max_bytes = excluded.max_bytes`,t.extensionId,t.name,t.initialJson,t.fork,t.maxBytes)}function Hj(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=k(zj)(e);if(n.fork===`inherit-at-fork-point`)return[];let r=n.fork===`fresh`?n.initial_json:t(n.extension_id,n.name)??n.initial_json;if(new TextEncoder().encode(r).byteLength>n.max_bytes)throw new G(`store`,`rejected`,`Session document exceeds its declared size bound`);return[{kind:`document`,workId:null,extensionId:n.extension_id,name:n.name,valueJson:r}]})}var Uj=Fp(N),Wj=`The conversation history before this point was compacted into the following summary:
112
-
113
- <summary>
114
- `,Gj=`
115
- </summary>`;function Kj(e,t){return{role:`user`,content:[{type:`text`,text:Wj+e+Gj}],timestamp:t}}function qj(e){let t=Array.isArray(e.content)?e.content[0]:void 0,n=t?.type===`text`?t.text:void 0;if(n===void 0||!n.startsWith(Wj)||!n.endsWith(Gj))throw Error(`Compaction model message is not a summary`);return n.slice(Wj.length,n.length-Gj.length)}function Jj(){return{edited:new Set,read:new Set,written:new Set}}function Yj(e,t){if(e.role===`assistant`)for(let n of e.content){if(n.type!==`toolCall`)continue;let e=n.arguments.path;Uj(e)&&(n.name===`edit`&&t.edited.add(e),n.name===`read`&&t.read.add(e),n.name===`write`&&t.written.add(e))}}function Xj(e){let t=new Set([...e.edited,...e.written]);return{modifiedFiles:[...t].sort(),readFiles:[...e.read].filter(e=>!t.has(e)).sort()}}function Zj(e,t){let n=[];return e.length>0&&n.push(`<read-files>\n${e.join(`
116
- `)}\n</read-files>`),t.length>0&&n.push(`<modified-files>\n${t.join(`
117
- `)}\n</modified-files>`),n.length===0?``:`\n\n${n.join(`
118
-
119
- `)}`}var Qj=2e3;function $j(e){return e.filter(e=>e.type===`text`).map(e=>e.text??``).join(``)}function eM(e){if(e.length<=Qj)return e;let t=String(e.length-Qj);return`${e.slice(0,Qj)}\n\n[... ${t} more characters truncated]`}function tM(e){let t=Uj(e.content)?e.content:$j(e.content);return t?`[User]: ${t}`:void 0}function nM(e){let t=[],n=[];for(let r of e.content)if(r.type===`text`)t.push(r.text);else if(r.type===`toolCall`){let e=Object.entries(r.arguments).map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(`, `);n.push(`${r.name}(${e})`)}let r=[];return t.length>0&&r.push(`[Assistant]: ${t.join(`
120
- `)}`),n.length>0&&r.push(`[Assistant tool calls]: ${n.join(`; `)}`),r}function rM(e){let t=$j(e.content);return t?`[Tool result]: ${eM(t)}`:void 0}function iM(e){let t=[];for(let n of e)if(n.role===`system`){let e=Uj(n.content)?n.content:$j(n.content);e&&t.push(`[System]: ${e}`)}else if(n.role===`user`){let e=tM(n);e!==void 0&&t.push(e)}else if(n.role===`assistant`)t.push(...nM(n));else{let e=rM(n);e!==void 0&&t.push(e)}return t.join(`
121
-
122
- `)}function aM(e,t,n){return n.enabled?e>t-n.reserveTokens:!1}function oM(e,t,n){return!n.enabled||n.backgroundTokens===0?!1:e>t-n.reserveTokens-n.backgroundTokens&&!aM(e,t,n)}var sM={enabled:!0,reserveTokens:16384,keepRecentTokens:2e4,backgroundTokens:32768},cM=`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.
123
-
124
- Do NOT continue the conversation. Do NOT respond to any questions in the conversation. ONLY output the structured summary.`,lM=`The messages above are a conversation to summarize. Create a structured context checkpoint summary that another LLM will use to continue the work.
125
-
126
- Use this EXACT format:
127
-
128
- ## Goal
129
- [What is the user trying to accomplish? Can be multiple items if the session covers different tasks.]
130
-
131
- ## Constraints & Preferences
132
- - [Any constraints, preferences, or requirements mentioned by user]
133
- - [Or "(none)" if none were mentioned]
134
-
135
- ## Progress
136
- ### Done
137
- - [x] [Completed tasks/changes]
138
-
139
- ### In Progress
140
- - [ ] [Current work]
141
-
142
- ### Blocked
143
- - [Issues preventing progress, if any]
144
-
145
- ## Key Decisions
146
- - **[Decision]**: [Brief rationale]
147
-
148
- ## Next Steps
149
- 1. [Ordered list of what should happen next]
150
-
151
- ## Critical Context
152
- - [Any data, examples, or references needed to continue]
153
- - [Or "(none)" if not applicable]
154
-
155
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,uM=`The messages above are NEW conversation messages to incorporate into the existing summary provided in <previous-summary> tags.
156
-
157
- Update the existing structured summary with new information. RULES:
158
- - PRESERVE all existing information from the previous summary
159
- - ADD new progress, decisions, and context from the new messages
160
- - UPDATE the Progress section: move items from "In Progress" to "Done" when completed
161
- - UPDATE "Next Steps" based on what was accomplished
162
- - PRESERVE exact file paths, function names, and error messages
163
- - If something is no longer relevant, you may remove it
164
-
165
- Use this EXACT format:
166
-
167
- ## Goal
168
- [Preserve existing goals, add new ones if the task expanded]
169
-
170
- ## Constraints & Preferences
171
- - [Preserve existing, add new ones discovered]
172
-
173
- ## Progress
174
- ### Done
175
- - [x] [Include previously done items AND newly completed items]
176
-
177
- ### In Progress
178
- - [ ] [Current work - update based on progress]
179
-
180
- ### Blocked
181
- - [Current blockers - remove if resolved]
182
-
183
- ## Key Decisions
184
- - **[Decision]**: [Brief rationale] (preserve all previous, add new)
185
-
186
- ## Next Steps
187
- 1. [Update based on current state]
188
-
189
- ## Critical Context
190
- - [Preserve important context, add new if needed]
191
-
192
- Keep each section concise. Preserve exact file paths, function names, and error messages.`,dM=`The messages above are earlier context from an ongoing conversation. Later messages are stored separately and do not need to be reconstructed.
193
-
194
- 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.
195
-
196
- ## Original Request
197
- [What did the user ask for?]
198
-
199
- ## Progress So Far
200
- - [Key decisions and work completed in these messages]
201
-
202
- ## Context Needed to Continue
203
- - [Information from these messages needed to understand the later work]
204
-
205
- Only summarize information explicitly present above. Do not infer or recreate later messages.`;function fM(e,t){if(e.stopReason===`error`){let n=e.errorMessage;return`${t} failed: ${n!==void 0&&n.length>0?n:`Unknown error`}`}return e.stopReason===`length`?`${t} failed: generation hit the token cap and the summary is incomplete`:e.content.some(e=>e.type===`toolCall`)?`${t} attempted to call a tool`:void 0}var pM=om(N.check(lh(1),fh(160)),R([`none`,`read`,`write`])).check(V(e=>Object.keys(e).length<=256)),mM=O(F({version:U.check(H(0),Km(2**53-1)),grants:pM}),{onExcessProperty:`error`}),hM=O(W(pM)),gM=Kp(W(pM)),_M=O(F({version:U,grants_json:N}));function vM(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_tool_grants (
206
- session_id TEXT PRIMARY KEY,
207
- version INTEGER NOT NULL,
208
- grants_json TEXT NOT NULL
209
- )`)}function yM(e,t,n){let r=mM(n);if(pe(r))throw new G(`contract`,`invalid`,`Session grants delivery is invalid`);let i=gM(r.success.grants),a=bM(e,t);if(a!==void 0){if(r.success.version<a.version)throw new G(`contract`,`conflict`,`Session grants delivery is older than the stored delivery`);if(r.success.version===a.version&&a.grantsJson===i)return`unchanged`}return e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
210
- VALUES (?, ?, ?)
211
- ON CONFLICT(session_id) DO UPDATE SET
212
- version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function bM(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=_M(n);if(pe(r))throw new G(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:r.success.version,grantsJson:r.success.grants_json}}function xM(e,t){let n=bM(e,t);if(n===void 0)return null;let r=hM(n.grantsJson);if(pe(r))throw new G(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:n.version,grants:r.success}}function SM(e,t,n){e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
213
- SELECT ?, version, grants_json FROM session_tool_grants WHERE session_id = ?`,n,t)}var CM=200,wM={onExcessProperty:`error`},TM=new TextEncoder,EM=N.pipe(B(lh(1)),B(V(e=>TM.encode(e).byteLength<=256))),DM=U.pipe(B(H(0))),OM=R([0,1,2]),kM=R([`needs_you`,`running`,`errored`,`done`]),AM=R([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),jM=F({session_id:EM,title:z(N),created_at:DM,last_activity_at:DM,settled_at:z(DM),state:kM,tier:OM}),MM=O(jM,wM);O(jM.mapFields(bp({revision:DM})),wM),O(F({revision:DM}),wM);var NM=O(F({outcome:z(AM)}),wM),PM=W(cm([OM,DM,EM])),FM=O(PM),IM=Kp(PM),LM=`session_id, title, created_at, last_activity_at, settled_at, state, tier`;function RM(e){return new G(`store`,`unavailable`,e)}function zM(e){switch(e){case`needs_you`:return 0;case`running`:return 1;case`errored`:case`done`:return 2}}function BM(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 VM(e){e.sql.exec(`
214
- CREATE TABLE IF NOT EXISTS session_inbox (
215
- session_id TEXT PRIMARY KEY REFERENCES sessions(id),
216
- title TEXT,
217
- created_at INTEGER NOT NULL,
218
- last_activity_at INTEGER NOT NULL,
219
- settled_at INTEGER,
220
- outcome TEXT CHECK (
221
- outcome IS NULL OR outcome IN (
222
- 'completed', 'failed', 'cancelled', 'outcome_unknown', 'interrupted'
223
- )
224
- ),
225
- state TEXT NOT NULL
226
- CHECK (state IN ('needs_you', 'running', 'errored', 'done')),
227
- tier INTEGER NOT NULL CHECK (tier IN (0, 1, 2)),
228
- revision INTEGER NOT NULL
229
- )
230
- `),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_order
231
- ON session_inbox(tier, last_activity_at DESC, session_id)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_revision
232
- ON session_inbox(revision)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_coldest
233
- ON session_inbox(last_activity_at, session_id)`),e.sql.exec(`
234
- CREATE TABLE IF NOT EXISTS session_inbox_clock (
235
- singleton INTEGER PRIMARY KEY CHECK (singleton = 1),
236
- revision INTEGER NOT NULL
237
- )
238
- `),e.sql.exec(`INSERT OR IGNORE INTO session_inbox_clock (singleton, revision) VALUES (1, 0)`),e.sql.exec(`
239
- CREATE TABLE IF NOT EXISTS session_inbox_tombstones (
240
- session_id TEXT PRIMARY KEY,
241
- revision INTEGER NOT NULL
242
- ) STRICT
243
- `),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_inbox_tombstones_revision ON session_inbox_tombstones(revision)`)}function HM(e){e.sql.exec(`UPDATE session_inbox_clock SET revision = revision + 1 WHERE singleton = 1`)}var UM=`(SELECT revision FROM session_inbox_clock WHERE singleton = 1)`;function WM(e,t){let n=t.title===void 0?``:t.title,r=t.title===void 0?0:1;HM(e),e.sql.exec(`INSERT INTO session_inbox
244
- (session_id, title, created_at, last_activity_at, settled_at, outcome,
245
- state, tier, revision)
246
- SELECT id, ?, created_at, COALESCE(?, created_at), NULL, NULL, 'done', 2,
247
- ${UM}
248
- FROM sessions
249
- WHERE id = ?
250
- ON CONFLICT (session_id) DO UPDATE SET
251
- title = CASE WHEN ? = 1 THEN excluded.title ELSE title END,
252
- last_activity_at = MAX(last_activity_at, excluded.last_activity_at),
253
- revision = excluded.revision`,n,t.activityAt??null,t.sessionId,r)}function GM(e,t){HM(e),e.sql.exec(`INSERT INTO session_inbox_tombstones (session_id, revision)
254
- VALUES (?, ${UM})
255
- ON CONFLICT (session_id) DO UPDATE SET revision = excluded.revision`,t)}function KM(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=NM(r);if(i._tag===`Failure`)throw RM(`Stored inbox row is invalid`);let a=t.settled?.outcome??i.success.outcome,o=BM(t.head,a,hk(e,t.queue));HM(e),e.sql.exec(`UPDATE session_inbox
256
- SET outcome = ?, state = ?, tier = ?, revision = ${UM},
257
- settled_at = CASE WHEN ? = 1 THEN ? ELSE settled_at END,
258
- last_activity_at = MAX(last_activity_at, ?)
259
- WHERE session_id = ?`,a,o,zM(o),t.settled===void 0?0:1,n,n,t.queue)}function qM(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=NM(r);if(i._tag===`Failure`)throw RM(`Stored inbox row is invalid`);let a=BM(n,i.success.outcome,hk(e,t));HM(e),e.sql.exec(`UPDATE session_inbox SET state = ?, tier = ?, revision = ${UM} WHERE session_id = ?`,a,zM(a),t)}function JM(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 YM(e){let t=FM(e);if(t._tag===`Failure`)throw new G(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function XM(e,t){let n=t===void 0?void 0:YM(t),r=n===void 0?e.sql.exec(`SELECT ${LM} FROM session_inbox
260
- ORDER BY tier ASC, last_activity_at DESC, session_id ASC
261
- LIMIT ?`,CM).toArray():e.sql.exec(`SELECT ${LM} FROM session_inbox
262
- WHERE tier > ?
263
- OR (tier = ? AND last_activity_at < ?)
264
- OR (tier = ? AND last_activity_at = ? AND session_id > ?)
265
- ORDER BY tier ASC, last_activity_at DESC, session_id ASC
266
- LIMIT ?`,n[0],n[0],n[1],n[0],n[1],n[2],CM).toArray(),i=[],a;for(let e of r){let t=MM(e);if(t._tag===`Failure`)throw RM(`Stored inbox row is invalid`);let n=t.success;a=[n.tier,n.last_activity_at,n.session_id],i.push(JM(n))}return{sessions:i,next:r.length===CM&&a!==void 0?IM(a):void 0}}var ZM=yg({family:`session`,version:1,kinds:{session:{prefix:`session`},work:{prefix:`session_work`},fact:{prefix:`session_fact`},receipt:{prefix:`session_receipt`}}});function QM(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.data.resumesRun||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.data===void 0?t.result:{...t.result,data:t.data},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 $M(e,t){let n=new Set(e.flatMap(({entry:e})=>e.kind===`run_terminal`?[e.workId]:[])),r=new Set,i=new Map;for(let a of e){let e=a.entry;if(e.kind===`message`&&(e.value.role===`assistant`&&i.set(e.workId,a.id),(n.has(e.workId)||e.workId===t)&&(e.value.role!==`assistant`||e.value.stopReason!==`error`&&e.value.stopReason!==`aborted`)&&r.add(a.id)),e.kind===`compaction`&&e.data.resumesRun||e.kind===`live_retry`&&e.event.type===`auto_retry_start`){let t=i.get(e.workId);t!==void 0&&r.delete(t)}}return r}function eN(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.data.resumesRun)))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 tN={onExcessProperty:`error`},nN=new TextEncoder,rN=N.pipe(B(lh(1)),B(V(e=>nN.encode(e).byteLength<=256))),iN=U.pipe(B(Wm(0))),aN=U.pipe(B(H(0))),oN=F({id:rN,leaf_id:z(rN)}),sN=F({session_id:rN}),cN=F({id:rN,leaf_id:z(rN),created_at:aN,updated_at:aN,metadata_json:z(N)}),lN=W(F({title:$y})),uN=O(lN,tN),dN=Kp(lN),fN=F({id:rN}),pN=F({version:U,protocol:M(`shiitake.extension/v0`)}),mN=F({name:rN}),hN=F({id:rN,session_id:rN,parent_id:z(rN),sequence:iN,type:N,role:z(R([`user`,`assistant`,`tool_result`])),state:R([`complete`,`streaming`]),request_id:z(rN),work_id:z(rN),data_json:N,timestamp:aN,completed_at:z(aN),damaged:R([0,1])}),gN=F({id:rN,session_id:rN,sequence:iN,request_id:rN,work_id:rN,data_json:N,timestamp:aN,origin_kind:R([`user`,`extension`]),origin_id:z(rN),origin_correlation:z(rN)}),_N=F({kind:M(`extension`),extensionId:rN,correlation:z(rN)}),vN=L([F({kind:M(`user`)}),_N]),yN=O(vN,tN),bN=Vh(vN),xN=e=>[`id`,`session_id`,`sequence`,`request_id`,`work_id`,`data_json`,`timestamp`,`origin_kind`,`origin_id`,`origin_correlation`].map(t=>e+t).join(`, `),SN=F({next_sequence:iN}),CN=F({present:M(1)}),wN=O(sN,tN),TN=O(cN,tN),EN=O(fN,tN),DN=O(pN,tN),ON=O(mN,tN),kN=O(F({candidate_id:z(rN),path_count:U.pipe(B(Wm(0))),root_count:U.pipe(B(H(0))),missing_parent_count:U.pipe(B(H(0))),leaf_state:R([`complete`,`streaming`])}),tN),AN=O(hN,tN),jN=O(gN,tN),MN=O(SN,tN),NN=O(CN,tN);function PN(e){return`${[`id`,`session_id`,`parent_id`,`sequence`,`type`,`role`,`state`,`request_id`,`work_id`,`data_json`,`timestamp`,`completed_at`].map(t=>`${e}.${t}`).join(`, `)},
267
- EXISTS (SELECT 1 FROM session_lineage_damage AS damage
268
- WHERE damage.session_id = ${e}.session_id) AS damaged`}var FN=PN(`session_entries`);function IN(e,t){return t===void 0?e:{...e,meta:t}}function LN(e,t){if(ZN(e,t)===void 0)return;let n=e.sql.exec(`SELECT id, leaf_id, created_at, updated_at, metadata_json
269
- FROM sessions
270
- WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=TN(n);if(r._tag===`Failure`)throw $(`Stored Session summary row is invalid`);let i=VN(e,t,r.success),a=r.success.metadata_json;if(a===null)return i;let o=uN(a);if(o._tag===`Failure`)throw $(`Stored Session title is invalid`);return Object.freeze({createdAt:r.success.created_at,updatedAt:r.success.updated_at,title:o.success.title})}var RN=O(F({id:rN,sequence:iN}),tN);function zN(e,t,n,r){let i=e.sql.exec(`SELECT command.id AS id, command.sequence AS sequence
271
- FROM session_entries AS command
272
- WHERE command.session_id = ? AND command.type = 'command'
273
- AND command.role = 'user' AND command.state = 'complete'
274
- AND NOT EXISTS (
275
- SELECT 1 FROM session_entries AS cancelled
276
- WHERE cancelled.work_id = command.work_id
277
- AND cancelled.session_id = command.session_id
278
- AND cancelled.type = 'cancellation'
279
- AND cancelled.sequence < command.sequence
280
- )
281
- ORDER BY command.sequence ASC LIMIT 1`,t).toArray()[0];if(i===void 0)return null;let a=RN(i);if(a._tag===`Failure`)throw $(`Stored Session first prompt is invalid`);let o=a.success;return r<o.sequence?null:e.sql.exec(`SELECT 1 AS present FROM session_entries AS parent
282
- WHERE parent.session_id = ? AND parent.sequence < ?
283
- AND (SELECT COUNT(*) FROM session_entries AS child
284
- WHERE child.parent_id = parent.id
285
- AND child.session_id = parent.session_id
286
- AND child.state = 'complete') > 1
287
- LIMIT 1`,t,o.sequence).toArray()[0]===void 0?o.id:BN(e,t,n)}function BN(e,t,n){let r=kN(e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, type, role, state, work_id) AS (
288
- SELECT id, parent_id, sequence, type, role, state, work_id
289
- FROM session_entries
290
- WHERE session_id = ? AND id = ?
291
- UNION
292
- SELECT parent.id, parent.parent_id, parent.sequence,
293
- parent.type, parent.role, parent.state, parent.work_id
294
- FROM branch AS child
295
- CROSS JOIN session_entries AS parent
296
- WHERE parent.id = child.parent_id AND parent.session_id = ?
297
- )
298
- SELECT
299
- (SELECT command.id FROM branch AS command
300
- WHERE command.type = 'command' AND command.role = 'user'
301
- AND command.state = 'complete'
302
- AND NOT EXISTS (
303
- SELECT 1 FROM branch AS cancelled
304
- WHERE cancelled.type = 'cancellation'
305
- AND cancelled.work_id = command.work_id
306
- AND cancelled.sequence < command.sequence
307
- )
308
- ORDER BY command.sequence ASC LIMIT 1) AS candidate_id,
309
- (SELECT COUNT(*) FROM branch) AS path_count,
310
- (SELECT COUNT(*) FROM branch WHERE parent_id IS NULL) AS root_count,
311
- (SELECT COUNT(*) FROM branch AS child
312
- WHERE child.parent_id IS NOT NULL
313
- AND NOT EXISTS (
314
- SELECT 1 FROM session_entries AS parent
315
- WHERE parent.session_id = ? AND parent.id = child.parent_id
316
- )) AS missing_parent_count,
317
- (SELECT state FROM branch WHERE id = ?) AS leaf_state`,t,n,t,t,n).one());if(r._tag===`Failure`||r.success.leaf_state!==`complete`||r.success.root_count!==1||r.success.missing_parent_count!==0)throw $(`Stored Session summary lineage is invalid`);return r.success.candidate_id}function VN(e,t,n){if(n.leaf_id===null)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:``});let r=QN(e,t,n.leaf_id);if(r?.state!==`complete`)throw $(`Stored Session summary leaf is invalid`);let i=zN(e,t,n.leaf_id,r.sequence),a=i===null?void 0:QN(e,t,i)?.entry,o=a===void 0?void 0:ej(a);if(o!==void 0)return Object.freeze({createdAt:n.created_at,updatedAt:n.updated_at,title:Array.from(JF(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 HN(e,t){try{return LN(e,t)?.title??``}catch(e){if(e instanceof G&&e.cause===`unavailable`)return null;throw e}}function $(e){return new G(`store`,`unavailable`,e)}function UN(e){return new G(`store`,`incompatible`,e)}function WN(e){return e.kind===`command`||e.kind===`cancellation`||e.kind===`operator`?e.requestId:null}function GN(e){return e.kind===`command`?$A(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 KN(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function qN(e,t){let n=AN(t);if(n._tag===`Failure`)throw $(`Stored Session entry row is invalid`);let r=n.success;if(r.damaged===1)throw BP(e,r.session_id);let i=aj(r.data_json);if(i._tag===`Failure`)throw $(`Stored Session entry data is invalid`);let a=i.success;if(r.type!==a.kind||r.work_id!==a.workId||r.request_id!==WN(a)||r.role!==GN(a))throw $(`Stored Session entry columns disagree with its data`);return Object.freeze({id:r.id,sessionId:r.session_id,parentId:r.parent_id,sequence:r.sequence,state:r.state,timestamp:r.timestamp,completedAt:r.completed_at,entry:a})}function JN(e){let t=jN(e);if(t._tag===`Failure`)throw $(`Stored command admission row is invalid`);let n=t.success,r=aj(n.data_json);if(r._tag===`Failure`||r.success.kind!==`command`)throw $(`Stored command admission data is invalid`);let i=r.success;if(n.request_id!==i.requestId||n.work_id!==i.workId||n.id!==i.receiptId||n.id!==i.workId||n.timestamp!==tj(i))throw $(`Stored command admission columns disagree with its data`);let a=yN(n.origin_kind===`user`?{kind:`user`}:{kind:`extension`,extensionId:n.origin_id,correlation:n.origin_correlation});if(a._tag===`Failure`||n.origin_kind===`user`&&(n.origin_id!==null||n.origin_correlation!==null))throw $(`Stored command admission origin is invalid`);return Object.freeze({id:n.id,sessionId:n.session_id,sequence:n.sequence,timestamp:n.timestamp,entry:i,origin:a.success})}function YN(e,t){return ZN(e,t)!==void 0}var XN=O(F({...oN.fields,damaged:R([0,1])}),tN);function ZN(e,t){let n=e.sql.exec(`SELECT id, leaf_id,
318
- EXISTS (SELECT 1 FROM session_lineage_damage
319
- WHERE session_id = sessions.id) AS damaged
320
- FROM sessions WHERE id = ?`,t).toArray()[0];if(n===void 0)return;let r=XN(n);if(r._tag===`Failure`)throw $(`Stored Session row is invalid`);if(r.success.damaged===1)throw BP(e,t);return Object.freeze({id:r.success.id,leaf_id:r.success.leaf_id})}function QN(e,t,n){let r=e.sql.exec(`SELECT ${FN}
321
- FROM session_entries
322
- WHERE session_id = ? AND id = ?`,t,n).toArray()[0];return r===void 0?void 0:qN(e,r)}function $N(e,t){if(t.leaf_id===null){let n=e.sql.exec(`SELECT 1 AS present
323
- FROM session_entries
324
- WHERE session_id = ?
325
- LIMIT 1`,t.id).toArray()[0];if(n===void 0)return;throw NN(n)._tag===`Failure`?$(`Session entry presence is invalid`):$(`Session leaf is invalid`)}let n=QN(e,t.id,t.leaf_id);if(n?.state!==`complete`)throw $(`Session leaf is invalid`);return n}function eP(e,t){let n=e.sql.exec(`SELECT ${FN}
326
- FROM session_entries
327
- WHERE id = ?`,t).toArray()[0];return n===void 0?void 0:qN(e,n)}function tP(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 ${xN(``)}
328
- FROM session_command_admissions
329
- WHERE session_id = ? AND ${r} = ?`,t,i).toArray()[0];return a===void 0?void 0:JN(a)}var nP=`FROM session_command_admissions AS a
330
- WHERE a.session_id = ?
331
- AND NOT EXISTS (
332
- SELECT 1 FROM session_entries AS e
333
- WHERE e.session_id = a.session_id AND e.work_id = a.work_id
334
- AND e.type IN ('command', 'cancellation', 'run_terminal', 'work_terminal')
335
- )`;function rP(e,t,n){return e.sql.exec(`SELECT 1 FROM session_entries WHERE session_id = ? AND work_id = ? AND type = 'run_terminal' LIMIT 1`,t,n).toArray().length>0}var iP=k(F({identity:z(N)}));function aP(e,t,n){let{identity:r}=iP(e.sql.exec(`SELECT json_extract(?, ?) AS identity`,JSON.stringify(n??null),t).one());if(r===null||r.length===0)throw new G(`runtime`,`rejected`,`Request author is required`);return{path:t,value:r}}function oP(e,t,n,r){let i=mP(e,t,n);if(i!==void 0&&aP(e,r.path,i.entry.meta).value!==r.value)throw new G(`runtime`,`rejected`,`Message author does not match`)}function sP(e,t,n){let r=e.sql.exec(`SELECT ${xN(`a.`)} ${nP}
336
- AND json_extract(a.data_json, '$.work') IS NULL
337
- AND a.origin_kind = 'user'
338
- AND (? IS NULL OR json_extract(json_extract(a.data_json, '$.meta'), ?) = ?)
339
- ORDER BY a.sequence DESC LIMIT 1`,t,n?.path??null,n?.path??null,n?.value??null).toArray()[0];return r===void 0?void 0:JN(r)}var cP=k(F({total:U.check(H(0))}));function lP(e,t,n,r=`all`){let i=r===`prompts`?`AND json_extract(a.data_json, '$.work') IS NULL`:``,a=cP(e.sql.exec(`SELECT COUNT(*) AS total ${nP} ${i}`,t).one()).total;return{commands:e.sql.exec(`SELECT ${xN(`a.`)} ${nP} ${i}
340
- ORDER BY (json_extract(a.data_json, '$.delivery') = 'steer') DESC,
341
- a.sequence ASC LIMIT ?`,t,n).toArray().map(JN),total:a}}function uP(e,t,n,r,i=200){return e.sql.exec(`SELECT ${xN(`a.`)}
342
- FROM session_command_admissions AS a
343
- WHERE a.session_id = ?
344
- AND json_extract(a.data_json, '$.delivery') = ?
345
- AND (? IS NULL OR json_extract(a.data_json, '$.targetWorkId') = ?)
346
- AND NOT EXISTS (
347
- SELECT 1 FROM session_entries AS e
348
- WHERE e.session_id = a.session_id AND e.work_id = a.work_id
349
- AND e.type IN ('command', 'run_terminal', 'work_terminal')
350
- )
351
- ORDER BY a.sequence ASC LIMIT ?`,t,n,r??null,r??null,i).toArray().map(JN)}function dP(e,t,n){return uP(e,t,`steer`,n,1).length>0}function fP(e,t,n,r){return e.transactionSync(()=>uP(e,t,n,r).map(n=>{let r=ej(QN(e,t,n.id)?.entry??YP(e,{sessionId:t,id:n.id,entry:n.entry}).entry);if(r===void 0)throw $(`Session control admission is invalid`);return{workId:r.workId,requestId:r.requestId,message:rj(r)}}))}function pP(e,t){e.transactionSync(()=>{let n=e.sql.exec(`SELECT ${xN(`a.`)}
352
- FROM session_command_admissions AS a
353
- WHERE a.session_id = ?
354
- AND json_extract(a.data_json, '$.delivery') = 'steer'
355
- AND json_extract(a.data_json, '$.targetWorkId') = ?
356
- ORDER BY a.sequence ASC`,t.sessionId,t.parentWorkId).toArray().map(JN);for(let r of n){if(e.sql.exec(`SELECT 1 AS present FROM session_entries WHERE session_id = ? AND work_id = ? AND type IN ('run_terminal', 'work_terminal') LIMIT 1`,t.sessionId,r.entry.workId).toArray()[0]!==void 0)continue;if(QN(e,t.sessionId,r.id)===void 0){t.enqueue({jobId:r.entry.workId,sessionId:t.sessionId,commandFactId:r.id,delivery:`steer`});continue}let n=t.outcome===`failed`||t.outcome===`interrupted`?t.diagnostic:void 0,i={kind:`work_terminal`,workId:r.entry.workId,outcome:t.outcome};n!==void 0&&(i={...i,diagnostic:n}),YP(e,{sessionId:t.sessionId,id:ZM.fact.generate(),entry:i})}})}function mP(e,t,n){return tP(e,t,{id:n})}function hP(e,t,n){return tP(e,t,{workId:n})}function gP(e,t,n){return tP(e,t,{requestId:n})}function _P(e,t,n){return ZN(e,t),e.sql.exec(`SELECT 1 AS present FROM session_entries
357
- INDEXED BY idx_session_entries_work_terminal
358
- WHERE session_id = ? AND work_id = ?
359
- AND type IN ('run_terminal', 'work_terminal')
360
- LIMIT 1`,t,n).toArray().length>0}function vP(e,t,n){return ZN(e,t),Object.freeze(e.sql.exec(`SELECT ${FN}
361
- FROM session_entries
362
- WHERE session_id = ? AND work_id = ?
363
- ORDER BY sequence ASC`,t,n).toArray().map(t=>qN(e,t)))}function yP(e,t,n){let r=e.sql.exec(`SELECT ${FN}
364
- FROM session_entries
365
- WHERE session_id = ? AND work_id = ? AND type = 'live_retry'
366
- ORDER BY sequence DESC
367
- LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=qN(e,r);if(i.entry.kind!==`live_retry`)throw $(`Stored live retry entry is invalid`);return{event:i.entry.event,timestamp:i.timestamp}}function bP(e,t,n,r){return e.sql.exec(`SELECT 1 FROM session_entries INDEXED BY idx_session_entries_successful_tool
368
- WHERE session_id = ? AND work_id = ? AND type = 'tool_outcome'
369
- AND json_extract(data_json, '$.result.isError') = 0
370
- AND json_extract(data_json, '$.call.id') = ? LIMIT 1`,t,n,r).toArray().length>0}function xP(e,t,n){let r=e.sql.exec(`SELECT ${PN(`intent`)}
371
- FROM session_entries AS intent
372
- WHERE intent.session_id = ? AND intent.work_id = ?
373
- AND intent.type = 'tool_intent'
374
- AND NOT EXISTS (
375
- SELECT 1 FROM session_entries AS outcome
376
- WHERE outcome.session_id = intent.session_id
377
- AND outcome.work_id = intent.work_id
378
- AND outcome.type = 'tool_outcome'
379
- AND json_extract(outcome.data_json, '$.toolCall.value') =
380
- json_extract(intent.data_json, '$.toolCall.value')
381
- )
382
- ORDER BY intent.sequence DESC
383
- LIMIT 1`,t,n).toArray()[0];if(r===void 0)return;let i=qN(e,r);if(i.entry.kind!==`tool_intent`)throw $(`Stored tool intent is invalid`);return i.entry.call.name}function SP(e,t){let n=MN(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
384
- FROM session_entries
385
- WHERE session_id = ?`,t).one());if(n._tag===`Failure`)throw $(`Next Session sequence is invalid`);return n.success.next_sequence}function CP(e,t){let n=MN(e.sql.exec(`SELECT COALESCE(MAX(sequence), 0) + 1 AS next_sequence
386
- FROM (
387
- SELECT sequence
388
- FROM session_command_admissions
389
- WHERE session_id = ?
390
- UNION ALL
391
- SELECT sequence
392
- FROM session_entries
393
- WHERE session_id = ? AND type = 'command'
394
- )`,t,t).one());if(n._tag===`Failure`)throw $(`Next command admission sequence is invalid`);return n.success.next_sequence}function wP(e,t){let n=ZN(e,t);if(n!==void 0)return n;let r=Date.now();e.sql.exec(`INSERT INTO sessions
395
- (id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
396
- VALUES (?, '/', NULL, NULL, ?, ?, NULL)`,t,r,r),WM(e,{sessionId:t,activityAt:r,title:``});let i=ZN(e,t);if(i===void 0)throw $(`Created Session row is unavailable`);return i}function TP(e,t,n){return e.transactionSync(()=>EP(e,t,n))}function EP(e,t,n){let r=e.sql.exec(`SELECT session_id FROM session_creation_receipts WHERE request_id = ?`,t).toArray()[0];if(r!==void 0){let e=wN(r);if(e._tag===`Failure`)throw $(`Session creation receipt is invalid`);return e.success.session_id}n();let i=ZM.session.generate();return wP(e,i),e.sql.exec(`INSERT INTO session_creation_receipts (request_id, session_id) VALUES (?, ?)`,t,i),i}function DP(e,t){return e.transactionSync(()=>{if(!(e.sql.exec(`SELECT id FROM sessions WHERE id = ?`,t.sessionId).toArray().length>0))return!1;t.assertIdleSession(t.sessionId),t.recordInboxDeletion(t.sessionId);for(let n of[`DELETE FROM session_command_admissions WHERE session_id = ?`,`DELETE FROM session_attention WHERE session_id = ?`,`DELETE FROM session_work_senders WHERE session_id = ?`,`DELETE FROM session_tool_grants WHERE session_id = ?`,`DELETE FROM session_inbox WHERE session_id = ?`,`DELETE FROM session_creation_receipts WHERE session_id = ?`,`DELETE FROM sessions WHERE id = ?`,`DELETE FROM session_entries WHERE session_id = ?`,`DELETE FROM session_lineage_damage WHERE session_id = ?`])e.sql.exec(n,t.sessionId);return!0})}var OP=3,kP=`shiitake.extension/v0`;function AP(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(ON(n)._tag===`Failure`)throw $(`Store catalog row is invalid`);return!0}function jP(e){if(!AP(e,`woodstock_schema`))return AP(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=DN(t[0]);return n._tag===`Success`&&n.success.version===OP?`v0`:`unmarked`}function MP(e){let t=jP(e);if(t!==`v0`){if(t===`unmarked`)throw UN(`Woodstock store has no current v0 schema marker; incompatible storage requires explicit host custody. To reset, stop the owning host before resetting a local store, then remove its database file and the file's .owner.sqlite sidecar. Reset discards that store's data. For the Hub, a Hub Agent is erased only with its Team; Team erasure is destructive and separately authorized, never a routine single-Agent repair. No migration runs.`);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 (?, ?)`,OP,kP)}}function NP(e){e.sql.exec(`
397
- CREATE TABLE IF NOT EXISTS session_entries (
398
- id TEXT PRIMARY KEY,
399
- session_id TEXT NOT NULL,
400
- parent_id TEXT,
401
- sequence INTEGER NOT NULL,
402
- type TEXT NOT NULL,
403
- role TEXT,
404
- state TEXT NOT NULL CHECK (state IN ('complete', 'streaming')),
405
- request_id TEXT,
406
- work_id TEXT,
407
- data_json TEXT NOT NULL,
408
- timestamp INTEGER NOT NULL,
409
- completed_at INTEGER,
410
- UNIQUE (session_id, sequence)
411
- )
412
- `)}var PP=[`session_entries_lineage_insert`,`session_entries_lineage_update`,`session_entries_lineage_delete`,`session_entries_damaged_session`,`session_entries_lineage_replace`,`session_entries_lineage_replace_position`],FP=O(F({installed:U.pipe(B(H(0)))}),tN),IP=O(F({session_id:N}),tN),LP=`Woodstock Session holds a broken lineage; a store never repairs itself — delete this Session (deleteSession), or reset the owning store`,RP=O(F({damaged:U.pipe(B(Wm(0))),first:N}),tN),zP=class extends G{store;sessionId;constructor(e,t,n){super(`store`,`unavailable`,n),this.store=e,this.sessionId=t}get diagnostic(){return`${this.store}: Woodstock Session ${this.sessionId} holds a broken lineage; delete it with deleteSession("${this.sessionId}"), or reset the owning store`}};function BP(e,t){let n=e.storeName??`Woodstock store`;return new zP(n,t,`${n}: ${HP(e,t)}`)}function VP(e,t){return e.sql.exec(`SELECT session_id FROM session_lineage_damage WHERE session_id = ?`,t).toArray().length>0}function HP(e,t){let n=RP(e.sql.exec(`SELECT COUNT(*) AS damaged, MIN(session_id) AS first FROM session_lineage_damage`).one());if(n._tag===`Failure`)throw $(`Stored Session lineage damage is invalid`);let{damaged:r,first:i}=n.success;return`Woodstock Session ${t} holds a broken lineage (this store has ${String(r)} damaged Session${r===1?``:`s`}, first ${i}); a store never repairs itself — delete this Session with deleteSession("${t}"), or reset the owning store: for a Durable Object, erase all of its storage (DurableObjectStorage.deleteAll(); a Hub Agent is erased only with its Team, POST /operator/teams/:teamId/erasure-durable-objects); for a local store, remove its file and the file's .owner.sqlite sidecar`}function UP(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_lineage_damage (session_id TEXT PRIMARY KEY)`);let t=FP(e.sql.exec(`SELECT COUNT(*) AS installed FROM sqlite_master
413
- WHERE type = 'trigger'
414
- AND name IN (SELECT value FROM json_each(?))`,JSON.stringify(PP)).one());if(t._tag===`Failure`)throw $(`Stored Session lineage guards are invalid`);if(t.success.installed!==PP.length){let t=e.sql.exec(`SELECT child.session_id AS session_id
415
- FROM session_entries AS child
416
- LEFT JOIN session_entries AS parent ON parent.id = child.parent_id
417
- WHERE child.parent_id IS NOT NULL
418
- AND (parent.id IS NULL
419
- OR parent.session_id != child.session_id
420
- OR parent.state != 'complete'
421
- OR parent.sequence >= child.sequence)
422
- UNION
423
- SELECT session_id FROM session_entries
424
- WHERE parent_id IS NULL AND state = 'complete'
425
- GROUP BY session_id HAVING COUNT(*) > 1`).toArray().map(e=>{let t=IP(e);if(t._tag===`Failure`)throw $(`Stored Session lineage audit is invalid`);return t.success.session_id});for(let n of t)e.sql.exec(`INSERT OR IGNORE INTO session_lineage_damage (session_id) VALUES (?)`,n),WM(e,{sessionId:n,title:null})}e.sql.exec(`
426
- CREATE TRIGGER IF NOT EXISTS session_entries_lineage_replace
427
- BEFORE INSERT ON session_entries
428
- WHEN EXISTS (
429
- SELECT 1 FROM session_entries AS child
430
- WHERE child.parent_id = NEW.id
431
- AND (child.session_id != NEW.session_id
432
- OR child.sequence <= NEW.sequence
433
- OR NEW.state != 'complete'))
434
- BEGIN
435
- SELECT RAISE(ABORT, 'Session entry would strand its children');
436
- END
437
- `),e.sql.exec(`
438
- CREATE TRIGGER IF NOT EXISTS session_entries_lineage_replace_position
439
- BEFORE INSERT ON session_entries
440
- WHEN EXISTS (
441
- SELECT 1 FROM session_entries AS held
442
- JOIN session_entries AS child ON child.parent_id = held.id
443
- WHERE held.session_id = NEW.session_id
444
- AND held.sequence = NEW.sequence
445
- AND held.id != NEW.id)
446
- BEGIN
447
- SELECT RAISE(ABORT, 'Session entry would strand its children');
448
- END
449
- `),e.sql.exec(`
450
- CREATE TRIGGER IF NOT EXISTS session_entries_damaged_session
451
- BEFORE INSERT ON session_entries
452
- WHEN EXISTS (
453
- SELECT 1 FROM session_lineage_damage WHERE session_id = NEW.session_id)
454
- BEGIN
455
- SELECT RAISE(ABORT, '${LP}');
456
- END
457
- `),e.sql.exec(`
458
- CREATE TRIGGER IF NOT EXISTS session_entries_lineage_insert
459
- BEFORE INSERT ON session_entries
460
- BEGIN
461
- SELECT RAISE(ABORT, 'Session entry parent is not an earlier complete entry of its Session')
462
- WHERE NEW.parent_id IS NOT NULL AND NOT EXISTS (
463
- SELECT 1 FROM session_entries AS parent
464
- WHERE parent.id = NEW.parent_id
465
- AND parent.session_id = NEW.session_id
466
- AND parent.state = 'complete'
467
- AND parent.sequence < NEW.sequence);
468
- SELECT RAISE(ABORT, 'Session already has a root entry')
469
- WHERE NEW.parent_id IS NULL AND EXISTS (
470
- SELECT 1 FROM session_entries AS other
471
- WHERE other.session_id = NEW.session_id
472
- AND other.state = 'complete'
473
- AND other.id != NEW.id);
474
- END
475
- `),e.sql.exec(`
476
- CREATE TRIGGER IF NOT EXISTS session_entries_lineage_update
477
- BEFORE UPDATE OF id, session_id, parent_id, sequence, state
478
- ON session_entries
479
- BEGIN
480
- SELECT RAISE(ABORT, 'Session entry lineage columns are immutable');
481
- END
482
- `),e.sql.exec(`
483
- CREATE TRIGGER IF NOT EXISTS session_entries_lineage_delete
484
- BEFORE DELETE ON session_entries
485
- WHEN EXISTS (SELECT 1 FROM sessions WHERE id = OLD.session_id)
486
- AND EXISTS (SELECT 1 FROM session_entries WHERE parent_id = OLD.id)
487
- BEGIN
488
- SELECT RAISE(ABORT, 'Session entry still has children');
489
- END
490
- `)}function WP(e){e.transactionSync(()=>{MP(e),e.sql.exec(`
491
- CREATE TABLE IF NOT EXISTS sessions (
492
- id TEXT PRIMARY KEY,
493
- cwd TEXT NOT NULL,
494
- parent_session TEXT,
495
- leaf_id TEXT,
496
- created_at INTEGER NOT NULL,
497
- updated_at INTEGER NOT NULL,
498
- metadata_json TEXT
499
- )
500
- `),NP(e),Bj(e),pk(e),Ck(e),aA(e),vM(e),VM(e),e.sql.exec(`
501
- CREATE TABLE IF NOT EXISTS session_creation_receipts (
502
- request_id TEXT PRIMARY KEY,
503
- session_id TEXT NOT NULL UNIQUE REFERENCES sessions(id)
504
- )
505
- `),e.sql.exec(`DELETE FROM session_delegators
506
- WHERE NOT EXISTS (
507
- SELECT 1 FROM session_creation_receipts AS creation
508
- WHERE creation.session_id = session_delegators.session_id
509
- AND creation.request_id = session_delegators.mail_key
510
- )`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_parent ON session_entries(parent_id)`),e.sql.exec(`DROP INDEX IF EXISTS idx_session_entries_lineage`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_ancestry
511
- ON session_entries(id, session_id, parent_id, sequence, state, type)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_session ON session_entries(session_id, sequence)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_streaming ON session_entries(session_id, state)`),e.sql.exec(`CREATE UNIQUE INDEX IF NOT EXISTS idx_session_entries_request
512
- ON session_entries(session_id, request_id)
513
- WHERE request_id IS NOT NULL`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_work ON session_entries(work_id, sequence)`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_work_terminal
514
- ON session_entries(session_id, work_id)
515
- WHERE type IN ('run_terminal', 'work_terminal')`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_model_preference
516
- ON session_entries(session_id, sequence)
517
- WHERE type = 'model_preference'`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_cancellation_target
518
- ON session_entries(session_id, json_extract(data_json, '$.targetWorkId'))
519
- WHERE type = 'cancellation'`),e.sql.exec(`CREATE INDEX IF NOT EXISTS idx_session_entries_successful_tool
520
- ON session_entries(session_id, work_id, json_extract(data_json, '$.call.id'))
521
- WHERE type = 'tool_outcome' AND json_extract(data_json, '$.result.isError') = 0`),UP(e),e.sql.exec(`
522
- CREATE TABLE IF NOT EXISTS session_request_withdrawals (
523
- session_id TEXT NOT NULL,
524
- request_id TEXT NOT NULL,
525
- PRIMARY KEY (session_id, request_id)
526
- )
527
- `),e.sql.exec(`
528
- CREATE TABLE IF NOT EXISTS session_command_admissions (
529
- id TEXT PRIMARY KEY,
530
- session_id TEXT NOT NULL,
531
- sequence INTEGER NOT NULL,
532
- request_id TEXT NOT NULL,
533
- work_id TEXT NOT NULL,
534
- data_json TEXT NOT NULL,
535
- timestamp INTEGER NOT NULL,
536
- origin_kind TEXT NOT NULL CHECK (origin_kind IN ('user', 'extension')),
537
- origin_id TEXT,
538
- origin_correlation TEXT,
539
- CHECK ((origin_kind = 'user') = (origin_id IS NULL)),
540
- CHECK (origin_kind = 'extension' OR origin_correlation IS NULL),
541
- -- This orders durable acceptance facts, not conversation entries.
542
- UNIQUE (session_id, sequence),
543
- UNIQUE (session_id, request_id),
544
- UNIQUE (session_id, work_id)
545
- )
546
- `)}),yj(e)}function GP(e,t){let n=ZN(e,t)?.leaf_id;return n==null?null:CF(e,t,n)}function KP(e,t){let n=ZN(e,t)?.leaf_id;return n==null?null:SF(e,t,n)?.sequence??null}function qP(e,t,n){return e.transactionSync(()=>YP(e,{sessionId:t,id:ZM.fact.generate(),entry:{kind:`model_preference`,workId:null,preference:n}}))}function JP(e,t,n){e.transactionSync(()=>{wP(e,t);let r=n===null?null:dN({title:n});e.sql.exec(`SELECT 1 FROM sessions WHERE id = ? AND metadata_json IS ?`,t,r).toArray().length>0||(e.sql.exec(`UPDATE sessions SET metadata_json = ? WHERE id = ?`,r,t),WM(e,{sessionId:t,title:HN(e,t)}))})}function YP(e,t){let n=$N(e,wP(e,t.sessionId)),r=t.state??`complete`;if(r===`streaming`!=(t.entry.kind===`message_start`))throw $(`A message start must be the streaming entry`);if(r===`streaming`&&t.entry.kind===`message_start`&&t.id!==t.entry.message.value)throw $(`Message placeholder identity does not match its row`);let i=Date.now(),a=SP(e,t.sessionId);e.sql.exec(`INSERT INTO session_entries
547
- (id, session_id, parent_id, sequence, type, role, state,
548
- request_id, work_id, data_json, timestamp, completed_at)
549
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t.id,t.sessionId,n?.id??null,a,t.entry.kind,GN(t.entry),r,WN(t.entry),t.entry.workId,oj(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),WM(e,t.entry.kind===`command`?{sessionId:t.sessionId,activityAt:i,title:HN(e,t.sessionId)}:{sessionId:t.sessionId,activityAt:i}));let o=QN(e,t.sessionId,t.id);if(o===void 0)throw $(`Appended Session entry is unavailable`);return o}function XP(e,t){let n=$N(e,wP(e,t.sessionId)),r=QN(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?SP(e,t.sessionId):r?.sequence??SP(e,t.sessionId),c=r?.timestamp??i;if(t.id!==t.entry.message.value)throw $(`Completed message identity does not match its row`);if(r!==void 0){let e=r.entry;if(e.kind!==`message_start`&&e.kind!==`message`)throw $(`Completed Session leaf is not a message entry`);if(e.workId!==t.entry.workId||!KN(e.run,t.entry.run)||!KN(e.turn,t.entry.turn)||!KN(e.message,t.entry.message)||e.kind===`message_start`&&e.role!==t.entry.value.role)throw $(`Completed message does not match its placeholder`)}e.sql.exec(`INSERT OR REPLACE INTO session_entries
550
- (id, session_id, parent_id, sequence, type, role, state,
551
- request_id, work_id, data_json, timestamp, completed_at)
552
- VALUES (?, ?, ?, ?, 'message', ?, 'complete',
553
- NULL, ?, ?, ?, ?)`,t.id,t.sessionId,o,s,GN(t.entry),t.entry.workId,oj(t.entry),c,i),e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,t.id,i,t.sessionId),WM(e,{sessionId:t.sessionId,activityAt:i});let l=QN(e,t.sessionId,t.id);if(l===void 0)throw $(`Completed Session leaf is unavailable`);return l}var ZP=4e3,QP=4194304,$P={selected:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
554
- SELECT id, parent_id, sequence, state
555
- FROM session_entries
556
- WHERE session_id = ? AND id = ?
557
- UNION ALL
558
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state
559
- FROM branch AS child
560
- CROSS JOIN session_entries AS parent
561
- WHERE parent.id = child.parent_id AND parent.session_id = ?
562
- AND child.sequence > ?
563
- AND +parent.sequence < child.sequence
564
- )`,fork:`WITH RECURSIVE branch (id, parent_id, sequence, state) AS (
565
- SELECT id, parent_id, sequence, state
566
- FROM session_entries
567
- WHERE session_id = ? AND id = ? AND state != 'streaming'
568
- UNION
569
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state
570
- FROM branch AS child
571
- CROSS JOIN session_entries AS parent
572
- WHERE parent.id = child.parent_id AND parent.session_id = ?
573
- AND child.sequence > ?
574
- AND parent.state != 'streaming'
575
- )`},eF={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`}},tF=O(F({id:rN,parent_id:z(N),sequence:iN,state:R([`complete`,`streaming`])}),tN),nF=new WeakMap;function rF(e,t,n,r=2**53-1){let i=nF.get(e);nF.set(e,{sessionId:t,before:r,encoded:new Map});try{return e.transactionSync(n)}finally{i===void 0?nF.delete(e):nF.set(e,i)}}function iF(e,t,n){return nF.get(e)?.sessionId===t?n():e.transactionSync(n)}function aF(e,t,n,r){let i=nF.get(e);if(i?.sessionId!==t)return;i.ancestry??=e.sql.exec(`WITH RECURSIVE read_window (before_sequence, rows) AS (VALUES (?, ?)),
576
- ancestry (id, parent_id, sequence, state, head, context_closed, taken) AS (
577
- SELECT id, parent_id, sequence, state,
578
- ${NF(`session_entries`)}, 0,
579
- CASE WHEN state != 'streaming'
580
- AND sequence < (SELECT before_sequence FROM read_window)
581
- THEN 1 ELSE 0 END
582
- FROM session_entries INDEXED BY idx_session_entries_ancestry
583
- WHERE session_id = ? AND id = ?
584
- UNION ALL
585
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
586
- COALESCE(child.head, ${NF(`parent`)}),
587
- child.context_closed OR
588
- (child.head IS child.id AND child.state != 'streaming'),
589
- child.taken + CASE WHEN parent.state != 'streaming'
590
- AND parent.sequence < (SELECT before_sequence FROM read_window)
591
- THEN 1 ELSE 0 END
592
- FROM ancestry AS child
593
- CROSS JOIN session_entries AS parent INDEXED BY idx_session_entries_ancestry
594
- WHERE parent.id = child.parent_id AND parent.session_id = ?
595
- AND +parent.sequence < child.sequence
596
- AND (child.taken < (SELECT rows FROM read_window)
597
- OR (child.context_closed = 0
598
- AND (child.head IS NOT child.id OR child.state = 'streaming')))
599
- )
600
- SELECT id, parent_id, sequence, state FROM ancestry
601
- WHERE context_closed = 0
602
- OR sequence <= (SELECT before_sequence FROM read_window)
603
- ORDER BY sequence DESC`,i.before,201,t,n,t).toArray().map(e=>{let t=tF(e);if(t._tag===`Failure`)throw $(`Stored Session ancestry is invalid`);return t.success});let a=i.ancestry.findIndex(({id:e})=>e===n);if(a===-1)return;let o=i.ancestry.slice(a);if(r!==void 0){let e=o.at(-1);if(e!==void 0&&e.parent_id!==null&&e.sequence>r.floor+1)return;let t=r.ceiling??2**53-1;for(let e=1;e<o.length;e+=1){let n=o[e-1],i=o[e];if(n!==void 0&&i!==void 0&&n.parent_id!==i.id&&r.floor<n.sequence-1&&t>i.sequence)return}}let s=i.encoded.get(n);if(s!==void 0)return s;let c=JSON.stringify(o);return i.encoded.set(n,c),c}function oF(e){return`${e} AS MATERIALIZED (
604
- SELECT json_extract(value, '$.id') AS id,
605
- json_extract(value, '$.parent_id') AS parent_id,
606
- json_extract(value, '$.sequence') AS sequence,
607
- json_extract(value, '$.state') AS state
608
- FROM json_each(?)
609
- )`}var sF=U.pipe(B(H(0))),cF=O(F({length:sF,root_id:z(rN),root_parent_id:z(N),broken:sF,newest_id:z(rN),newest_sequence:z(iN)}),tN),lF=O(F({sequence:iN}),tN),uF=O(F({work_id:rN}),tN),dF=O(F({work_id:rN,diagnostic:N}),tN);function fF(e,t,n,r,...i){let a=t.walk===`selected`?aF(e,t.sessionId,t.tipId,n):void 0;return a===void 0?e.sql.exec(`${$P[t.walk]} ${r}`,t.sessionId,t.tipId,t.sessionId,n.floor,...i).toArray():e.sql.exec(`WITH ${oF(`branch`)} ${r}`,a,...i).toArray()}function pF(e,t,n,r){let i=eF[r],a=cF(e.sql.exec(`${$P[r]},
610
- kept AS MATERIALIZED (
611
- SELECT id, parent_id, sequence FROM branch
612
- WHERE state != 'streaming'
613
- ),
614
- links AS (
615
- SELECT parent_id, LAG(id) OVER (ORDER BY sequence) AS previous
616
- FROM kept
617
- )
618
- SELECT
619
- (SELECT COUNT(*) FROM kept) AS length,
620
- (SELECT id FROM kept ORDER BY sequence ASC LIMIT 1) AS root_id,
621
- (SELECT parent_id FROM kept ORDER BY sequence ASC LIMIT 1)
622
- AS root_parent_id,
623
- (SELECT COUNT(*) FROM links
624
- WHERE previous IS NOT NULL AND parent_id IS NOT previous) AS broken,
625
- (SELECT id FROM kept ORDER BY sequence DESC LIMIT 1) AS newest_id,
626
- (SELECT sequence FROM kept ORDER BY sequence DESC LIMIT 1)
627
- AS newest_sequence`,t,n,t,0).one());if(a._tag===`Failure`)throw $(`Stored Session lineage check is invalid`);let o=a.success;if(o.length===0||o.root_id===null||o.newest_id===null||o.newest_sequence===null)throw $(i.empty);if(o.root_parent_id!==null)throw $(i.missingParent);if(o.broken!==0)throw $(i.invalid);return Object.freeze({sessionId:t,walk:r,tipId:n,rootId:o.root_id,newestId:o.newest_id,newestSequence:o.newest_sequence})}var mF=O(F({state:R([`complete`,`streaming`]),newest_sequence:iN,root_id:z(rN),root_parent_id:z(N)}),tN);function hF(e,t){let n=ZN(e,t.sessionId),r=t.leafId??n?.leaf_id;if(r==null)return;let i=eF.selected,a=e.sql.exec(`SELECT tip.state AS state, tip.sequence AS newest_sequence,
628
- root.id AS root_id, root.parent_id AS root_parent_id
629
- FROM session_entries AS tip
630
- LEFT JOIN (
631
- SELECT id, parent_id FROM session_entries
632
- WHERE session_id = ? AND state = 'complete'
633
- ORDER BY sequence ASC LIMIT 1
634
- ) AS root
635
- WHERE tip.session_id = ? AND tip.id = ?`,t.sessionId,t.sessionId,r).toArray()[0];if(a===void 0)throw $(i.empty);let o=mF(a);if(o._tag===`Failure`)throw $(`Stored Session lineage ends are invalid`);if(o.success.state!==`complete`||o.success.root_id===null)throw $(i.empty);if(o.success.root_parent_id!==null)throw $(i.missingParent);return Object.freeze({sessionId:t.sessionId,walk:`selected`,tipId:r,rootId:o.success.root_id,newestId:r,newestSequence:o.success.newest_sequence})}function gF(e,t,n,r){let i=Object.freeze(fF(e,t,{floor:n-1,ceiling:r},`SELECT ${FN}
636
- FROM session_entries
637
- WHERE session_id = ? AND state != 'streaming'
638
- AND sequence BETWEEN ? AND ?
639
- AND id IN (SELECT id FROM branch)
640
- ORDER BY sequence ASC`,t.sessionId,n,r).map(t=>qN(e,t))),a=eF.selected,o=i[0];if(o!==void 0&&o.parentId!==null&&o.sequence!==n)throw $(a.missingParent);let s;for(let e of i){if(s!==void 0&&e.parentId!==s.id)throw $(a.invalid);s=e}return i}var _F=O(F({sizes:W(I(cm([iN,sF]))),deepest_parent:z(N),deepest_sequence:z(iN)}),tN);function vF(e,t,n,r,i,a){let o=t.walk===`selected`?aF(e,t.sessionId,t.tipId):void 0;if(o!==void 0){let s=nF.get(e)?.ancestry?.filter(e=>e.sequence<=t.newestSequence&&e.state!==`streaming`&&e.sequence>r&&e.sequence<i),c=n===`newest`?s?.[a-1]:void 0;o=aF(e,t.sessionId,t.tipId,{floor:c===void 0?r:c.sequence-1,ceiling:i-1})}let s=n===`newest`?`DESC`:`ASC`,c=`SELECT
641
- (SELECT json_group_array(json_array(sequence, bytes)) FROM (
642
- SELECT sequence, octet_length(data_json) AS bytes
643
- FROM session_entries
644
- WHERE ${n===`newest`?``:`session_id = ? AND`}
645
- state != 'streaming'
646
- AND sequence > ? AND sequence < ?
647
- AND id IN (SELECT id FROM ${o===void 0?`branch`:`candidates`})
648
- ORDER BY sequence ${s}
649
- LIMIT ?)) AS sizes,
650
- (SELECT parent_id FROM branch ORDER BY sequence ASC LIMIT 1)
651
- AS deepest_parent,
652
- (SELECT sequence FROM branch ORDER BY sequence ASC LIMIT 1)
653
- AS deepest_sequence`,l=e=>`CASE WHEN ${e}.state != 'streaming'
654
- AND ${e}.sequence < ? AND ${e}.sequence > ?
655
- THEN 1 ELSE 0 END`,u=_F((o===void 0?n===`newest`?e.sql.exec(`WITH RECURSIVE branch (id, parent_id, sequence, state, taken) AS (
656
- SELECT id, parent_id, sequence, state,
657
- ${l(`session_entries`)}
658
- FROM session_entries
659
- WHERE session_id = ? AND id = ?
660
- UNION ALL
661
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
662
- child.taken + ${l(`parent`)}
663
- FROM branch AS child
664
- CROSS JOIN session_entries AS parent
665
- WHERE parent.id = child.parent_id AND parent.session_id = ?
666
- AND +parent.sequence < child.sequence
667
- AND child.taken < ? AND child.sequence > ?
668
- )
669
- ${c}`,i,r,t.sessionId,t.tipId,i,r,t.sessionId,a,r,r,i,a).toArray():fF(e,t,{floor:r},c,t.sessionId,r,i,a):e.sql.exec(`WITH ${oF(`branch`)},
670
- candidates AS MATERIALIZED (
671
- SELECT id FROM branch
672
- WHERE state != 'streaming' AND sequence > ? AND sequence < ?
673
- ORDER BY sequence ${s} LIMIT ?
674
- ) ${c}`,o,r,i,a,...n===`newest`?[]:[t.sessionId],r,i,a).toArray())[0]);if(u._tag===`Failure`)throw $(`Stored Session entry size is invalid`);let{sizes:d,deepest_parent:f,deepest_sequence:p}=u.success;if(!(f===null||p===null||p<=r||n===`newest`&&d.length===a))throw $(eF.selected.missingParent);return Object.freeze(d.map(([e,t])=>({sequence:e,bytes:t})).sort((e,t)=>n===`newest`?t.sequence-e.sequence:e.sequence-t.sequence))}function yF(e,t,n){let r=vF(e,t,n.from,n.after??0,n.before??2**53-1,n.rows+1),i=0,a=0;for(let e of r){if(i===n.rows||i>0&&a+e.bytes>QP)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:gF(e,t,Math.min(o.sequence,s.sequence),Math.max(o.sequence,s.sequence)),more:r.length>i})}function bF(e,t,n){return fF(e,t,{floor:n-1,ceiling:n},`SELECT 1 AS present
675
- FROM session_entries
676
- WHERE session_id = ? AND state != 'streaming' AND sequence = ?
677
- AND id IN (SELECT id FROM branch)`,t.sessionId,n).length>0}function xF(e,t,n){let r=e.sql.exec(`SELECT sequence FROM session_entries
678
- WHERE session_id = ? AND id = ? AND state != 'streaming'`,t.sessionId,n).toArray()[0];if(r===void 0)return;let i=lF(r);if(i._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return bF(e,t,i.success.sequence)?i.success.sequence:void 0}function SF(e,t,n){let[r]=OF(e,t,n,`SELECT id, sequence FROM session_entries
679
- WHERE session_id = ? AND type = 'model_preference'
680
- AND state != 'streaming'`,[t],e=>`${e}.id NOT IN (SELECT id FROM targets)
681
- AND ${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return r===void 0?void 0:QN(e,t,r)}function CF(e,t,n){let r=SF(e,t,n)?.entry;return r?.kind===`model_preference`?r.preference:null}function wF(e,t,n,r){if(t===void 0)return;let i=fF(e,t,{floor:0},`SELECT ${FN}
682
- FROM session_entries
683
- WHERE session_id = ? AND state != 'streaming' AND type = 'document'
684
- AND json_extract(data_json, '$.extensionId') = ?
685
- AND json_extract(data_json, '$.name') = ?
686
- AND id IN (SELECT id FROM branch)
687
- ORDER BY sequence DESC
688
- LIMIT 1`,t.sessionId,n,r)[0],a=i===void 0?void 0:qN(e,i).entry;if(a!==void 0){if(a.kind!==`document`||a.extensionId!==n||a.name!==r)throw $(`Stored Session document disagrees with its row`);return a.valueJson}}var TF=O(F({oldest:z(iN),newest:z(iN)}),tN);function EF(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=TF(e.sql.exec(`SELECT MIN(oldest) AS oldest, MAX(newest) AS newest FROM (
689
- SELECT MIN(sequence) AS oldest, MAX(sequence) AS newest
690
- FROM session_entries INDEXED BY idx_session_entries_work
691
- WHERE work_id IN (SELECT value FROM json_each(?))
692
- AND session_id = ?
693
- UNION ALL
694
- SELECT MIN(sequence), MAX(sequence) FROM session_entries
695
- INDEXED BY idx_session_entries_cancellation_target
696
- WHERE session_id = ? AND type = 'cancellation'
697
- AND json_extract(data_json, '$.targetWorkId')
698
- IN (SELECT value FROM json_each(?))
699
- )`,r,t.sessionId,t.sessionId,r).one());if(i._tag===`Failure`)throw $(`Stored Session work order is invalid`);if(i.success.oldest===null||i.success.newest===null)return Object.freeze({commands:new Set,diagnostics:new Map,cancellations:new Map});let a=i.success.oldest-1,o={floor:a,ceiling:i.success.newest},s=new Set(fF(e,t,o,`SELECT DISTINCT work_id
700
- FROM session_entries
701
- WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'command'
702
- AND work_id IN (SELECT value FROM json_each(?))
703
- AND id IN (SELECT id FROM branch)`,t.sessionId,a,r).map(e=>{let t=uF(e);if(t._tag===`Failure`)throw $(`Stored Session command work is invalid`);return t.success.work_id})),c=new Map;for(let n of fF(e,t,o,`SELECT work_id, diagnostic FROM (
704
- SELECT work_id, sequence,
705
- json_extract(data_json, '$.diagnostic') AS diagnostic
706
- FROM session_entries
707
- WHERE session_id = ? AND sequence > ? AND state != 'streaming'
708
- AND work_id IN (SELECT value FROM json_each(?))
709
- AND type IN ('work_terminal', 'run_terminal')
710
- AND id IN (SELECT id FROM branch)
711
- )
712
- WHERE diagnostic IS NOT NULL
713
- ORDER BY sequence ASC`,t.sessionId,a,r)){let e=dF(n);if(e._tag===`Failure`)throw $(`Stored Session diagnostic is invalid`);c.set(e.success.work_id,e.success.diagnostic)}let l=new Map;for(let{entry:n}of fF(e,t,o,`SELECT ${FN}
714
- FROM session_entries
715
- WHERE session_id = ? AND sequence > ? AND state != 'streaming' AND type = 'cancellation'
716
- AND json_extract(data_json, '$.targetWorkId')
717
- IN (SELECT value FROM json_each(?))
718
- AND id IN (SELECT id FROM branch)
719
- ORDER BY sequence ASC`,t.sessionId,a,r).map(t=>qN(e,t)))n.kind===`cancellation`&&n.meta!==void 0&&l.set(n.targetWorkId,n.meta);return Object.freeze({commands:s,diagnostics:c,cancellations:l})}function DF(e,t,n,r){return r===void 0?{sql:`walk (id, parent_id, sequence, state) AS (
720
- SELECT id, parent_id, sequence, state
721
- FROM session_entries
722
- WHERE session_id = ? AND id = ?
723
- UNION ALL
724
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state
725
- FROM walk AS child
726
- CROSS JOIN session_entries AS parent
727
- WHERE parent.id = child.parent_id AND parent.session_id = ?
728
- AND +parent.sequence < child.sequence
729
- AND ${n}
730
- )`,bindings:[e,t,e],recursive:!0}:{sql:`${oF(`ancestors`)},
731
- stopped AS (
732
- SELECT child.*,
733
- COALESCE(SUM(CASE WHEN ${n} THEN 0 ELSE 1 END)
734
- OVER (ORDER BY child.sequence DESC
735
- ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 0) AS stops
736
- FROM ancestors AS child
737
- ),
738
- walk AS (
739
- SELECT id, parent_id, sequence, state FROM stopped WHERE stops = 0
740
- )`,bindings:[r],recursive:!1}}function OF(e,t,n,r,i,a){let o=aF(e,t,n),s=o=>{let s=DF(t,n,a(`child`),o);return e.sql.exec(`WITH ${s.recursive?`RECURSIVE `:``}targets AS MATERIALIZED (
741
- ${r}
742
- ),
743
- ${s.sql}
744
- ${kF(a(`walk`))}`,...i,...s.bindings).toArray()},c=s(o);if(o!==void 0){let r=c.at(-1);if(r!==void 0){let i=jF(r);if(i._tag===`Failure`)throw $(`Stored Session walk row is invalid`);(i.success.continues===1&&i.success.parent_id!==null||aF(e,t,n,{floor:i.success.sequence-1})===void 0)&&(c=s(void 0))}}return MF(c)}function kF(e){return`SELECT id, parent_id, sequence, target, continues FROM (
745
- SELECT id, parent_id, sequence,
746
- id IN (SELECT id FROM targets) AS target,
747
- COALESCE((${e}), 0) AS continues
748
- FROM walk
749
- )
750
- WHERE target = 1 OR sequence = (SELECT MIN(sequence) FROM walk)
751
- ORDER BY sequence DESC`}var AF=R([0,1]),jF=O(F({id:rN,parent_id:z(N),sequence:iN,target:AF,continues:AF}),tN);function MF(e){let t=eF.selected;if(e.length===0)throw $(t.empty);let n=e.map(e=>{let t=jF(e);if(t._tag===`Failure`)throw $(`Stored Session walk row is invalid`);return t.success}),r=n.at(-1);if(r?.continues===1&&r.parent_id!==null)throw $(t.missingParent);return n.flatMap(e=>e.target===1?[e.id]:[])}function NF(e){return`CASE WHEN ${e}.type = 'compaction' AND ${e}.state != 'streaming'
752
- THEN json_extract(${e}.data_json, '$.head') END`}var PF=`WITH RECURSIVE walk (id, parent_id, sequence, state, head) AS (
753
- SELECT id, parent_id, sequence, state,
754
- ${NF(`session_entries`)}
755
- FROM session_entries
756
- WHERE session_id = ? AND id = ?
757
- UNION ALL
758
- SELECT parent.id, parent.parent_id, parent.sequence, parent.state,
759
- COALESCE(child.head, ${NF(`parent`)})
760
- FROM walk AS child
761
- CROSS JOIN session_entries AS parent
762
- WHERE parent.id = child.parent_id AND parent.session_id = ?
763
- AND +parent.sequence < child.sequence
764
- AND (child.head IS NOT child.id OR child.state = 'streaming')
765
- )`;function FF(e,t,n,r,i){let a=JSON.stringify(r.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[])),o=OF(e,t,n.id,`SELECT id, sequence FROM session_entries
766
- WHERE session_id = ? AND type = 'compaction' AND work_id = ?
767
- AND sequence < ? AND state != 'streaming'
768
- UNION ALL
769
- SELECT id, sequence
770
- FROM session_entries
771
- INDEXED BY idx_session_entries_cancellation_target
772
- WHERE session_id = ? AND type = 'cancellation'
773
- AND json_extract(data_json, '$.targetWorkId')
774
- IN (SELECT value FROM json_each(?))
775
- AND sequence < ? AND state != 'streaming'`,[t,i,n.sequence,t,a,n.sequence],e=>`${e}.sequence > (SELECT MIN(sequence) FROM targets)`);return o.length===0?Object.freeze([]):Object.freeze(e.sql.exec(`SELECT ${FN}
776
- FROM session_entries
777
- WHERE id IN (SELECT value FROM json_each(?))
778
- ORDER BY sequence ASC`,JSON.stringify(o)).toArray().map(t=>qN(e,t)))}function IF(e,t,n){let r=eF.selected,i=aF(e,t,n);nF.get(e)?.ancestry?.[0]?.id!==n&&(i=void 0);let a=i===void 0?{sql:PF,bindings:[t,n,t]}:{sql:`WITH ${oF(`ancestors`)},
779
- boundary AS (
780
- SELECT sequence, json_extract(data_json, '$.head') AS head
781
- FROM session_entries
782
- WHERE session_id = ? AND type = 'compaction'
783
- AND state != 'streaming'
784
- AND id IN (SELECT id FROM ancestors)
785
- ORDER BY sequence DESC LIMIT 1
786
- ),
787
- walk AS (
788
- SELECT * FROM ancestors
789
- WHERE sequence >= COALESCE((
790
- SELECT ancestors.sequence FROM ancestors, boundary
791
- WHERE ancestors.id = boundary.head
792
- AND ancestors.state != 'streaming'
793
- AND ancestors.sequence <= boundary.sequence
794
- ), 0)
795
- )`,bindings:[i,t]},o=e.sql.exec(`${a.sql}
796
- SELECT ${FN}
797
- FROM session_entries
798
- WHERE id IN (SELECT id FROM walk) AND state != 'streaming'
799
- ORDER BY sequence ASC`,...a.bindings).toArray().map(t=>qN(e,t)),s=o[0];if(s===void 0)throw $(r.empty);let c,l;for(let e of o){if(l!==void 0&&e.parentId!==l.id)throw $(r.invalid);e.entry.kind===`compaction`&&(c=e.entry.head),l=e}let u=c===s.id;if(!u&&s.parentId!==null)throw $(r.missingParent);return Object.freeze({rows:Object.freeze(o),compacted:u})}function LF(e,t){let n=ZN(e,t.sessionId)?.leaf_id;if(n==null)return Object.freeze([]);let r=IF(e,t.sessionId,n),i=r.rows[0];return!r.compacted||i===void 0?r.rows:Object.freeze([...FF(e,t.sessionId,i,r.rows,t.workId??null),...r.rows])}function RF(e,t,n){return e.entry.kind===`compaction`&&e.entry.workId===t||e.entry.kind===`cancellation`&&n.has(e.entry.targetWorkId)}function zF(e,t,n,r,i){let a=hF(e,{sessionId:t,leafId:n.id});if(a===void 0)throw $(`Accepted Session command lineage is unavailable`);let o=r===void 0?[]:fF(e,r,{floor:n.sequence},`SELECT ${FN}
800
- FROM session_entries
801
- WHERE session_id = ? AND sequence > ? AND state != 'streaming'
802
- AND id IN (SELECT id FROM branch)
803
- AND (work_id = ?
804
- OR (type = 'command'
805
- AND json_extract(data_json, '$.targetWorkId') = ?))
806
- ORDER BY sequence ASC`,t,n.sequence,i,i).map(t=>qN(e,t)),s;for(let e of o)e.entry.kind===`compaction`&&(s=e.entry.head);let c=0,l;if(s===void 0){let r=IF(e,t,n.id);l=r.rows,r.compacted&&(c=r.rows[0]?.sequence??0)}else{let t=s;c=o.find(({id:e})=>e===t)?.sequence??xF(e,a,t)??0,l=c>n.sequence?[]:gF(e,a,Math.max(c,1),n.sequence)}if(c===0)return Object.freeze([...l,...o]);let u=[...l,...o.filter(({sequence:e})=>e>=c)],d=new Set(u.flatMap(({entry:e})=>e.kind===`command`?[e.workId]:[]));return Object.freeze([...FF(e,t,l[0]??n,u,i),...o.filter(e=>e.sequence<c&&RF(e,i,d)),...u])}function BF(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 VF(e,t){let n=BF(e),r;for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.entry.kind===`compaction`){r=n;break}}let i=r?.entry.kind===`compaction`?r.entry:void 0,a=i===void 0?-1:e.findIndex(({id:e})=>e===i.head),o=a>=0?e.slice(a):e,s=$M(o,t),c=[];i!==void 0&&c.push(...i.model);for(let e of o){let t=ej(e.entry);t!==void 0&&!n.has(t.workId)&&c.push(rj(t)),e.entry.kind===`operator`&&c.push(nj(e.entry)),e.entry.kind===`message`&&s.has(e.id)&&c.push(e.entry.value)}return Object.freeze(c)}function HF(e,t){return e.transactionSync(()=>{let n=QN(e,t.sessionId,t.commandFactId),r=`replay`,i=mP(e,t.sessionId,t.commandFactId);if(n===void 0&&i!==void 0&&(n=YP(e,{sessionId:i.sessionId,id:i.id,entry:i.entry}),r=`new`),n?.entry.kind!==`command`)throw $(`Accepted Session command is unavailable`);if(i!==void 0&&oj(n.entry)!==oj(i.entry))throw $(`Accepted Session command disagrees with its admission`);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 a=vP(e,t.sessionId,n.entry.workId),o=n.entry.workId,s=hF(e,{sessionId:t.sessionId}),c=zF(e,t.sessionId,n,s,o),l=Object.freeze({...n,entry:n.entry});return Object.freeze({command:l,modelPreference:CF(e,t.sessionId,n.id),messages:VF(c,n.entry.workId),path:c,entryDelivery:r,resume:QM(a),abnormalTerminal:eN(a)})})}function UF(e,t){let n=ZN(e,t.sessionId)?.leaf_id;if(n==null)return`stale`;let r=e.sql.exec(`${PF}
807
- SELECT sequence
808
- FROM session_entries
809
- WHERE state != 'streaming' AND id = ? AND id IN (SELECT id FROM walk)`,t.sessionId,n,t.sessionId,t.head).toArray()[0];if(r===void 0)return`stale`;if(lF(r)._tag===`Failure`)throw $(`Stored Session entry sequence is invalid`);return`current`}function WF(e,t){return e.transactionSync(()=>{let n={kind:`compaction_notice`,workId:t.workId,trigger:t.trigger},r;if(t.result===`stale`||t.result===`insufficient`){let e={...n,result:t.result};r=t.usage===void 0?e:{...e,usage:t.usage}}else if(t.result===`failed`){let e={...n,result:`failed`},i=t.diagnostic===void 0?e:{...e,diagnostic:t.diagnostic.slice(0,200)};r=t.usage===void 0?i:{...i,usage:t.usage}}else{let e={...n,result:`nothing_to_compact`};r=t.diagnostic===void 0?e:{...e,diagnostic:t.diagnostic.slice(0,200)}}return YP(e,{sessionId:t.sessionId,id:ZM.fact.generate(),entry:r})})}function GF(e,t){return e.transactionSync(()=>qF(e,t))}function KF(e,t){return e.transactionSync(()=>UF(e,{sessionId:t.sessionId,head:t.head})===`stale`?`stale`:qF(e,t))}function qF(e,t){if(ZN(e,t.sessionId)?.leaf_id!==t.expectedLeafId)throw new G(`store`,`conflict`,`Session leaf changed during compaction`);let n={kind:`compaction`,workId:t.workId,head:t.head,model:[Kj(t.summary,Date.now())],data:{reason:t.trigger,resumesRun:t.resumesRun??!1,tokensBefore:t.tokensBefore,tokensAfter:t.tokensAfter,usage:t.usage,contextRevision:t.contextRevision}},r=t.receipt===void 0?n:{...n,data:{...n.data,receipt:t.receipt}};return YP(e,{sessionId:t.sessionId,id:ZM.fact.generate(),entry:t.details===void 0?r:{...r,data:{...r.data,details:t.details}}})}function JF(e){return Array.isArray(e)}function YF(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 XF(e,t){return!JF(e)||!JF(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 ZF(e,t){if(t.type===`compact`)return $A(e)&&e.instructions===t.instructions;let n=ej(e);return n?.delivery===t.delivery&&XF(n.message.content,YF(t))}function QF(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:YF(e),timestamp:n},contract:r},c=i===void 0?s:{...s,targetWorkId:i};return a===void 0?c:{...c,reply:a}}function $F(e,t){return e?.agentId===t?.agentId&&e?.sessionId===t?.sessionId&&e?.outcome===t?.outcome&&(e?.outcome===`undeliverable`?t?.outcome===`undeliverable`&&e.reason===t.reason:t?.outcome!==`undeliverable`&&e?.commandId===t?.commandId&&e?.diagnostic===t?.diagnostic)}function eI(e,t,n,r,i,a,o,s,c){let l=gP(e,t,n.requestId);if(l!==void 0){if(!ZF(l.entry,n)||!zO(l.entry.meta,r)||!$F(ej(l.entry)?.reply,c)||!bN(l.origin,i))throw new G(`contract`,`conflict`,`Request id conflicts with an accepted Session command`);return rI(l,`replay`)}let u=ZM.fact.generate();wP(e,t);let d=Date.now(),f=QF(n,u,d,a,s,c);e.sql.exec(`INSERT INTO session_command_admissions
810
- (id, session_id, sequence, request_id, work_id, data_json, timestamp,
811
- origin_kind, origin_id, origin_correlation)
812
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,u,t,CP(e,t),n.requestId,u,oj(IN(f,r)),d,i.kind,i.kind===`user`?null:i.extensionId,i.kind===`user`?null:i.correlation);let p=mP(e,t,u);if(p===void 0)throw $(`Accepted Session command admission is unavailable`);return o?.({jobId:u,sessionId:t,commandFactId:u,delivery:n.type===`prompt`?n.delivery:`followUp`}),rI(p,`new`)}function tI(e,t,n){if(e.sql.exec(`SELECT 1 FROM session_request_withdrawals WHERE session_id = ? AND request_id = ?`,t,n).toArray().length>0)throw new G(`contract`,`closed`,`Request was withdrawn`,n)}function nI(e,t,n){let r=gP(e,t,n);if(r!==void 0)return{status:`accepted`,commandId:r.id};let i=e.sql.exec(`SELECT id FROM session_entries WHERE session_id = ? AND request_id = ? AND type = 'operator'`,t,n).toArray()[0];if(i!==void 0){let e=EN(i);if(e._tag===`Failure`)throw $(`Stored operator receipt is invalid`);return{status:`accepted`,commandId:e.success.id}}return e.sql.exec(`INSERT OR IGNORE INTO session_request_withdrawals(session_id, request_id) VALUES (?, ?)`,t,n),{status:`unknown`}}function rI(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 iI(e,t,n){if(e.entry.kind!==`cancellation`)throw $(`Accepted Session cancellation is unavailable`);return Object.freeze({accepted:Object.freeze({commandId:e.entry.targetWorkId,entryId:e.id}),delivery:t,active:n})}function aI(e,t,n,r,i){return e.transactionSync(()=>{let a=n(),o=a.state===`running`?hP(e,t,a.jobId):void 0,s=o===void 0?void 0:sI(e,t,o.id,n,r,!1,i);for(let a=CP(e,t);a>0;){let{commands:o}=lP(e,t,64);if(o.length===0)return s;a-=o.length;for(let a of o){if(sI(e,t,a.id,n,r,!1,i,!0)===void 0)throw $(`Pending Session command could not be cancelled`);YP(e,{sessionId:t,id:a.id,entry:a.entry})}}throw $(`Session cancellation did not settle its pending admissions`)})}function oI(e,t,n,r,i,a=!1,o){return e.transactionSync(()=>sI(e,t,n,r,i,a,o))}function sI(e,t,n,r,i,a=!1,o,s=!1){let c=r(),l=mP(e,t,n);if(l?.entry.kind!==`command`)return;let u=vP(e,t,l.entry.workId),d=u.find(({entry:e})=>e.kind===`cancellation`);if(d?.entry.kind===`cancellation`)return iI(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`))||ej(l.entry)?.delivery===`steer`&&u.some(({entry:e})=>e.kind===`command`)&&!f)return;let p=ZM.fact.generate(),m=i({jobId:l.entry.workId,cancellationId:p,onlyIfPending:a});if(m.status===`missing`&&ej(l.entry)?.delivery!==`steer`&&!s||m.status===`conflict`&&a)return;if(m.status!==`recorded`&&m.status!==`missing`)throw new G(`store`,`conflict`,`Session cancellation identity conflicts`);let ee=YP(e,{sessionId:t,id:p,entry:IN({kind:`cancellation`,requestId:p,receiptId:p,workId:l.entry.workId,targetWorkId:l.entry.workId},o)});return m.status===`missing`&&YP(e,{sessionId:t,id:ZM.fact.generate(),entry:{kind:`work_terminal`,workId:l.entry.workId,outcome:`cancelled`}}),iI(ee,`new`,f)}function cI(e,t){e.transactionSync(()=>{t.assertIdleSession?.(t.sessionId);let n=ZN(e,t.sessionId);if(n===void 0)throw $(`Session is unavailable for branch selection`);$N(e,n);let r=QN(e,t.sessionId,t.entryId);if(r?.state!==`complete`)throw $(`Selected branch entry is unavailable`);let i=Date.now();e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,r.id,i,n.id),WM(e,{sessionId:n.id,activityAt:i,title:HN(e,n.id)})})}function lI(e,t){return e.transactionSync(()=>{if(tI(e,t.sessionId,t.requestId),ZN(e,t.sessionId)===void 0)throw $(`Session is unavailable for an operator entry`);let n=e.sql.exec(`SELECT id FROM session_entries WHERE session_id = ? AND request_id = ?`,t.sessionId,t.requestId).toArray()[0];if(n!==void 0){let r=EN(n);if(r._tag===`Failure`)throw $(`Stored Session entry identity is invalid`);let i=QN(e,t.sessionId,r.success.id);if(i?.entry.kind===`operator`&&i.entry.author===t.author&&zO(i.entry.meta,t.meta)&&i.entry.message.content===t.text)return!1;throw new G(`store`,`conflict`,`Request id already names another Session entry`)}t.assertIdleSession(t.sessionId);let r={kind:`operator`,workId:null,requestId:t.requestId,author:t.author,message:{role:`user`,content:t.text,timestamp:Date.now()}};return YP(e,{sessionId:t.sessionId,id:ZM.fact.generate(),entry:IN(r,t.meta)}),!0})}function uI(e,t){return e.transactionSync(()=>{if(t.assertIdleSession?.(t.sessionId),ZN(e,t.sessionId)===void 0)throw $(`Source Session is unavailable`);let n=pF(e,t.sessionId,t.entryId,`fork`),r=ZM.session.generate(),i=Date.now();e.sql.exec(`INSERT INTO sessions
813
- (id, cwd, parent_session, leaf_id, created_at, updated_at, metadata_json)
814
- VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),SM(e,t.sessionId,r);let a=null,o=null,s=1,c=new Map,l=0;for(;;){let t=yF(e,n,{after:l,from:`oldest`,rows:ZP});for(let n of t.rows){let t=ZM.fact.generate();c.set(n.id,t);let i=n.entry.kind===`compaction`?{...n.entry,head:c.get(n.entry.head)??(()=>{throw $(`Fork compaction boundary is unavailable`)})()}:n.entry;e.sql.exec(`INSERT INTO session_entries
815
- (id, session_id, parent_id, sequence, type, role, state,
816
- request_id, work_id, data_json, timestamp, completed_at)
817
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,GN(i),n.state,WN(i),i.workId,oj(i),n.timestamp,n.completedAt),a=t,o=t,s+=1,l=n.sequence}if(!t.more)break}if(o===null)throw $(`Fork path is empty`);e.sql.exec(`UPDATE sessions SET leaf_id = ?, updated_at = ? WHERE id = ?`,o,i,r);let u=hF(e,{sessionId:t.sessionId});for(let t of Hj(e,(t,n)=>wF(e,u,t,n)))YP(e,{sessionId:r,id:ZM.fact.generate(),entry:t});return WM(e,{sessionId:r,activityAt:i,title:HN(e,r)}),r})}function dI(e,t,n,r){if(ZN(e,t)===void 0)throw $(`Session document owner is unavailable`);return wF(e,hF(e,{sessionId:t}),n,r)}function fI(e,t,n,r,i){if(ZN(e,t)===void 0)throw $(`Session document owner is unavailable`);YP(e,{sessionId:t,id:ZM.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var pI=2097152,mI=200,hI=200,gI=new TextEncoder;function _I(e){return new G(`store`,`unavailable`,e)}function vI(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)mP(e,t,n)!==void 0&&r.set(n,n);return r}function yI(e,t){return n=>{let r=mP(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function bI(e,t,n){return{commandIds:vI(e,t,n),diagnostics:CI(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:yI(e,t)}}function xI(e,t,n,r){let i=EF(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)&&mP(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:yI(e,t)}}function SI(e,t){let n=ej(e.entry);if(n!==void 0){let r=t.origin(n.workId),i={id:e.id,sequence:e.sequence,commandId:n.workId,requestId:n.requestId,value:n.message};return n.meta!==void 0&&(i={...i,meta:n.meta}),r!==void 0&&(i={...i,origin:r}),Object.freeze(i)}if(e.entry.kind===`operator`){let t={id:e.id,sequence:e.sequence,commandId:null,requestId:e.entry.requestId,value:ij(e.entry)};return e.entry.meta!==void 0&&(t={...t,meta:e.entry.meta}),Object.freeze(t)}if(e.entry.kind===`message`){let n={id:e.entry.message.value,sequence:e.sequence,commandId:t.commandIds.get(e.entry.workId)??null,value:e.entry.value};return Object.freeze(e.entry.data===void 0?n:{...n,data:e.entry.data})}}function CI(e){let t=new Map;for(let{entry:n}of e)(n.kind===`work_terminal`||n.kind===`run_terminal`)&&n.diagnostic!==void 0&&t.set(n.workId,n.diagnostic);return t}function wI(e,{commandIds:t,diagnostics:n,cancellations:r}){if(e.entry.kind!==`run_terminal`&&e.entry.kind!==`work_terminal`)return;let i=t.get(e.entry.workId);if(i===void 0)return;let a={commandId:i,outcome:e.entry.outcome,sequence:e.sequence,diagnostic:n.get(e.entry.workId)??null},o=e.entry.outcome===`cancelled`?r.get(e.entry.workId):void 0;return Object.freeze(o===void 0?a:{...a,meta:o})}var TI=new WeakMap;function EI(e){let t=TI.get(e);if(t===void 0)throw _I(`Session compaction entry position is unavailable`);return t}function DI(e,t,n){let r=[];for(let i of n){let a=i.entry;if(a.kind!==`compaction`)continue;let o=n.find(e=>e.id===a.head)?.sequence??xF(e,t,a.head);if(o===void 0)throw _I(`Session compaction horizon is unavailable`);let s=Object.freeze({id:i.id,sequence:o,at:i.timestamp,tokensBefore:a.data.tokensBefore,tokensAfter:a.data.tokensAfter??null,trigger:a.data.reason??null});TI.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function OI(e){return Object.freeze(e.flatMap(({id:e,sequence:t,timestamp:n,entry:r})=>r.kind===`compaction_notice`?[Object.freeze({id:e,sequence:t,at:n,trigger:r.trigger,result:r.result,diagnostic:r.result===`stale`||r.result===`insufficient`?null:r.diagnostic??null})]:[]))}function kI(e){return gI.encode(JSON.stringify(e)).byteLength}function AI(e,t){let n=hA({generation:e,sequence:t});if(n===void 0)throw _I(`Session cursor is unavailable`);return n}function jI(e,t,n,r,i=!1){let a=SI(t,r),o=wI(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:kI(a))+(o===void 0?0:kI(o))+(s===void 0?0:kI(s));if(c>pI)throw _I(`Session projection entry exceeds the read bound`);return e.bytes+c>pI?!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 MI(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==hI;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!jI(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw _I(`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 NI(e){return Array.isArray(e)}function PI(e,t){let{commands:n,total:r}=lP(e,t,hI+1,`prompts`),i=[],a=gI.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=II(e),n=gI.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===hI||a+n>pI)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function FI(e,t,n){let r=sP(e,t,n);return r===void 0?null:II(r)}function II(e){let t=ej(e.entry);if(t===void 0)throw _I(`Pending Session prompt is unavailable`);let n=t.message.content,r=NI(n)?{commandId:e.entry.workId,requestId:t.requestId,text:n.filter(e=>e.type===`text`).map(e=>e.text).join(``),images:n.filter(e=>e.type===`image`),delivery:t.delivery??`followUp`}:{commandId:e.entry.workId,requestId:t.requestId,text:n,delivery:t.delivery??`followUp`},i=e.entry.meta===void 0?r:{...r,meta:e.entry.meta};return e.origin.kind===`extension`?{...i,origin:{extensionId:e.origin.extensionId,correlation:e.origin.correlation}}:i}function LI(e,t,n){let r=gA(n);if(r?.generation===t.rootId)return bF(e,t,r.sequence)?r.sequence:void 0}function RI(e,t,n,r,i=()=>({})){return iF(e,t,()=>{let a=PI(e,t),o=hF(e,{sessionId:t});if(o===void 0)return Object.freeze({sessionId:t,cursor:null,hasMore:!1,oldestCursor:null,messages:Object.freeze([]),terminals:Object.freeze([]),compactions:Object.freeze([]),compactionNotices:Object.freeze([]),pending:a,activity:r.facts,progress:r.readProgress(),toolOutput:r.toolOutput,extensions:i(),attention:mk(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:LI(e,o,n.before);if(c===void 0)throw _I(`Session read cursor is unavailable`);let l=yF(e,o,{before:c,from:`newest`,rows:hI}),u=MI(l.rows,l.more,n.limit,xI(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:AI(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?AI(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:DI(e,o,d),compactionNotices:OI(d),pending:a,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:mk(e,t)};return Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var zI=Object.freeze({kind:`reset`});function BI(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return bF(e,t,n.sequence)?n.sequence:void 0}function VI(e,t,n,r,i,a,o,s,c){let l=yF(e,t,{after:n,from:`oldest`,rows:hI}),u=MI(l.rows,l.more,mI,xI(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:AI(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:DI(e,t,d),compactionNotices:OI(d),pending:s,activity:i.facts,extensions:a,attention:o},m=[Object.freeze(c?{...p,sandboxFailures:u.sandboxFailures}:p)];return Object.freeze({kind:`page`,frames:Object.freeze(u.hasMore?m:[...m,{kind:`tool_output`,toolOutput:i.toolOutput,activity:i.facts}]),hasMore:u.hasMore})}function HI(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:gA(n);return n!==void 0&&s===void 0?zI:iF(e,t,()=>{let c=PI(e,t),l=hF(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:mk(e,t),pending:c}],hasMore:!1}:zI;let u=BI(e,l,s);return u===void 0?zI:VI(e,l,u,r,i,a(),mk(e,t),c,o)})}function UI(e,t,n){let r=mP(e,t,n);if(r===void 0)throw _I(`Accepted Session command is unavailable`);if(!_P(e,t,r.entry.workId))return;let i=vP(e,t,r.entry.workId),a=bI(e,t,i),o=i.flatMap(e=>{let t=wI(e,a);return t===void 0?[]:[t]}).at(-1);if(o===void 0)return;let s=i.flatMap(({entry:e})=>e.kind===`message`&&e.value.role===`assistant`?[e.value]:[]),c=s.at(-1),l=o.outcome===`cancelled`?o.meta:r.entry.meta,u=Zh(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:sA(e,t)?.replyTo[0]?.agentId??null,terminal:l===void 0?o:{...o,meta:l},content:o.outcome===`cancelled`?``:c?.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()??``,usage:s.map(({provider:e,model:t,usage:n})=>({provider:e,model:t,usage:n})),toolCalls:new Set(i.flatMap(({entry:e})=>e.kind===`tool_intent`?[e.call.id]:[])).size,waitingOnYou:Ek(e,t,r.entry.workId)}}var WI=65536,GI=2048,KI=new TextEncoder,qI=()=>({chunks:[],length:0,bytes:0});function JI(e,t){for(let n=0;n<t.length;){let r=Math.min(n+GI,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=KI.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=GI?(s.text+=a,s.bytes+=o):e.chunks.push({offset:e.length,text:a,bytes:o}),e.length+=a.length,e.bytes+=o,n=r;e.bytes>WI&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function YI(e){return e.chunks[0]?.offset??0}function XI(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function ZI(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:XI(e.text,YI(e.text)),thinking:XI(e.thinking,YI(e.thinking)),textOffset:YI(e.text),thinkingOffset:YI(e.thinking),textTruncated:YI(e.text)>0,thinkingTruncated:YI(e.thinking)>0}}function QI(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function $I(e,t,n,r){let i=eL.get(e)?.get(t),a=i?.workId===n?i.value:null;if(a===null)return null;let o=r?.messageId===a.messageId?r:null;if(o!==null&&o.revision>=a.revision)return null;let s=o?.text??0,c=o?.thinking??0;if(!(s<YI(a.text)||c<YI(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:XI(a.text,s)},thinking:{offset:c,append:XI(a.thinking,c)}}}var eL=new WeakMap;function tL(e,t,n){let r=eL.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var nL=O(F({droppedBytes:U.check(H(0)),totalBytes:U.check(H(0))}),{onExcessProperty:`error`});function rL(e,t){return S(function*(){let n=yield*aL(e,t),r=()=>{ek(e,t.sessionId,`progress`)};return{started:e=>w(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>w(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=nL(e.result.data);if(pe(i))return;let a=e.result.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);new TextEncoder().encode(a).byteLength>8192||a.split(`
818
- `).length>200||i.success.droppedBytes>i.success.totalBytes||(n.slots.set(e.toolCall.value,{toolCallId:e.call.id,revision:(t?.revision??0)+1,tail:a,...i.success}),r())}),terminal:e=>w(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function iL(e){let t=eL.get(e);if(t!==void 0)return t;let n=new Map;return eL.set(e,n),n}function aL(e,t){return S(function*(){let n=iL(e),r=n.get(t.sessionId);if(r?.workId===t.commandId)return r;let i={workId:t.commandId,value:null,slots:new Map};return n.set(t.sessionId,i),yield*br(()=>w(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&ek(e,t.sessionId,`progress`))})),i})}function oL(e){return new G(`runtime`,`rejected`,e)}function sL(e,t,n){let r=iL(e).get(t);return ZI(r?.workId===n?r.value:null)}function cL(e,t,n){let r=eL.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function lL(e,t,n){return S(function*(){let r=yield*aL(e,t),i,a=0,o,s=()=>{o!==void 0&&clearTimeout(o),o=void 0},c=()=>{s();let n=r.value;n!==null&&(a=n.text.length+n.thinking.length,ek(e,t.sessionId,`progress`))},l=w(()=>{s();let n=r.value!==null;r.value=null,n&&ek(e,t.sessionId,`progress`),i=void 0});return yield*br(()=>l),Object.freeze({started:e=>w(()=>{s(),i=e,r.value=null,a=0}),update:e=>hr(()=>{let t=i;if(t===void 0)return x(oL(`Mule progress arrived before its message start`));if(t.run.value!==e.run.value||t.turn.value!==e.turn.value||t.message.value!==e.message.value)return x(oL(`Mule progress identity conflicts`));let n=e.event;if(n.type!==`text_delta`&&n.type!==`thinking_delta`||n.delta.length===0)return h;let s=r.value===null,l=r.value??{messageId:e.message.value,revision:0,text:qI(),thinking:qI()};JI(n.type===`text_delta`?l.text:l.thinking,n.delta),l.revision++,r.value=l;let u=l.text.length+l.thinking.length;return s||u-a>=4096?c():o??=setTimeout(c,100),h}),terminal:e=>l.pipe(y(n(e)))})})}var uL=new WeakMap;function dL(e){let t=uL.get(e);if(t!==void 0)return t;let n=new Map;return uL.set(e,n),n}function fL(e,t){return dL(e).get(t)??null}function pL(e,t,n){dL(e).set(t,Object.freeze({trigger:n})),ek(e,t,`progress`)}function mL(e,t){dL(e).delete(t)&&ek(e,t,`progress`)}var hL=Object.freeze({admitNew:()=>{}});function gL(e){return e===void 0?hL:Object.freeze({admitNew:()=>{if(e.underPressure())throw new G(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function _L(e,t){let n=WF(e,t);return ek(e,t.sessionId),n}function vL(e,t){let n=GF(e,t);return ek(e,t.sessionId),n}function yL(e,t){let n=KF(e,t);return n!==`stale`&&ek(e,t.sessionId),n}function bL(e){return new G(`store`,`rejected`,e)}function xL(e){return new G(`store`,`conflict`,e)}function SL(e){return en({try:e,catch:e=>e instanceof G?e:new G(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function CL(e){return SL(()=>{WP(e)})}function wL(e,t,n,r,i,a,o){return SL(()=>{let s=oI(e,t,n,i,a,r,o);return s?.delivery===`new`&&ek(e,t,`settlement`),s})}function TL(e,t){return SL(()=>{let n=fP(e,t.sessionId,t.delivery,t.workId);return n.length>0&&ek(e,t.sessionId),n})}function EL(e,t){return SL(()=>{pP(e,t),ek(e,t.sessionId,`settlement`)})}function DL(e,t,n,r,i){return SL(()=>{let a=aI(e,t,n,r,i);return ek(e,t,`settlement`),a?.accepted})}function OL(e,t){return SL(()=>{cI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),ek(e,t.sessionId)})}function kL(e,t){return SL(()=>{lI(e,t)&&ek(e,t.sessionId)})}function AL(e,t){return SL(()=>{let n=uI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return ek(e,n),Object.freeze({sessionId:n})})}function jL(e,t){return SL(()=>{let n=HF(e,{sessionId:pb(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&ek(e,t.sessionId),n})}function ML(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function NL(e,t){return SL(()=>{let n=mP(e,t.sessionId,t.commandFactId);if(n===void 0)throw bL(`Accepted Session command is unavailable`);let r=vP(e,t.sessionId,n.entry.workId);for(let e=r.length-1;e>=0;--e){let t=r[e]?.entry;if(t?.kind===`message`&&t.value.role===`assistant`){let e=ML(t.value);if(e!==``)return e}}return``})}function PL(e,t){return S(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*NL(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*SL(()=>{let n=mP(e,t.sessionId,i);if(n===void 0)throw bL(`Accepted Session command is unavailable`);if(JL(e,t.sessionId,i,n.entry.workId)===null)return;let r=eP(e,i);if(r===void 0)throw bL(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=eP(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw bL(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function FL(e,t,n){return SL(()=>{let r=mP(e,t.sessionId,t.commandFactId);if(r===void 0)throw bL(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=vP(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function IL(e,t){return SL(()=>{let n=mP(e,t.sessionId,t.commandFactId);if(n===void 0)throw bL(`Accepted Session command is unavailable`);return CI(vP(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function LL(e,t,n,r,i,a){return SL(()=>{let o=pb(t),s=gb(r);return rF(e,o,()=>a(RI(e,o,s,n(),i)),s.before===void 0?void 0:gA(s.before)?.sequence)})}function RL(e,t,n){return SL(()=>TP(e,hb({requestId:t}),n))}function zL(e,t,n){return EP(e,hb({requestId:t}),n)}function BL(e,t){return SL(()=>DP(e,{sessionId:pb(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{GM(e,t)}}))}function VL(e,t){return SL(()=>XM(e,t))}function HL(e,t,n,r,i,a,o,s){return SL(()=>{let c=pb(t);return rF(e,c,()=>s(HI(e,c,n,r,i,a,o)))})}function UL(e,t){return oj(e)===oj(t)}function WL(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function GL(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 KL(e,t,n,r,i){e.transactionSync(()=>{i?.();let a=vP(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||UL(a.entry,n))return`replay`;throw xL(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=ZM.fact.generate();if(eP(e,r)===void 0&&mP(e,t.sessionId,r)===void 0)return YP(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw bL(`Session fact identity allocation failed`)})===`new`&&ek(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`)}function qL(e,t,n){return SL(()=>{KL(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function JL(e,t,n,r){let i=mP(e,t,n);if(i?.entry.workId!==r)throw bL(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function YL(e,t,n,r){let i=JL(e,t,n,r),a=vP(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 XL(e,t){return SL(()=>{if(mP(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw bL(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};KL(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 ZL(e,t,n,r,i){return SL(()=>{let a=r.type===`run_start`?{kind:`run_started`,workId:t.commandId,run:r.run,contract:n}:r.type===`turn_start`?{kind:`turn_started`,workId:t.commandId,run:r.run,turn:r.turn}:{kind:`run_terminal`,workId:t.commandId,run:r.run,terminal:r.terminal,outcome:r.outcome};a.kind===`run_terminal`&&i!==void 0&&(a={...a,diagnostic:i}),KL(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?WL(e.run,a.run)&&GL(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?WL(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&WL(e.terminal,a.terminal):!1)})}function QL(e,t,n){return SL(()=>{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=vP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&WL(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!WL(i.entry.run,r.run)||!WL(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw xL(`Mule message-start identity conflicts`);return`replay`}if(!UL(i.entry,r))throw xL(`Mule message-start identity conflicts`);return`replay`}return YP(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&ek(e,t.sessionId)})}function $L(e,t,n,r){return SL(()=>{KL(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`&&WL(e.turn,r.turn)&&e.attempt===r.attempt&&GL(e.contract,n))})}function eR(e,t,n){return SL(()=>{let r={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value},i=n.data===void 0?r:{...r,data:n.data};e.transactionSync(()=>{let r=vP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&WL(e.message,n.message));if(r?.entry.kind===`message`){if(!UL(r.entry,i))throw xL(`Mule completed-message identity conflicts`);return`replay`}return XP(e,{sessionId:t.sessionId,id:n.message.value,entry:i}),`new`})===`new`&&ek(e,t.sessionId)})}function tR(e,t,n,r){return SL(()=>{KL(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`&&WL(e.toolCall,r.toolCall)&&GL(e.contract,n))})}function nR(e,t,n){return SL(()=>{let{data:r,...i}=n.result,a={kind:`tool_outcome`,workId:t.commandId,run:n.run,turn:n.turn,toolCall:n.toolCall,call:n.call,result:i};KL(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&WL(e.toolCall,n.toolCall))})}function rR(e,t,n,r){return SL(()=>{let i=vP(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&WL(e.turn,r));if(i===void 0)throw xL(`Retry has no recorded turn`);KL(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&&WL(e.event.run,n.run))}).pipe(it(iR))}var iR=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function aR(e,t,n){return S(function*(){let r=yield*lL(e,t,n=>eR(e,t,n)),i=yield*rL(e,t),a=(a,o)=>{switch(a.type){case`model_prompt`:return $L(e,t,n,a);case`run_start`:case`turn_start`:case`run_end`:return ZL(e,t,n,a,o);case`message_start`:return a.value.role===`user`?h:QL(e,t,a).pipe(y(a.value.role===`assistant`?r.started(a):h));case`message_update`:return r.update(a);case`message_end`:return a.value.role===`user`?h:a.value.role===`assistant`?r.terminal(a):eR(e,t,a);case`tool_execution_start`:return tR(e,t,n,a).pipe(y(i.started(a)));case`tool_execution_end`:return nR(e,t,a).pipe(y(i.terminal(a)));case`tool_execution_update`:return i.update(a);case`turn_end`:return h}};return(e,t)=>a(e,t).pipe(it(iR))})}function oR(e,t,n){return SL(()=>UI(e,pb(t),pb(n)))}var sR=_N.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),cR=F({requestId:A(N),meta:A(FO),data:A(MO),origin:A(sR),id:N,sequence:U.check(Wm(0)),commandId:z(N),value:BA}),lR=R([`manual`,`threshold`,`overflow`]),uR=F({queue:L([F({state:M(`idle`)}),F({state:M(`queued`),commandId:Th,runningWork:z(F({phase:R([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),F({state:M(`running`),commandId:Th})]),cancellationRequested:nm,retry:z(F({attempt:U.check(Wm(0)),maxAttempts:U.check(Wm(0)),delayMs:U.check(H(0)),errorMessage:N,scheduledAt:U.check(H(0))})),activeTool:z(N),lastModelChoiceSequence:z(U.check(Wm(0))),compaction:z(F({trigger:lR}))}),dR=N,fR=om(N,L([F({status:M(`running`),revision:dR,value:MO,catalog:A(MO)}),F({status:M(`stopped`),revision:dR,reason:N})])),pR=F({id:N,version:N,revision:dR,status:R([`running`,`stopped`]),reason:z(N),stoppedAt:z(P)}),mR=F({commandId:N,outcome:R([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:U.check(Wm(0)),diagnostic:z(N),meta:A(FO)}),hR=F({id:N,sequence:U.check(Wm(0)),at:U.check(H(0)),tokensBefore:P,tokensAfter:z(P),trigger:z(lR)}),gR=F({id:N,sequence:U.check(Wm(0)),at:U.check(H(0)),trigger:lR,result:R([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:z(N)}),_R=N.check(V(e=>new TextEncoder().encode(e).byteLength<=65536)),vR=F({messageId:N,revision:U.check(H(0)),text:_R,thinking:_R,textOffset:U.check(H(0)),thinkingOffset:U.check(H(0)),textTruncated:nm,thinkingTruncated:nm}),yR=F({commandId:N,requestId:N,meta:A(FO),origin:A(sR),text:N,images:A(I(Ly)),delivery:R([`steer`,`followUp`])}),bR=I(F({toolCallId:N,revision:U.check(H(0)),tail:N.check(V(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
819
- `).length<=200)),droppedBytes:U.check(H(0)),totalBytes:U.check(H(0))})).check(fh(4)),xR=F({total:U.check(H(0)),prompts:I(yR),hasMore:nm}),SR=F({tokens:U.check(H(0)),window:z(U.check(Wm(0)))}),CR=F({sessionId:N,cursor:z(N),hasMore:nm,oldestCursor:A(z(N)),messages:I(cR),terminals:I(mR),sandboxFailures:A(I(OO)),compactions:A(I(hR)),compactionNotices:A(I(gR)),pending:xR,activity:uR,progress:z(vR),toolOutput:bR,extensions:fR,attention:Cy,context:A(SR)}),wR=L([F({kind:M(`heartbeat`)}),F({kind:M(`activity`),activity:uR}),F({kind:M(`tool_output`),toolOutput:bR,activity:uR}),F({kind:M(`update`),delivery:R([`replay`,`live`]),cursor:z(N),messages:I(cR),terminals:I(mR),sandboxFailures:A(I(OO)),compactions:A(I(hR)),compactionNotices:A(I(gR)),pending:xR,activity:uR,extensions:fR,attention:Cy,context:A(SR)}),F({kind:M(`progress`),progress:F({messageId:N,revision:U.check(H(0)),text:F({offset:U.check(H(0)),append:_R}),thinking:F({offset:U.check(H(0)),append:_R})}),activity:uR}),F({kind:M(`reset`),reason:M(`history_unavailable`),cursor:z(N),baseline:CR})]),TR=F({status:M(`accepted`),commandId:N,sessionId:A(N)});k(W(L([TR,F({status:M(`held`),reason:M(`recipient_offline`),message:M(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var ER=F({status:M(`unknown`)}),DR=k(W(L([TR,ER])));function OR(e){return DR(e)}var kR=L([TR,ER,F({status:M(`too_late`),commandId:N})]),AR=F({sessionId:N}),jR=k(W(CR),{onExcessProperty:`error`}),MR=k(W(wR),{onExcessProperty:`error`}),NR=k(W(TR)),PR=k(W(kR)),FR=k(W(AR)),IR=k(W(jy)),LR=k(W(pR)),RR=k(W(I(pR))),zR=k(W(MO));function BR(e){return LR(e)}function VR(e){return RR(e)}function HR(e){return zR(e)}function UR(e){return NR(e)}function WR(e){return PR(e)}function GR(e){return k(W(z(yR)))(e)}function KR(e){return FR(e)}var qR=F({acceptedSender:z(N),delegator:z(N),terminal:mR,content:N,usage:I(F({provider:N,model:N,usage:IA})),toolCalls:U.check(H(0)),waitingOnYou:I(F({itemId:N,kind:N,summary:N})).check(fh(8))});function JR(e){return k(W(z(qR)))(e)??void 0}function YR(e){return jR(e)}function XR(e){return MR(e)}function ZR(e){let t=IR(e);return new G(t.boundary,t.cause,t.message,t.requestId)}var QR=k(W(F({sessions:I(L([F({sessionId:Th,createdAt:P,lastActivityAt:P,settledAt:A(P),title:N,state:R([`needs_you`,`running`,`errored`,`done`])}),F({sessionId:Th,state:M(`unavailable`)})])),next:j(Th)})));function $R(e){let t=QR(e);return{sessions:t.sessions,next:t.next}}var ez=k(W(F({sessionId:Th}))),tz=k(W(F({deleted:nm})));function nz(e){return tz(e).deleted}function rz(e){return ez(e).sessionId}function iz(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:xO(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function az(e,t){return Tr(e,t).then(e=>{if(ra(e))return e.value;let t=Pr(Ki(e.cause))??Wi(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function oz(e){let t=lr(e);if(ra(t))return t.value;let n=Pr(Ki(t.cause))??Wi(t.cause);throw n instanceof Error?n:Error(String(n))}function sz(e){let t=my(e);return Object.freeze({[Symbol.asyncIterator]:()=>{let e=t[Symbol.asyncIterator]();return{next:()=>e.next(),return:()=>e.return?.()??Promise.resolve({done:!0,value:void 0})}}})}function cz(e,t){function n(e){return az(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>az(t.withdraw(e)),abort:()=>az(t.abort),send:(e,n)=>az(t.send(e,n)),cancel:e=>az(t.cancel(e)),latestPending:()=>az(t.latestPending),modelPreference:Object.freeze({read:()=>az(t.modelPreference.read),set:e=>az(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>az(n.call(e,t,r))})},read:e=>az(t.read(e)),readSettlement:(e,n)=>az(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>sz(t.subscribe(e)),watch:e=>az(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:sz(e.changes),close:()=>az(e.close)}))})}function lz(e,t){let n=t??`local:${ng()}`;return Object.freeze({createSession:t=>az(e.createSession(t)),deleteSession:t=>az(e.deleteSession(t)),listSessions:t=>az(e.listSessions(t)),extensions:Object.freeze({list:()=>az(e.extensions.list),resume:t=>az(e.extensions.resume(t)),call:(t,n,r)=>az(e.extensions.call(t,n,r))}),session:t=>cz(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>az(e.close)})}function uz(e){let t=`local:${ng()}`;return Object.freeze({...lz(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:iz(t.tools)});let r=await az(e.prepareConfiguration(n));return{commit:()=>{oz(r.commit)},discard:()=>az(r.discard)}},grants:Object.freeze({deliver:(t,n)=>oz(e.grants.deliver(t,n)),read:t=>oz(e.grants.read(t))}),withMeta:n=>lz(e.withMeta(n),t)})}function dz(e=`Remote Shiitake operation is unavailable`){return new G(`runtime`,`unavailable`,e)}function fz(e){return new G(`runtime`,`invalid`,e)}function pz(){return new G(`runtime`,`closed`,`Shiitake client is closed`)}var mz=2,hz=k(N);function gz(e){if(!(e instanceof MessageEvent))throw fz(`Session stream event is invalid`);return hz(e.data)}function _z(e){return e.kind===`source-error`?x(dz(`Session stream is unavailable`)):e.kind===`snapshot`?en({try:()=>({kind:`snapshot`,value:YR(gz(e.event))}),catch:()=>fz(`Session snapshot is invalid`)}):e.kind===`frame`?en({try:()=>({kind:`frame`,value:XR(gz(e.event))}),catch:()=>fz(`Session frame is invalid`)}):en({try:()=>ZR(gz(e.event)),catch:()=>fz(`Session runtime error is invalid`)}).pipe(E(x))}function vz(e,t){return w(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function yz(e,t,n,r){return Lv(t=>jr(en({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Rg(t,{kind:e,event:r})||(Vg(t,Bi(dz(`Session stream client fell behind`))),Xt(vz(i,n)))};return i.source.addEventListener(`snapshot`,e=>{a(`snapshot`,e)}),i.source.addEventListener(`frame`,e=>{a(`frame`,e)}),i.source.addEventListener(`runtime-error`,e=>{a(`runtime-error`,e)}),i.source.addEventListener(`error`,e=>{i.source.readyState===mz&&a(`source-error`,e)}),n.add(i),i},catch:()=>dz(`Session stream could not open`)}),e=>vz(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(Xv(_z),$v({duration:gy,orElse:()=>Vv(dz(`Session feed is connected but silent; the service may be busy`))}),uy(t.await))}function bz(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function xz(e,t,n=!1){let r=new URLSearchParams({mode:`subscribe`});return t!==void 0&&r.set(`after`,t),n&&r.set(`includeSandboxFailures`,`true`),`${e}?${r.toString()}`}function Sz(e,t,n,r){return yz(e,t,n,r).pipe(Xv(e=>e.kind===`frame`?b(e.value):x(fz(`Session subscription received a snapshot`))))}function Cz(e,t,n,r,i,a){return S(function*(){yield*n;let o=yield*b_(!1),s=yield*_a();yield*w(()=>t.add(s)),yield*xa(s,w(()=>{t.delete(s)}));let c=yield*Dn(yz(e,r,i,a).pipe(oy(Dv()),ya(s)));if(ia(c))return yield*wa(s,c),yield*Bt(c.cause);let[l,u]=c.value;if(ir(l)||l.value.kind!==`snapshot`){let e=fz(`Session stream did not begin with a snapshot`);return yield*wa(s,ea(e)),yield*x(e)}let d=u.pipe(Xv(e=>e.kind===`frame`?b(e.value):b({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),uy(o.await),sy(e=>o.isOpen()&&Hi(e)?Rv:Hv(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(y(wa(s,na)))})})}function wz(e,t,n){return si({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>dz(`${n} request failed`)}).pipe(E(({response:e,body:r})=>e.ok?en({try:()=>t(r),catch:()=>fz(`${n} response is invalid`)}):en({try:()=>ZR(r),catch:()=>fz(`${n} error response is invalid`)}).pipe(E(x))))}function Tz(t){let n=t.baseUrl.replace(/\/+$/u,``),r=t.fetch??globalThis.fetch,i=new Set,a=new Set,o=y_(!1),s=!1,c=hr(()=>s?x(pz()):h),l=(t,n,r)=>e(wz(t,n,r),o.await.pipe(y(x(pz())))),u=(e,t)=>c.pipe(y(l(n=>r(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:n}),HR,`Extension command`)));return Object.freeze({createSession:e=>c.pipe(E(()=>{let t=hb({requestId:e});return l(e=>r(`${n}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:t}),signal:e}),rz,`Session creation`)})),deleteSession:e=>c.pipe(E(()=>{let t=pb(e);return l(e=>r(`${n}/sessions/${encodeURIComponent(t)}`,{method:`DELETE`,signal:e}),nz,`Session deletion`)})),listSessions:e=>c.pipe(E(()=>{let t=new URLSearchParams;e!==void 0&&t.set(`after`,mb(e));let i=t.size===0?``:`?${t.toString()}`;return l(e=>r(`${n}/sessions${i}`,{signal:e}),$R,`Session discovery`)})),extensions:Object.freeze({list:c.pipe(y(l(e=>r(`${n}/extensions`,{signal:e}),VR,`Extension list`))),resume:e=>c.pipe(y(l(t=>r(`${n}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:t}),BR,`Extension resume`))),call:(e,t,r)=>u(`${n}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,r)}),session:e=>{let s=pb(e),d=bz(n,s),f=`${d}/events`;function p(e){return c.pipe(y(l(t=>r(`${d}/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({command:e}),signal:t}),e.type===`prompt`||e.type===`compact`?UR:e.type===`cancel`?WR:e.type===`fork`?KR:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>c.pipe(y(l(t=>r(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),OR,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>w(()=>t?.requestId??ng()).pipe(E(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return p(t?.images===void 0?r:{...r,images:t.images}).pipe(it(e=>e.requestId===n?e:new G(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:c.pipe(y(l(e=>r(`${d}/pending/latest`,{signal:e}),GR,`Newest pending prompt`))),modelPreference:Object.freeze({read:c.pipe(y(l(e=>r(`${d}/model-preference`,{signal:e}),Dy,`Model preference read`))),set:e=>c.pipe(y(l(t=>r(`${d}/model-preference`,{signal:t,method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),()=>void 0,`Model preference set`)))}),extension:e=>Object.freeze({call:(t,n)=>u(`${d}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,n)}),read:e=>c.pipe(y(en({try:()=>gb(e),catch:e=>e instanceof G?e:fz(`Read options are invalid`)})),E(({limit:e,before:t,includeSandboxFailures:n})=>{let i=new URLSearchParams({limit:String(e)});return t!==void 0&&i.set(`before`,t),n===!0&&i.set(`includeSandboxFailures`,`true`),l(e=>r(`${d}?${i.toString()}`,{signal:e}),YR,`Session read`)})),readSettlement:(e,t=0)=>c.pipe(y(l(n=>r(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:n}),JR,`Command settlement`))),subscribe:e=>Jv(c.pipe(y(en({try:()=>_b(e),catch:e=>e instanceof G?e:fz(`Subscribe options are invalid`)})),be(({after:e,includeSandboxFailures:n})=>Sz(xz(f,e,n===!0),o,a,t.eventSource)))),watch:e=>Cz(e?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,i,c,o,a,t.eventSource)})},close:hr(()=>s?h:(s=!0,o.open.pipe(y(Kr([...i],e=>wa(e,na),{discard:!0})),y(Kr([...a],e=>vz(e,a),{discard:!0})))))})}function Ez(e){return lz(Tz(e),e.baseUrl.replace(/\/+$/u,``))}O(MO);function Dz(e,t){if(t===void 0)return{status:`unavailable`};if(t.status===`stopped`)return{status:`stopped`,reason:t.reason};if(t.value===null||e.projection===null)return{status:`running`,value:null};let n=O(e.projection.schema)(t.value);return n._tag===`Success`?{status:`running`,value:n.success}:{status:`stopped`,reason:`Extension projection does not match this client`}}function Oz(e,t){let n=e?.messageId===t.messageId?e:null;if(n!==null&&n.revision>=t.revision)return e;let r=n===null?0:n.textOffset+n.text.length,i=n===null?0:n.thinkingOffset+n.thinking.length;return t.text.offset>r||t.thinking.offset>i?e:{messageId:t.messageId,revision:t.revision,text:(n?.text??``)+t.text.append.slice(Math.max(0,r-t.text.offset)),thinking:(n?.thinking??``)+t.thinking.append.slice(Math.max(0,i-t.thinking.offset)),textOffset:n?.textOffset??0,thinkingOffset:n?.thinkingOffset??0,textTruncated:n?.textTruncated??!1,thinkingTruncated:n?.thinkingTruncated??!1}}var kz=N.pipe(B(lh(1)),B(fh(128)),B(Om(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),Az=N.pipe(B(lh(1)),B(fh(64)),B(Om(/^(?: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))),jz=kz.pipe(hm(`ExtensionId`)),Mz=N.pipe(B(Om(/^sha256:[0-9a-f]{64}$/u)),hm(`ExtensionRevision`)),Nz=N.pipe(B(Om(/^sha256:[0-9a-f]{64}$/u)),hm(`ExtensionFingerprint`)),Pz=class extends Fi(`ExtensionHookError`){};function Fz(e){return hr(()=>{let t=e();return He(t)?t:si({try:()=>Promise.resolve(t),catch:e=>new Pz({cause:e})})})}var Iz=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function Lz(e,t){let n=e(t);if(n instanceof Promise||He(n)&&!wr(n))throw new Iz;return n}export{tL as $,Bs as $a,$m as $i,ME as $n,Im as $r,Cj as $t,JL as A,Uh as Aa,Lp as Ai,Ek as An,Nv as Ar,KM as At,kL as B,hc as Ba,wm as Bi,XO as Bn,g_ as Br,qj as Bt,BL as C,V as Ca,hm as Ci,oA as Cn,Wi as Co,gy as Cr,qP as Ct,yL as D,pm as Da,zp as Di,Jk as Dn,Vv as Dr,fI as Dt,aR as E,mm as Ea,Tp as Ei,eA as En,dy as Er,BF as Et,NL as F,Dc as Fa,Kp as Fi,vk as Fn,my as Fr,lM as Ft,gL as G,Tc as Ga,rh as Gi,BO as Gn,yg as Gr,iM as Gt,XL as H,wc as Ha,qm as Hi,qO as Hn,Hg as Hr,Jj as Ht,IL as I,Cc as Ia,vm as Ii,mk as In,Jv as Ir,cM as It,fL as J,Ku as Ja,xh as Ji,jO as Jn,Zh as Jr,fM as Jt,pL as K,Gu as Ka,ph as Ki,RO as Kn,ng as Kr,aM as Kt,FL as L,bc as La,Hp as Li,yk as Ln,x_ as Lr,dM as Lt,VL as M,Np as Ma,O as Mi,wk as Mn,qv as Mr,yM as Mt,HL as N,Sm as Na,k as Ni,_k as Nn,fy as Nr,xM as Nt,CL as O,Cm as Oa,Bp as Oi,tA as On,ey as Or,$M as Ot,YL as P,wd as Pa,Wp as Pi,hk as Pn,$v as Pr,sM as Pt,sL as Q,Rs as Qa,ih as Qi,uD as Qn,Dh as Qr,Mj as Qt,PL as R,Zu as Ra,Up as Ri,gk as Rn,y_ as Rr,uM as Rt,zL as S,Am as Sa,$p as Si,sA as Sn,Ji as So,hy as Sr,VP as St,jL as T,A as Ta,Ep as Ti,nA as Tn,ty as Tr,nI as Tt,EL as U,vc as Ua,ch as Ui,tk as Un,zg as Ur,Yj as Ut,qL as V,yc as Va,Fp as Vi,nk as Vn,h_ as Vr,Xj as Vt,TL as W,gc as Wa,gh as Wi,ek as Wn,Rg as Wr,Zj as Wt,QI as X,sc as Xa,Lm as Xi,mD as Xn,im as Xr,Rj as Xt,cL as Y,Su as Ya,Pm as Yi,SO as Yn,I as Yr,Vj as Yt,$I as Z,Ls as Za,Wm as Zi,VD as Zn,nm as Zr,Tj as Zt,_L as _,Sh as _a,cm as _i,$A as _n,Vi as _o,G as _r,gP as _t,Nz as a,Gm as aa,Xm as ai,bj as an,_a as ao,SE as ar,oP as at,wL as b,Om as ba,fm as bi,vA as bn,Ki as bo,yy as br,hF as bt,Az as c,Km as ca,Th as ci,Oj as cn,da as co,MT as cr,UF as ct,Ez as d,hh as da,P as di,Sj as dn,oa as do,ub as dr,YN as dt,H as ea,U as ei,jj as en,jo as eo,LE as er,EI as et,iz as f,fh as fa,om as fi,Dj as fn,ia as fo,hb as fr,bP as ft,DL as g,lh as ga,jh as gi,rj as gn,na as go,vb as gr,yP as gt,UR as h,mh as ha,rm as hi,kA as hn,Qi as ho,_b as hr,KP as ht,jz as i,Ym as ia,R as ii,Fj as in,Sa as io,OE as ir,eI as it,LL as j,Hh as ja,Rp as ji,Tk as jn,Xv as jr,XM as jt,oR as k,Wh as ka,Ip as ki,Dk as kn,Kv as kr,qM as kt,Oz as l,sh as la,em as li,Nj as ln,ua as lo,lb as lr,dP as lt,uz as m,bh as ma,F as mi,Aj as mn,aa as mo,Vy as mr,aP as mt,Fz as n,eh as na,Kh as ni,wj as nn,xa as no,NE as nr,vN as nt,kz as o,oh as oa,Qp as oi,xj as on,va as oo,TT as or,tI as ot,az as p,Ch as pa,N as pi,kj as pn,ra as po,pb as pr,xP as pt,mL as q,qu as qa,wh as qi,MO as qn,Xh as qr,oM as qt,Lz as r,Fm as ra,M as ri,Lj as rn,wa as ro,DE as rr,zP as rt,Mz as s,th as sa,lm as si,Ej as sn,ya as so,wT as sr,VF as st,Iz as t,ah as ta,Gh as ti,yj as tn,ga as to,IE as tr,FI as tt,Dz as u,nh as ua,z as ui,Ij as un,ma as uo,gb as ur,rP as ut,vL as v,yh as va,Nh as vi,nj as vn,Bi as vo,Ey as vr,LF as vt,AL as w,j as wa,B as wi,Xk as wn,Fi as wo,Lv as wr,JP as wt,RL as x,Nm as xa,L as xi,gA as xn,Hi as xo,Sy as xr,GP as xt,OL as y,Jm as ya,tm as yi,ej as yn,qi as yo,by as yr,dI as yt,rR as z,xc as za,W as zi,YO as zn,m_ as zr,Kj as zt};