@fungi.computer/grove 0.13.3 → 0.13.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{Effect-CsknxyoC.js → Effect-DeiDqvoz.js} +1 -1
- package/dist/assets/{anthropic-messages-CFPH_UNu.js → anthropic-messages-DRCIDkuM.js} +3 -3
- package/dist/assets/{azure-openai-responses-CSgmN70B.js → azure-openai-responses-BLdXsJsO.js} +1 -1
- package/dist/assets/{base-face-BYNJAADF.js → base-face-Biu4f93I.js} +1 -1
- package/dist/assets/burger-_bhUKwsW.js +1 -0
- package/dist/assets/cat-CwE4Zh7L.js +1 -0
- package/dist/assets/{compat-oy1YdGOO.js → compat-bF01jZNd.js} +2 -2
- package/dist/assets/{document-Bq-ilh6h.js → document-CEriO-BY.js} +1 -1
- package/dist/assets/{extension-hook-CNCgQKuR.js → extension-hook-CTu5o2jQ.js} +12 -12
- package/dist/assets/{google-generative-ai-ZweefzCV.js → google-generative-ai-C2oH9OZp.js} +1 -1
- package/dist/assets/{google-shared-BNsmrVre.js → google-shared-jP8lgN2u.js} +1 -1
- package/dist/assets/{google-vertex-5XlwcffB.js → google-vertex-C17eje_2.js} +1 -1
- package/dist/assets/index-Vpqb1PUB.js +117 -0
- package/dist/assets/{mistral-conversations-d91izuu2.js → mistral-conversations-ndIEqz9T.js} +1 -1
- package/dist/assets/{mushroom-Bm99-6Un.js → mushroom-a_sE2Lmz.js} +1 -1
- package/dist/assets/{node.browser-DHPRDGM3.js → node.browser-D_jblep6.js} +1 -1
- package/dist/assets/{openai-codex-responses-Byq3AJ6w.js → openai-codex-responses-BgrNR8T1.js} +1 -1
- package/dist/assets/{openai-completions-B8HPuJG9.js → openai-completions-BHxNs5Ca.js} +1 -1
- package/dist/assets/{openai-responses-4TsOe5p8.js → openai-responses-W9SrIwyk.js} +1 -1
- package/dist/assets/{openai-responses-shared-OeUCvs3J.js → openai-responses-shared-SmcOX-CT.js} +1 -1
- package/dist/assets/parakeet-B6q5iha9.js +36 -0
- package/dist/assets/{parakeet-conversation-5ulIIF5X.js → parakeet-conversation-D5Cm6M0G.js} +2 -2
- package/dist/assets/{renderer-B77qG8Ri.js → renderer-BvWy-oBw.js} +1 -1
- package/dist/assets/{runtime-core-CP9YyZVG.js → runtime-core-B_1gibxC.js} +1 -1
- package/dist/assets/sigil-CEqXOKdC.js +31 -0
- package/dist/assets/{transform-messages-D8nvw62n.js → transform-messages-C3pBaiQJ.js} +1 -1
- package/dist/assets/{website-conversation-LWlh-qyt.js → website-conversation-CLV6Ji2W.js} +1 -1
- package/dist/index.html +6 -6
- package/package.json +7 -7
- package/dist/assets/burger-XIvkUQFx.js +0 -1
- package/dist/assets/cat-Cf9Ryl3W.js +0 -1
- package/dist/assets/index-CHxxTwbn.js +0 -117
- package/dist/assets/parakeet-BYGXavdn.js +0 -36
- package/dist/assets/sigil-CD9cI8dy.js +0 -31
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-
|
|
2
|
-
import{$i as e,$n as t,$r as n,$t as r,A as i,Ai as a,An as o,Ar as s,At as c,B as l,Bn as u,Br as d,Bt as f,C as p,Ci as m,Cn as ee,Ct as te,D as ne,Di as re,Dn as ie,Dr as ae,Dt as oe,E as se,Ei as ce,En as le,Er as ue,Et as de,Fi as fe,Fn as pe,Fr as me,Ft as he,G as ge,Gn as _e,Gr as ve,Gt as ye,H as be,Hr as xe,Ht as Se,I as Ce,Ii as we,In as Te,Ir as Ee,It as De,J as Oe,Jn as ke,Jr as Ae,Jt as je,K as Me,Kr as Ne,Kt as Pe,L as Fe,Li as Ie,Ln as Le,Lr as Re,Lt as ze,M as Be,Mi as Ve,Mn as He,Mr as Ue,Mt as We,N as Ge,Ni as Ke,Nn as qe,Nr as Je,Nt as Ye,O as Xe,Oi as Ze,On as Qe,Or as $e,Ot as et,P as tt,Pi as nt,Pn as rt,Pr as it,Pt as at,Q as ot,Qi as st,Qr as h,Qt as ct,R as lt,Rn as ut,Rr as dt,Rt as ft,S as pt,Sa as mt,Si as ht,Sn as gt,Sr as _t,St as vt,T as yt,Ta as bt,Ti as xt,Tn as St,Tt as Ct,U as wt,Un as Tt,Ur as Et,Ut as Dt,V as Ot,Vn as kt,Vr as At,Vt as jt,W as Mt,Wn as Nt,Wr as Pt,Wt as Ft,X as It,Xn as Lt,Xr as Rt,Xt as zt,Y as Bt,Yi as Vt,Yn as Ht,Yr as Ut,Yt as Wt,Z as Gt,Za as Kt,Zi as qt,Zn as Jt,Zt as Yt,_ as Xt,_a as Zt,_i as Qt,_n as $t,_r as en,a as g,aa as tn,ai as nn,an as rn,ar as an,at as on,b as sn,ba as cn,bi as ln,bn as un,br as dn,bt as fn,c as pn,ca as mn,ci as hn,cn as gn,cr as _n,d as vn,da as yn,di as bn,dn as xn,dr as Sn,ea as Cn,en as wn,eo as Tn,er as En,et as Dn,f as On,fa as _,fi as kn,fn as An,ft as jn,g as v,ga as Mn,gi as Nn,gn as Pn,gr as Fn,gt as In,h as Ln,ha as Rn,hi as zn,hn as Bn,hr as Vn,ht as y,i as Hn,ii as Un,in as Wn,ir as Gn,it as Kn,j as b,jr as qn,jt as Jn,k as Yn,ki as Xn,kr as Zn,kt as Qn,l as $n,li as er,ln as tr,lt as nr,m as rr,ma as ir,mi as ar,mn as or,mt as sr,ni as cr,nn as lr,nt as ur,o as dr,oa as fr,oi as pr,on as mr,or as hr,ot as gr,p as _r,pa as vr,pi as yr,pn as br,pr as xr,pt as x,q as Sr,qr as S,qt as Cr,r as wr,ra as Tr,ri as Er,rn as Dr,ro as Or,rt as kr,s as Ar,sa as jr,sn as Mr,sr as Nr,st as Pr,t as Fr,ta as Ir,ti as Lr,tn as Rr,tt as zr,u as Br,ua as Vr,ui as Hr,un as Ur,ur as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wa as Qr,wi as $r,wn as ei,wr as ti,wt as C,x as ni,xa as w,xi as ri,xn as ii,xr as ai,xt as oi,y as T,ya as si,yi as ci,yn as li,yr as ui,yt as di,z as fi,zr as pi,zt as mi}from"./Effect-CsknxyoC.js";import{l as hi,t as gi}from"./preload-helper-DY31Aviq.js";var _i=e=>e>0?Math.floor(e):0,vi=e=>Math.max(1,_i(e)),yi=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},bi=`~effect/BigDecimal`,xi={[bi]:bi,[kn](){let e=ki(this);return hn(bn(String(e.value)),Hr(e.scale))},[pr](e){return Si(e)&&Pi(this,e)===0},toString(){return`BigDecimal(${Ii(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Ne](){return this.toJSON()},pipe(){return Ie(this,arguments)}},Si=e=>yr(e,bi),Ci=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(xi);return n.value=e,n.scale=t,n},wi=(e,t)=>{let n=Ci(e,t);return n.normalized=n,n},Ti=BigInt(0),Ei=BigInt(1),Di=BigInt(10),Oi=wi(Ti,0),ki=e=>{if(e.normalized===void 0){if(e.value===Ti)e.normalized=Oi;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=wi(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Ai=100,ji=[Ei],Mi=(e,t)=>e===t?0:e<t?-1:1,Ni=(e,t)=>{let n=`${e.value<Ti?-e.value:e.value}`,r=`${t.value<Ti?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Ti)return i<Ti?-1:1;let a=Math.max(n.length,r.length);return Yr(n.padEnd(a,`0`),r.padEnd(a,`0`))},Pi=(e,t)=>{if(e.scale===t.scale)return Mi(e.value,t.value);let n=Fi(e),r=Fi(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>Ai)return n===-1?Ni(t,e):Ni(e,t);let o=ji[a]??=Di**BigInt(a);return i>0?Mi(e.value,t.value*o):Mi(e.value*o,t.value)},Fi=e=>e.value===Ti?0:e.value<Ti?-1:1,Ii=e=>{let t=ki(e);if(Math.abs(t.scale)>=16)return Li(t);let n=t.value<Ti,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},Li=e=>{if(Ri(e))return`0e+0`;let t=ki(e),n=`${t.value}`,r=t.value<Ti?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Ri=e=>e.value===Ti,zi=ae,Bi=`~effect/encoding/EncodingError`,Vi=class extends zi(`EncodingError`){[Bi]=Bi},Hi=d,Ui=qn,Wi=s,Gi=Zn,Ki=Dr,qi=Ye,Ji=he,Yi=ct,Xi=r,Zi=Yt,Qi=lr,$i=at,ea=dt,ta=Ue,na=et;qe()(`effect/Cause/StackTrace`),qe()(`effect/Cause/InterruptorStackTrace`);var ra=Re,ia=Ee,aa=me,oa=it,sa=ye,ca=Se,la=jt,ua=Ft,da=Dt,fa=mi,pa={"~effect/Deferred":{_A:Ve,_E:Ve},pipe(){return Ie(this,arguments)}},ma=function(){this.resumes=void 0,this.effect=void 0};ma.prototype=pa;var ha=()=>new ma,ga=()=>gt(()=>ha()),_a=e=>Jn(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),gt(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),va=a(2,(e,t)=>gt(()=>xa(e,t))),ya=a(2,(e,t)=>va(e,me(t))),ba=a(2,(e,t)=>va(e,Re(t))),xa=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},Sa=Jr,Ca=Pn,wa=$t,Ta=tr,Ea=An,Da=xn,Oa=or,ka=Bn,Aa=br,ja=oe,Ma=ze,Na=`~effect/DateTime`,Pa=`~effect/DateTime/TimeZone`,Fa={[Na]:Na,pipe(){return Ie(this,arguments)},[Ne](){return this.toString()},toJSON(){return Ka(this).toJSON()}},Ia={...Fa,_tag:`Utc`,[kn](){return Hr(this.epochMilliseconds)},[pr](e){return Ra(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ka(this).toJSON()})`}};({...Fa});var La={[Pa]:Pa,[Ne](){return this.toString()}};({...La}),{...La};var Ra=e=>yr(e,Na),za=e=>e._tag===`Utc`,Ba=e=>{let t=Object.create(Ia);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Va=e=>{let t=e.getTime();if(Number.isNaN(t))throw new na(`Invalid date`);return Ba(t)},Ha=e=>{if(Ra(e))return e;if(e instanceof Date)return Va(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Va(new Date(e.epochMilliseconds));let t=new Date(0);return qa(t,e),Va(t)}return typeof e==`string`&&!Ua(e)?Va(new Date(e+`Z`)):Va(new Date(e))},Ua=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Wa=_n(Ha),Ga=e=>Ba(e.epochMilliseconds),Ka=e=>new Date(e.epochMilliseconds),qa=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Ja=e=>Ka(e).toISOString();globalThis.Number;var Ya=a(2,(e,t)=>{if(!globalThis.Number.isFinite(e)||!globalThis.Number.isFinite(t)||t===0)return NaN;if(globalThis.Number.isInteger(e)&&globalThis.Number.isInteger(t))return e%t;let[n,r]=Xa(e),[i,a]=Xa(t),o=Math.min(r,a),s=n*BigInt(10)**BigInt(r-o)%(i*BigInt(10)**BigInt(a-o));if(s===BigInt(0))return e<0||Object.is(e,-0)?-0:0;let c=globalThis.Number(`${s}e${o}`);return c===0?Math.sign(e)*globalThis.Number.MIN_VALUE:c});function Xa(e){if(globalThis.Number.isInteger(e))return[BigInt(e),0];let t=Math.abs(e).toExponential(),n=t.indexOf(`e`),r=t.slice(0,n).replace(`.`,``);return[BigInt(r)*(e<0?-BigInt(1):BigInt(1)),globalThis.Number(t.slice(n+1))-r.length+1]}globalThis.String;var Za=e=>e.trim(),Qa=a(2,(e,t)=>We(e,no,e=>t(e))),$a=e=>e.reasons.some(eo),eo=e=>e._tag===`Fail`&&ea(e.error),to=e=>{let n,r=!1;for(let t of e.reasons)eo(t)?n??=t.error:t._tag!==`Interrupt`&&(r=!0);return n===void 0?_e(e):r?_e(Ui(e.reasons.filter(e=>!eo(e)))):t(n)},no=e=>{let n=to(e);return ke(n)?n:t(n.success.value)},ro=e=>{let t=to(e);return ke(t)?ia(t.failure):ra(t.success.value)},io=He(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),ao=He(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),oo=`~effect/Metric`,so=class{[oo]=oo;#e;#t=``;id;description;attributes;constructor(e,t,n){this.id=e,this.description=t,this.attributes=n}valueUnsafe(e){return this.hook(e).get(e)}modifyUnsafe(e,t){return this.hook(t).modify(e,t)}updateUnsafe(e,t){return this.hook(t).update(e,t)}hook(e){let t=Te(e,io);t!==this.#e&&(this.#e=t,this.#t=ho(this,_o(this.attributes,t)));let n=Te(e,ao),r=n.get(this.#t);return ce(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?_o(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return Ie(this,arguments)}},co=BigInt(0),lo=class extends so{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,vo(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?co:0,t=this.#t?this.#e?e=>e>=co:e=>e>=0:e=>!0;return go(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},uo=class extends so{type;metric;valueUnsafe;updateUnsafe;modifyUnsafe;constructor(e,t,n,r){super(e.id,e.description,e.attributes),this.metric=e,this.valueUnsafe=t,this.updateUnsafe=n,this.modifyUnsafe=r,this.type=e.type}createHooks(){return this.metric.createHooks()}},fo=(e,t)=>new lo(e,t),po=a(2,(e,t)=>De(n=>gt(()=>e.updateUnsafe(t,n)))),mo=a(2,(e,t)=>{let n=yo(t);return new uo(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function ho(e,t){let n=Object.entries(t).sort((e,t)=>e[0]<t[0]?-1:+(e[0]>t[0]));return JSON.stringify([e.type,e.id,e.description,n])}function go(e,t,n){return{get:e,update:t,modify:n??t}}function _o(e,t){return{...vo(e),...vo(t)}}function vo(e){return ci(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(h(e,t,n),e),{}):e}function yo(e){let t,n={};return r=>{let i=Te(r,io);return i!==t&&(t=i,n=_o(i,e)),rt(r,io,n)}}var bo=Ra,xo=za,So=Ha,Co=Wa,wo=Ga;qe()(`effect/DateTime/CurrentTimeZone`);var To=Ja,Eo=e=>Oo(typeof e==`string`?ko.encode(e):e),Do=e=>{let n=Ao(e),r=n.length;if(r%4!=0)return _e(new Vi({kind:`Decode`,module:`Base64`,input:n,message:`Length must be a multiple of 4, but is ${r}`}));let i=n.indexOf(`=`);if(i!==-1&&(i<r-2||i===r-2&&n[r-1]!==`=`))return _e(new Vi({kind:`Decode`,module:`Base64`,input:n,message:`Found a '=' character, but it is not at the end`}));try{let e=n.endsWith(`==`)?2:+!!n.endsWith(`=`),i=new Uint8Array(r/4*3-e);for(let e=0,t=0;e<r;e+=4,t+=3){let r=No(n.charCodeAt(e))<<18|No(n.charCodeAt(e+1))<<12|No(n.charCodeAt(e+2))<<6|No(n.charCodeAt(e+3));i[t]=r>>16,i[t+1]=r>>8&255,i[t+2]=r&255}return t(i)}catch(e){return _e(new Vi({kind:`Decode`,module:`Base64`,input:n,message:e instanceof Error?e.message:`Invalid input`}))}},Oo=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2|e[r]>>6],n+=jo[e[r]&63];return r===t+1&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2],n+=`=`),n},ko=new TextEncoder,Ao=e=>e.replace(/[\n\r]/g,``),jo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Mo=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Mo[jo.charCodeAt(e)]=e;Mo[61]=0;var No=e=>{if(e>=Mo.length||Mo[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Mo[e]};zi(`CookiesError`),{...ve},{...ve};var Po=new WeakMap,Fo=`~effect/Redacted`,Io=e=>yr(e,Fo),Lo=(e,t)=>{let n=Object.create(Ro);return t?.label&&(n.label=t.label),Po.set(n,e),n},Ro={[Fo]:{_A:e=>e},label:void 0,...ue,toJSON(){return this.toString()},toString(){return`<redacted${$r(this.label)?`:`+this.label:``}>`},[kn](){return er(Po.get(this))},[pr](e){return Io(e)&&Er(Po.get(this),Po.get(e))}};({...ue});function zo(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Bo(e){return t=>zo(t)?.[e]}var Vo=`~structural`,Ho=`~identifier`,Uo=`~sentinels`,Wo=`~constructor`,Go=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],Ko=Bo(`identifier`),qo=Bo(Ho),Jo=Bo(`title`),Yo=Bo(`description`),Xo=Ke(e=>{let t=zo(e)?.identifier;return typeof t==`string`?t:e.getExpected(Xo)}),Zo=new Set([Uo,Vo,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),E=Symbol(),Qo=ra,$o=Qo(E),es=Qo(E),ts=e=>e===E?Sn():xr(e),ns=e=>e._tag===`None`?$o:Qo(e.value),rs=`~effect/SchemaIssue/Issue`;function is(e){return yr(e,rs)&&e[rs]===rs}function as(e){return Object.hasOwn(e,`input`)}var os=class{[rs]=rs;constructor(e,t){t?.reportInput===!0&&e!==E&&(this.input=e)}},ss=class extends os{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},cs=class extends os{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},ls=class extends os{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},us=class extends os{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},ds=class extends os{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},fs=class extends os{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ps=class extends os{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},ms=class extends os{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},hs=class extends os{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},gs=class extends os{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},_s=class extends os{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function vs(e,t,n){if(is(e))return e;if(typeof e==`string`)return new ms({message:e},t,n);let r=typeof e.issue==`string`?new ms({message:e.issue},t,n):e.issue;return new ls(e.path,r)}function ys(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new ms(void 0,t,n):vs(e,t,n)}function bs(e,t,n,r){return Array.isArray(t)?kt(t)?t.length===1?vs(t[0],n,r):new fs(e,Tt(t,e=>vs(e,n,r)),n,r):void 0:ys(t,n,r)}var xs=e=>{let t=Ms(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Es(Xo(e.ast),e);case`InvalidValue`:{let t=Ts(e);if(t!==void 0)return Es(t,e);let n=ws(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=ws(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=ws(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Ss=e=>Ms(e.issue)??Ms(e);function Cs(e){return t=>({issues:Ds(t,[],e?.leafHook??xs,e?.checkHook??Ss)})}function ws(e){return as(e)?S(e.input):void 0}function Ts(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Es(e,t){let n=ws(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Ds(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return Ds(e.issue,t,n,r);let a=Ts(e.issue);return[{path:t,message:a===void 0?Es(Os(e.filter),e):Es(a,e.issue)}]}case`Encoding`:return Ds(e.issue,t,n,r);case`Pointer`:return Ds(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>Ds(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:Ms(e)??Es(Xo(e.ast),e)}]:e.issues.flatMap(e=>Ds(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Os(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>Os(e)).join(` & `)}}function ks(){return e=>js(e,``)}var As=ks();function js(e,t){let n;switch(e._tag){case`Filter`:{let r=Ss(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return js(e.issue,t);let r=Ts(e.issue);n=r===void 0?Es(Os(e.filter),e):Es(r,e.issue)}break}case`Encoding`:return js(e.issue,t);case`Pointer`:return js(e.issue,t+Ut(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>js(e,t)).join(`
|
|
3
|
-
`);n=Ms(e)??Es(Xo(e.ast),e);break;default:n=xs(e)}return t?`${n}\n at ${t}`:n}function Ms(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Ms(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Ns(e){let t;for(let n of e.reasons){if(!Hi(n)||!is(n.error))return;t??=n.error}return t}function Ps(e,t){let n=Ns(e);if(n===void 0)throw Error(t,{cause:e});return n}var Fs=e=>Eo(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Is=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return _e(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Length should be a multiple of 4, but is ${n}`}));if(!/^[-_A-Z0-9]*?={0,2}$/i.test(t))return _e(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Invalid input`}));let r=n%4==2?`${t}==`:n%4==3?`${t}=`:t;return r=r.replace(/-/g,`+`).replace(/_/g,`/`),Do(r)},Ls=e=>Object.assign(Object.create(we),e);function Rs(e){return qs((t,n)=>v(e(t,n)))}function zs(e){return Rs((t,n)=>{let r={message:e(t)};return Nr(t)?new hs(r,t.value,n):new hs(r)})}var Bs=zs(()=>`Encoding is not supported`),Vs=Ls({_tag:`Passthrough`});function Hs(){return Vs}function Us(){return Vs}function Ws(e){return Ls({_tag:`Transform`,transform:e})}function Gs(e){return Ls({_tag:`TransformEffect`,transform:e})}function Ks(e){return Ls({_tag:`TransformOptional`,transform:e})}function qs(e){return Ls({_tag:`TransformOptionalEffect`,transform:e})}function Js(){return Ks(()=>Sn())}function Ys(e){return qs(t=>{let n=En(t,ci);return Nr(n)?x(n):Fe(e,xr)})}function Xs(){return Ws(globalThis.String)}function Zs(){return Ws(globalThis.Number)}function Qs(){return Ws(globalThis.BigInt)}function $s(){return Ws(e=>new globalThis.Date(e))}function ec(){return Ws(Za)}function tc(e){return Gs((t,n)=>oi({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ms({expected:`a valid JSON string`},t,n)}))}function nc(e){return Gs((t,n)=>oi({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new ms({expected:`a JSON-serializable value`},t,n)}))}function rc(){return Ws(Eo)}function ic(){return Gs((e,t)=>fi(i(Do(e)),()=>new ms({expected:`a valid Base64 string`},e,t)))}var ac=class extends fe{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new ac(this.encode,this.decode)}},oc=`~effect/SchemaTransformation/Transformation`,sc=class extends fe{[oc]=oc;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new sc(this.encode,this.decode)}};function cc(e){return yr(e,oc)&&e[oc]===oc}var lc=e=>cc(e)?e:new sc(e.decode,e.encode);function uc(e){return new sc(Gs(e.decode),Gs(e.encode))}function dc(){return new sc(ec(),Hs())}var fc=new sc(Hs(),Hs());function pc(){return fc}var mc=new sc(Zs(),Xs()),hc=new sc(Qs(),Xs()),gc=new sc($s(),Ws(Ae)),_c=new sc(ic(),rc());function vc(e){return new sc(tc(e??{}),nc(e))}function yc(e){return t=>t._tag===e}var bc=yc(`Declaration`),xc=yc(`Null`),Sc=yc(`Undefined`),Cc=yc(`Never`),wc=yc(`String`),Tc=yc(`Number`),Ec=yc(`Boolean`),Dc=yc(`Literal`),Oc=yc(`UniqueSymbol`),kc=yc(`Arrays`),Ac=yc(`Objects`),jc=yc(`Union`),Mc=yc(`Suspend`),Nc=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Pc={},Fc=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Ic=`~effect/Schema`,Lc=class{[Ic]=Ic;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},Rc=class extends Lc{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===E?$o:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=du(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Rc(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},zc=new class extends Lc{_tag=`Null`;getParser(){return Mu(this,null)}getExpected(){return`null`}},Bc=class extends Lc{_tag=`Undefined`;getParser(){return Mu(this,void 0)}toCodecJson(){return $l(this,[Vc])}getExpected(){return`undefined`}},Vc=new Nc(zc,new sc(Ws(()=>void 0),Ws(()=>null))),Hc=new Bc,Uc=new class extends Lc{_tag=`Never`;getParser(){return Nu(this,Qt)}getExpected(){return`never`}},Wc=new class extends Lc{_tag=`Unknown`;getParser(){return Nu(this,re)}getExpected(){return`unknown`}},Gc=class extends Lc{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${S(e)}`);this.literal=e}getParser(){return Mu(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Kc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Kc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Kc(e){let t=globalThis.String(e.literal);return $l(e,[new Nc(new Gc(t),new sc(Ws(()=>e.literal),Ws(()=>t)))])}var qc=new class extends Lc{_tag=`String`;getParser(){return Nu(this,$r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Yu(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Jc=class extends Lc{_tag=`Number`;getParser(){return Nu(this,ln)}matchKey(e,t){return this._match(Ru,e,t)}matchPart(e,t){return this._match(Lu,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Yu(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Yc(this.checks,`effect/schema/isFinite`)||Yc(this.checks,`effect/schema/isInt`))?this:$l(this,[Jl])}toCodecStringTree(){return this.toCodecJson()===this?$l(this,[Vu]):$l(this,[Hu])}getExpected(){return`number`}};function Yc(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Yc(e.checks,t))}var Xc=new Jc,Zc=new class extends Lc{_tag=`Boolean`;getParser(){return Nu(this,zn)}getExpected(){return`boolean`}},Qc=new class extends Lc{_tag=`Symbol`;getParser(){return Nu(this,xt)}matchKey(e,t){return t.disableChecks||!this.checks?e:Yu(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return $l(this,[qu])}getExpected(){return`symbol`}},$c=new class extends Lc{_tag=`BigInt`;getParser(){return Nu(this,ar)}matchPart(e,t){if(!Uu.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Yu(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return $l(this,[Gu])}getExpected(){return`bigint`}},el=class extends Lc{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Su(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Su(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new ds(n,t[o],i),a=new ls([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return v(new fs(n,[a],t,i))}return e.issues?v(new fs(n,e.issues,t,i)):Qo(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Ur(t.concurrency),f=d===1?rl(i,e,0,u):il(i,e,{concurrency:d,end:u});if(!f)return c(i);if(ft(f))return sn(f,()=>c(i));let p=!0;return sr(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===E)return $o;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):v(new ps(n,e,a))}catch(e){return _r(e)}}}_rebuild(e,t,n){let r=du(this.elements,e),i=du(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new el(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function tl(e,t,n,r){if(n._tag===`Failure`)return al(e,e.ast,r,n);let i=n===es?t:n[$e];if(i!==E)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Su(t.ast))return;let n=new ls([r],new us(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return aa(new fs(e.ast,[n],e.input,e.options))}}var nl={onItem(e,t,n){let r=n<e.len?t:E;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:tl},rl=rn()(nl),il=Wn()(nl),al=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Ns(r.cause);if(i===void 0)return ia(qi(r.cause,r=>new fs(t,[new ls([n],r)],e.input,e.options)));let a=new ls([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return aa(new fs(t,[a],e.input,e.options))},ol=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function sl(e,t,n=Pc){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(Pu(Ou(t)))}var cl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ll(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ll);default:return!1}}function ul(e){let t=tu(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ul);default:return!1}}function dl(e){return ll(e)&&ul(e)}var fl=class{parameter;type;constructor(e,t){if(!dl(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Su(t)&&!ju(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},pl=class extends Lc{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Nu(n,qr);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(Pu(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return al(t,n,i,s)??sa;let c=s===es?o:s[$e];if(a!==E&&c!==E){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return sa;h(t.out,a,c)}return sa},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!ft(t))return T(Ln(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return al(e,n,r,a)??sa;let o=a===es?r:a[$e],s=e.input[r],l=i.parserValue(s,e.options);return ft(l)?t(e,r,o,s,l):T(Ln(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return ft(a)?t(e,n,n,i,a):T(Ln(a),r=>t(e,n,n,i,r))},u=i?Wn()({onItem:(e,[t,n])=>n.is.parameter===qc?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return p(function*(t,d){if(t===E)return E;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*v(new ps(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},ee=d.errors===`all`,te=d.onExcessProperty===`error`,ne=d.concurrency===void 0?1:Ur(d.concurrency),re=i&&te?n.indexSignatures.map(e=>sl(f,e.parameter,d)):void 0;if(te){let r=re?new Set(e):e;if(re)for(let e of re)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new ds(n,f[a],d),r=new ls([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*v(new fs(n,[r],t,d))}}}if(r){let e=ne===1?gl(m,a):_l(m,a,{concurrency:ne});e&&(yield*e)}if(i&&ne===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===qc?l:c,r=re?.[e]??(t.is.parameter===qc?Object.keys(f):sl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!ft(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=ut();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===qc?Object.keys(f):sl(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:ne});t&&(yield*t)}return m.issues?yield*v(new fs(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(Ln(n),n=>{let i=ml(e,r,n);if(i)return i;let o=()=>Qo(e.out),s=gl(e,a.slice(t+1));return s?sn(s,o):o()})};return(e,t)=>{if(e===E)return $o;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Ur(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return v(new ps(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=Al(i,s),l=c?i[s]:E,d=n.parser(l,t);if(!ft(d))return u(o,e,d);if(d===es){c&&h(a,s,l);continue}let f=ml(o,n,d);if(f)return f}}catch(e){return _r(e)}return Qo(a)}}_rebuild(e,t,n,r){let i=du(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new cl(t.name,n)}),a=du(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new fl(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new pl(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function ml(e,t,n){if(n._tag===`Failure`)return al(e,e.ast,t.name,n);if(n===es)return;let r=n[$e];if(r!==E){h(e.out,t.name,r);return}if(delete e.out[t.name],!Su(t.type)){let n=new ls([t.name],new us(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return aa(new fs(e.ast,[n],e.input,e.options))}}var hl={onItem(e,t){if(!Al(e.input,t.name))return t.parser(E,e.options);let n=e.input[t.name];return h(e.out,t.name,n),t.parser(n,e.options)},step:ml},gl=rn()(hl),_l=Wn()(hl);function vl(e,t){return e?t?[...e,...t]:e:t}function yl(e,t,n){return new pl(Reflect.ownKeys(e).map(t=>new cl(t,e[t].ast)),[],n,t)}function bl(e){return e.ast}function xl(e,t=void 0){return new el(!1,e.map(e=>e.ast),[],void 0,t)}function Sl(e,t,n){return new Ml(e.map(bl),t,void 0,n)}function Cl(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new el(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var wl=nt(e=>{for(;;){if(Mc(e))return Wc;let t=e.encoding;if(!t)return e.recur?.(wl,Ve)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==Ve))return Wc;e=t[t.length-1].to}});function Tl(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(Tl)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function El(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Uo];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Su(t)){if(Dc(t))return[{key:e.name,literal:t.literal}];if(Oc(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Su(e)){if(Dc(e))return[{key:t,literal:e.literal}];if(Oc(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>El(wl(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return El(e.thunk())}}var Dl=new WeakMap,Ol=Object.freeze([]),kl=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Al=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function jl(e){let t=Dl.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=wl(c);if(Cc(l))continue;if(Dc(l)||Oc(l)){a??=new Map;let e=Dc(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=El(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=Tl(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Ol);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Ol;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(ht(e)){let n=Al(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Ol;if(t)return o}return Ol}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=kl(t);if(!ht(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Al(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=Al(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=Al(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(kl(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Dl.set(e,t),t}var Ml=class extends Lc{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===E)return $o;let i=(o??=jl(n.types))(e,r);if(i.length===0)return v(new gs(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:ft(r)?Nl(n,r.cause,e,t):Pl(n,r,e,t)}return Fl(n,a,i,e,t)}}_rebuild(e,t,n){let r=du(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Ml(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=Ou(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Dc);if(t.length>0)return`${zl(n.isMutable)}[ ${t.map(t=>e(t)+Bl(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Dc(e.type));if(t.length>0)return`{ ${t.map(t=>`${zl(t.type.context?.isMutable)}${Rt(t.name)}${Bl(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Nl(e,t,n,r){let i=Ns(t);return i?aa(new gs(e,[i],n,r)):ia(t)}function Pl(e,t,n,r){return Br(t,t=>Nl(e,t,n,r))}function Fl(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=Ll(a,n);if(!o)return a.out?a.out:v(new gs(e,a.issues??[],r,i));if(ft(o))return Il(o,a);let s=!0;return sr(()=>s?(s=!1,Il(o,a)):Fl(e,t,n,r,i))}function Il(e,t){return sn(e,e=>t.out===es?x(t.input):t.out?t.out:v(new gs(t.ast,t.issues??[],t.input,t.options)))}var Ll=rn()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Ns(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),aa(new _s(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return sa}}}),Rl=new Ml([new Gc(`Infinity`),new Gc(`-Infinity`),new Gc(`NaN`)]);function zl(e){return e?``:`readonly `}function Bl(e){return e?`?`:``}var Vl=class extends Lc{_tag=`Suspend`;thunk;constructor(e,t,n,r,i){if(n)throw Error(`Cannot add checks to Suspend`);super(t,void 0,r,i);let a;this.thunk=()=>a??=e()}getParser(e){let t;return(n,r)=>(t??=e(this.thunk()))(n,r)}recur(e){return new Vl(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Hl=class extends fe{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Hl(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Hl(this.run,this.annotations,!0)}and(e,t){return new Ul([this,e],t)}},Ul=class extends fe{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ul(this.checks,{...this.annotations,...e})}and(e,t){return new Ul([this,e],t)}};function Wl(e,t,n=!1){return new Hl((t,n,r)=>bs(n,e(t,n,r),t,r),t,n)}function Gl(e,t){return new Hl((t,n,r)=>e(t)?void 0:new ms(void 0,t,r),t,!0)}function Kl(e){return Wl(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var ql=iu(Xc,[Kl()]),Jl=new Nc(new Ml([ql,Rl]),new sc(Zs(),Ws(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Yl(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Wl(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var Xl=new WeakMap;function Zl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Xl.set(n,Ql(e)),n}function Ql(e){let t=Xl.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Xl.set(e,n),n}function $l(e,t){return e.encoding===t?e:Zl(e,{encoding:t})}function eu(e,t){if(e.context===t)return e;let n=Ql(e);return n.context===t&&n.encoding===e.encoding?n:Zl(e,{context:t})}function tu(e){return e.encoding?tu(e.encoding[e.encoding.length-1].to):e}function nu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return ru(e,Le(e.checks.slice(0,-1),n.annotate(t)))}return Zl(e,{annotations:{...e.annotations,...t}})}function ru(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Zl(e,{checks:t})}function iu(e,t){return ru(e,vl(e.checks,t))}function au(e,t){let n=t(e.to);return n===e.to?e:new Nc(n,e.transformation)}function ou(e,t){let n=e,r=n[n.length-1],i=au(r,t);return i===r?e:Le(e.slice(0,e.length-1),i)}function su(e){return t=>t.encoding?$l(t,ou(t.encoding,e)):t}function cu(e,t){return su(e=>eu(e,t))(e)}function lu(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:$l(r,ou(r.encoding,n))}return e(r)}return nt(n)}function uu(e,t,n){let r=new Nc(e,t);return $l(n,n.encoding?[...n.encoding,r]:[r])}function du(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function fu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Fc(!1,!1,void 0,t))}var pu=nt(e=>mu(eu(e,e.context?e.context.isOptional===!1?new Fc(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!0,!1)))),mu=su(pu),hu=Ke(e=>pu(new Ml([e,Hc]))),gu=nt(e=>_u(eu(e,e.context?e.context.isMutable===!1?new Fc(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!1,!0)))),_u=su(gu);function vu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Fc(!1,!1,t))}function yu(e,t,n){return uu(e,n,t)}function bu(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:m(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function xu(e,t){let{literals:n,parameters:r}=bu(e);return new pl(n.map(e=>new cl(e,t)),r.map(e=>new fl(e,t)))}function Su(e){return e.context?.isOptional??!1}function Cu(e){return e.context?.isMutable??!1}function wu(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(wu)}function Tu(e){function t(e){return wu(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return u(n)?n:void 0}function Eu(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Mc(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var Du=nt(e=>{let t=Ql(e);if(t!==e){let n=Du(t);return n===t&&e.encoding===void 0?e:eu(n,e.context)}let n=`recur`in e?e.recur(Du):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Eu(e)?n.encodingChecks:kc(n)||Ac(n)||bc(n)&&n.typeParameters.length>0?Tu(n.encodingChecks):void 0;return Zl(n,{encodingChecks:void 0,checks:vl(n.checks,t)})}return n}),Ou=nt(e=>Du(Au(e)));function ku(e,t){let n=t,r=n.length,i=n[r-1],a=[new Nc(Au($l(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Nc(Au(n[e-1].to),n[e].transformation.flip()));let o=Au(i.to);return o.encoding?$l(o,[...o.encoding,...a]):$l(o,a)}var Au=Ke(e=>{if(e.encoding)return ku(e,e.encoding);let t=Ql(e);if(t!==e){let n=Au(t);return n===t?e:eu(n,e.context)}return`flip`in e?e.flip(Au):`recur`in e?e.recur(Au):e});function ju(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(ju);default:return!1}}function Mu(e,t){let n=t===0?es:Qo(t);return(r,i)=>r===E?$o:r===t?n:v(new ps(e,r,i))}function Nu(e,t){return(n,r)=>n===E?$o:t(n)?es:v(new ps(e,n,r))}var Pu=lu(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Pu)}}),Fu=lu(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Fu)}}),Iu=`[\\s\\S]*?`,Lu=new globalThis.RegExp(`^${ol}$`),Ru=new globalThis.RegExp(`^(?:${ol}|Infinity|-Infinity|NaN)$`);function zu(e){return Yl(Lu,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Lu.source}),...e})}var Bu=iu(qc,[zu()]),Vu=new Nc(Bu,mc),Hu=new Nc(new Ml([Bu,Rl]),mc),Uu=new globalThis.RegExp(`^-?\\d+$`);function Wu(e){return Yl(Uu,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Uu.source}),...e})}var Gu=new Nc(iu(qc,[Wu({expected:`a string representing a bigint`})]),hc),Ku=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),qu=new Nc(iu(qc,[Ju()]),new sc(Ws(e=>globalThis.Symbol.for(Ku.exec(e)[1])),Gs((e,t)=>globalThis.Symbol.keyFor(e)===void 0?v(new hs({message:`cannot serialize to string, Symbol is not registered`},e,t)):x(globalThis.String(e)))));function Ju(e){return Yl(Ku,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:Ku.source}),...e})}function Yu(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Yu(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new ss(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Xu(e){if(!bc(e))return;let t=e.annotations?.[Wo];return Nn(t)?t(e.typeParameters):void 0}var Zu=zo,Qu=Jo,$u=Yo;function ed(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function td(e){return e===void 0||typeof e==`string`}function nd(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function rd(e){return nd(e,ed)}var id=new Rc([],()=>(e,t,n)=>rd(e)?es:v(new ps(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>cd}),ad=new Nc(id,pc()),od=new Nc(new Ml([new el(!1,[],[id]),new pl([],[new fl(qc,id)])]),pc());function sd(e){return nd(e,td)}var cd=new Nc(new Rc([],()=>(e,t,n)=>sd(e)?es:v(new ps(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),pc()),ld=(e,t,n)=>e===es?n(t):sn(e,n);function ud(e){if(e._tag===`Middleware`)return(t,n,r)=>dd(t===es?e.decode(Qo(ts(n)),r):e.decode(Fe(t,ts),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===es?Qo(t):e;case`Transform`:{let e=e=>e===E?$o:Qo(t.transform(e));return(t,n)=>ld(t,n,e)}case`TransformOptional`:{let e=e=>ns(t.transform(ts(e)));return(t,n)=>ld(t,n,e)}case`TransformEffect`:return(e,n,r)=>ld(e,n,e=>e===E?$o:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>ld(e,n,e=>dd(t.transform(ts(e),r)))}}var dd=e=>sn(e,ns),fd=(e,t,n,r)=>Br(r,r=>Kr(()=>qi(r,r=>new cs(e,r,t,n))));function pd(e,t){let n=ud(e.link.transformation),r;return(i,a)=>{if(i===E)return $o;if(e.isConstructed(i))return es;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function md(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==E&&r!==void 0)return t(r,i);let a=n;if(ft(a)&&a._tag===`Success`){let e=t(a[$e],i);return e===es?a:e}return sn(fd(e,r,i,a),e=>{let n=t(e,i);return n===es?Qo(e):n})}}function hd(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:md(e,n)}function gd(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Xu(e):void 0,o=a?pd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>ud(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(ft(r)){if(r._tag===`Success`){let i=r===es?t:r[$e];if(t!==E&&i!==E){let i=Yu(u,t,void 0,e,n);i&&(r=v(new fs(e,i,t,n)))}}}else r=T(r,r=>{if(t!==E&&r!==E){let r=Yu(u,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(r)})}if(s&&!n.disableChecks){if(ft(r)){if(r._tag===`Success`){let i=r===es?t:r[$e];if(i===E)return r;let a=Yu(s,i,void 0,e,n);a&&(r=v(new fs(e,a,i,n)))}}else r=T(r,t=>{if(t!==E){let r=Yu(s,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[$e],o=t(a,r)):o=sn(o,e=>{let n=t(e,r);return n===es?Qo(e):n})}if(o._tag===`Success`){let e=o[$e],t=p(e,r);return t===es?o:t}return o=fd(e,n,r,o),sn(o,e=>{let t=p(e,r);return t===es?Qo(e):t})}:p}var _d=Symbol(),vd=new WeakMap,yd=e=>Cd(e).parser,bd=e=>Cd(e).makeEffect,xd=e=>hd(e,bd),Sd=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=gd(this.ast,yd)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=gd(this.ast,bd,xd)}};function Cd(e){let t=vd.get(e);if(t!==void 0)return t;let n=new Sd(e);return vd.set(e,n),n}function wd(e){let t=e.ast,n;return(e,r)=>(n??=Vd(Jd,Du(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Td(e){let t=wd(e);return(e,n)=>{let r=Pr(t(e,n));return ca(r)?xr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Sn())}}function Ed(e){return Kd(Du(e.ast))}function Dd(e){return kd(e.ast)}function Od(e){{let t=Hd(zd(e));return e=>{let n=t(e,Pc);return ca(n)?!0:(Ps(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function kd(e){let t=Du(e),n=e=>(n=Od(t),n(e));return e=>n(e)}function Ad(e,t){let n=zd(e.ast);return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function jd(e,t){return Hd(Ad(e,t))}function Md(e,t){return Ud(Ad(e,t))}function Nd(e,t){return Wd(Ad(e,t))}function Pd(e,t){let n=zd(Au(e.ast));return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function Fd(e,t){return Hd(Pd(e,t))}function Id(e,t){return Wd(Pd(e,t))}var Ld=(e,t)=>t?{...e,...t}:e,Rd=e=>e===E?v(new ms):x(e);function zd(e){return Vd(qd,e)}function Bd(e,t){return e===es?x(t):ft(e)?e[$e]===E?Rd(E):e:sn(e,Rd)}function Vd(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Pc);return a===es?x(r):ft(a)?a[$e]===E?Rd(E):a:sn(a,Rd)}}function Hd(e){return(t,n)=>Pr(e(t,n))}function Ud(e){let t=Hd(e);return(e,n)=>{let r=t(e,n);return ca(r)?xr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Sn())}}function Wd(e){let n=Hd(e);return(e,r)=>{let i=n(e,r);return ca(i)?t(i.value):_e(Ps(i.cause,`Result adapter can only return schema issues`))}}function Gd(e,t){let n=Pr(e);if(ca(n))return n.value;let r=Ps(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Kd(e){let t,n;return(r,i)=>{t??=Cd(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Pc,o=t.make;if(o!==void 0&&r!==E){let e;try{e=o(r,a)}catch(e){throw Ps(Gi(e),`Constructor adapter can only throw schema issues`),e}if(e!==_d&&e!==E)return e}return Gd(Bd((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var qd=e=>Cd(e).parser,Jd=e=>Cd(e).makeEffect,Yd=`~effect/Schema/Schema`,Xd=Symbol(),Zd={[Yd]:Yd,get make(){let e=Ed(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=wd(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Td(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Ie(this,arguments)},annotate(e){return this.rebuild(nu(this.ast,e))},annotateKey(e){return this.rebuild(fu(this.ast,e))},check(...e){return this.rebuild(iu(this.ast,e))},rebuild(e){return Qd(e,this[Xd])}};function Qd(e,t){function n(){}let r=Object.setPrototypeOf(n,Zd);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Xd]=t,r.ast=e,r}function $d(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ef(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function tf(e){return encodeURI($d(e)).replace(/#/g,`%23`)}function nf(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function rf(e){let t=nf(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(ef)}function af(e){return e.reduce((e,t)=>`${e}/${tf(t)}`,`#`)}var of=`http://json-schema.org/draft-07/schema#`;function sf(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function cf(e){return{dialect:`draft-07`,...bf(e,Mf)}}function lf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!ri(e))return e;let a=r||!i&&yf(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=ff(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}h(o,t,i)}return t(o,a),o}}function uf(e,t){return lf(e,e=>{df(e,t)})}function df(e,t){typeof e.$ref==`string`&&h(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&h(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function ff(e,t){if(!ri(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function pf(e,t,n){let r=new Map,i=[],a=mf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=gf(ri(e)?u(e):void 0,mf)??mf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=hf(t,n);if(a!==void 0){let e=rf(a.hash);if(a.hash=``,e!==void 0){let n=r.get(vf(a.href,e));n!==void 0&&(i=_f(t,n))}}h(e,`$ref`,i)}}let c=n(o);return s(),c;function l(n,r,a,o){if(typeof n==`boolean`)return d(r,a,o),t?.booleanAdapter?.(n)??n;if(!ri(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&yf(c)){let e=gf(c,o.uri);e!==void 0&&(s={parent:o,sourceRoot:r,targetRoot:a,uri:e})}d(r,a,s);let f=s.uri;return e(n,{isDocumentRoot:r.length===0,schema(e,t,n=t){return l(e,[...r,t],[...a,n],s)},schemaAt(e,t,n){return l(e,[...r,...t],[...a,...n],s)},schemaArray(e,t,n=t){return Array.isArray(e)?e.map((e,i)=>l(e,[...r,t,String(i)],[...a,n,String(i)],s)):e},schemaMap(e,t,n=t){return ri(e)?ff(e,(e,i)=>l(e,[...r,t,i],[...a,n,i],s)):e},reference(e,t){typeof t==`string`?i.push([e,t,f]):h(e,`$ref`,t)}})}function u(e){return t?.ignoreRefSiblings===!0&&typeof e.$ref==`string`?void 0:e.$id}function d(e,t,n){n.parent!==void 0&&d(e,t,n.parent),r.set(vf(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var mf=`https://effect.invalid/.json-schema/`;function hf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function gf(e,t){if(typeof e!=`string`)return;let n=hf(e,t);if(n!==void 0)return n.hash=``,n.href}function _f(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${af(t)}`}function vf(e,t){return`${e}\u0000${JSON.stringify(t)}`}function yf(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function bf(e,t,n){return pf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:ff(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var xf=new Set([`properties`,`patternProperties`]),Sf=new Set([`allOf`,`anyOf`,`oneOf`]),Cf=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function wf(e,t,n,r,i,a=xf){let o;if(a.has(t))o=r.schemaMap(n,t);else if(Sf.has(t))o=r.schemaArray(n,t);else if(i.has(t))o=r.schema(n,t);else return!1;return h(e,t,o),!0}var Tf=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Tf],[...Tf];var Ef=/^[A-Za-z_][-A-Za-z0-9._]*$/,Df=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Of(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function kf(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Of(i,n,`it is not active in ${r} but would become active in the target`)}var Af=[`additionalItems`,`definitions`,`dependencies`];function jf(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,sf(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):sf(t,`https://json-schema.org/draft/2020-12/schema`)||Of(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Mf(e,t){kf(e,Af,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!wf(n,o,s,t,Cf))switch(o){case`$ref`:r=s;break;case`$schema`:jf(n,s,t,of,`Draft-07`);break;case`$id`:case`$anchor`:break;case`$defs`:h(n,`definitions`,t.schemaMap(s,o,`definitions`));break;case`prefixItems`:i=s;break;case`items`:a=s;break;case`dependentRequired`:case`dependentSchemas`:case`minContains`:case`maxContains`:break;case`$dynamicRef`:case`$dynamicAnchor`:case`$vocabulary`:case`unevaluatedProperties`:case`unevaluatedItems`:Of(o,`Draft-07`,`the target dialect has no equivalent`);case`required`:if(Array.isArray(s)&&s.length===0)break;h(n,o,s);break;default:h(n,o,s)}}if(Nf(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Of(`minContains/maxContains`,`Draft-07`,`contains cardinality cannot be represented`),Object.hasOwn(e,`minContains`)&&h(n,`minContains`,t)}else Object.hasOwn(e,`minContains`)&&h(n,`minContains`,e.minContains),Object.hasOwn(e,`maxContains`)&&h(n,`maxContains`,e.maxContains);return Ff(e,n,t,`draft-07`),Lf(e,n,`$id`,`Draft-07`),Pf(n,r,t),n}function Nf(e,t,n,r){if(t===void 0){n!==void 0&&h(e,`items`,r.schema(n,`items`));return}h(e,`items`,r.schemaArray(t,`prefixItems`,`items`)),n!==void 0&&h(e,`additionalItems`,r.schema(n,`items`,`additionalItems`))}function Pf(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),If(e,r)}else n.reference(e,t)}}function Ff(e,t,n,r){let i=ri(e.dependentRequired)?e.dependentRequired:void 0,a=ri(e.dependentSchemas)?e.dependentSchemas:void 0;if(i===void 0&&a===void 0)return;let o={},s=new Set([...Object.keys(i??{}),...Object.keys(a??{})]);for(let e of s){let t=i?.[e],s=a?.[e],c=r===`draft-04`&&Array.isArray(t)&&t.length===0;s===void 0?c||h(o,e,t):t===void 0||c?h(o,e,n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e])):h(o,e,{allOf:[n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e,`allOf`,`0`]),{required:t}]})}Object.keys(o).length>0&&h(t,`dependencies`,o)}function If(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function Lf(e,t,n,r){let i=e.$id,a=e.$anchor;if(a===void 0){i!==void 0&&h(t,n,i);return}(typeof a!=`string`||!Ef.test(a))&&Of(`$anchor`,r,`the anchor is not valid`),Df.test(a)||Of(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):Of(`$anchor`,r,`it cannot be combined with the schema $id`)}function Rf(e){return Qd(zf(e.ast),{schema:e})}var zf=lu(e=>{let t=Wf(e,zf),n=e.context;return t===e||n===void 0?t:cu(t,Bf(n))});function Bf(e){return e.constructorDefault===void 0?e:new Fc(e.isOptional,e.isMutable,void 0,e.annotations)}function Vf(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Hf(e){return t=>{let n=[...t].sort((t,n)=>e(Ou(t))-e(Ou(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Uf=Hf(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wf(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Nn(n))return $l(e,[ad]);let r=n(e.typeParameters.map(e=>Qd(Ou(e))));return r===void 0?e:$l(e,[au(r,t)])}case`Unknown`:return $l(e,[ad]);case`ObjectKeyword`:return $l(e,[od]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Vf(e),e.recur(t,Fu);case`Union`:{let n=Uf(e.types);return n===e.types?e.recur(t):new Ml(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}globalThis.RegExp;var Gf=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Kf(e,t){return t.length>0&&(e+=`\n at ${Ut(t)}`),Error(e)}function qf(e){return`#/$defs/${tf(e)}`}var Jf=new Set([...Zo,Ho,...Go]);function Yf(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;rd(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&rd(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(rd(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))Jf.has(r)||!t.includeAnnotationKey(r)||rd(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function Xf(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=Xf(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function Zf(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}var Qf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function $f(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function ep(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var tp=`|title|description|default|examples|readOnly|writeOnly|`,np=Qf+tp;function rp(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Zf(e);if(i!==void 0||a){let r=Xf(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:$f(r.schema,tp)&&ep(o,s)?{...o,...r.schema}:rp(o,r.schema,n)}}if(n&&ep(e,r))return{...e,...t};let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function ip(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>ip(e,t)))}function ap(e){return Array.isArray(e)}function op(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=Tt(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!ip(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=te(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Er(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Tt(u,ee),f={};for(let e of l)a.has(e)||h(f,e,ee(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw Kf(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=re(n[e],[`references`,e],a[1]),a}function ee(e){return uf(e,e=>{let t=nf(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(ef(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,qf(r))})}function te(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[Ho]:void 0}function ne(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>re(e,[...n,`representation`,`schemas`,t],i))??[]}),c=ap(s);c&&i.push(!1);let l=c?s[0]:s,u=Yf(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Qf:np;return[d,e._tag===`Filter`&&$f(d,f)&&(u===void 0||$f(u,tp))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=ne(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Yf(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function re(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:qf(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=ie(e,t,a),c=Yf(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&sp(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=rp(s,...i))}return o.set(e,[s,a]),p(s)}function ie(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return re(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw Kf(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(lp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Kf(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=re(e.type,[...t,`elements`,i,`type`],n),s=Yf(e.annotations,r);return s===void 0?o:p(rp(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=re(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw Kf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=Yf(s.annotations,r);h(a,c,u===void 0?l:p(rp(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=re(i.type,[...t,`indexSignatures`,r,`type`],n);Er(a,{not:{}})&&(a=!1),l.push(a);let o=ae(i.parameter,[...t,`indexSignatures`,r,`parameter`],new Set);if(o===void 0){u=!0,n.push(!1);continue}if(o.length===0)c.push(a);else for(let e of o){let t=s[e];h(s,e,t===void 0?a:t===!1||a===!1?!1:p(rp(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(re(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>re(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=cp(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function ae(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw Kf(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ae(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=re(e,t,n);return ip(n)&&r.type===`string`&&typeof r.pattern==`string`&&$f(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lp).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=ae(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw Kf(`Invalid schema representation document`,t)}}}function sp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function cp(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function lp(e){switch(e._tag){case`Literal`:return Gf(globalThis.String(e.literal));case`String`:return Iu;case`Number`:return ol;case`TemplateLiteral`:return e.parts.map(lp).join(``);case`Union`:return`(?:${e.types.map(lp).join(`|`)})`;default:throw Kf(`Invalid schema representation document`,[])}}function up(e,t){let n=op([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var dp=({identifier:e})=>e;function fp(e){return e===void 0?void 0:{annotations:e}}function pp(e,t){let{references:n,representations:r}=mp([e],t);return{representation:r[0],references:n}}function mp(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)f(t);let s=t?.referencePolicy??dp;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:Tt(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:nu(e,{identifier:n}):qo(e)===r?e:nu(e,{[Ho]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=ee(t);i.delete(e),h(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=tu(e),n=Ql(t),r=Ko(t),i=r===void 0?(t===e?void 0:Ko(e))??qo(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t)){t.isRecursive=!0;return}if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(Du(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?ee(n):u(r,t.identifier===void 0?n:l(n,t,r))}function ee(e){let t=te(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...re(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...fp(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...fp(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...fp(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...fp(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=tu(e),n=t.context?.annotations;return{isOptional:Su(t),type:m(e),...fp(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=tu(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Su(t),isMutable:Cu(t),...fp(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...fp(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...fp(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...fp(e.annotations)}}}function te(e){return e?.map(ne)??[]}function ne(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...ie(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:Tt(e.checks,ne),...ie(e.annotations)}}}function re(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function ie(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(Du(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function hp(e){return ca(e)?e.value:{issues:[{message:$i(e.cause)}]}}function gp(e,t){let n=Ad(e),r={errors:`all`,...t?.parseOptions},i=Cs(t),a=e=>{let t=new St(`sync`),a=ur(l(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?hp(o):new Promise(e=>{a.addObserver(t=>{e(hp(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}function _p(e){return up(pp(zf(e)))}function vp(e,t){let n=_p(e);if(t===`draft-2020-12`){let e=n.schema;return Object.keys(n.definitions).length>0&&(e.$defs=n.definitions),e}if(t===`draft-07`){let e=cf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function yp(e){let t={input(t){return vp(e.ast,t.target)},output(t){return vp(Du(e.ast),t.target)}};if(Object.hasOwn(e,`~standard`)){let n=e;return`jsonSchema`in n[`~standard`]||Object.assign(n[`~standard`],{jsonSchema:t}),n}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,jsonSchema:t}})}var bp=Ke(e=>xp(e));function xp(e){let t=zo(e)?.toEquivalence;if(t)return t(bc(e)?e.typeParameters.map(xp):[]);switch(e._tag){case`Never`:return cr();case`Declaration`:return Sp(e);case`Null`:case`Undefined`:case`Void`:case`Unknown`:case`Any`:case`String`:case`Number`:case`Boolean`:case`BigInt`:case`Symbol`:case`Literal`:case`UniqueSymbol`:case`ObjectKeyword`:case`Enum`:case`TemplateLiteral`:return Er;case`Arrays`:{let t=e.elements.map(xp),n=e.rest.map(xp),[r,...i]=n,a=i.length;return Lr((o,s)=>{if(!Array.isArray(o)||!Array.isArray(s))return!1;let c=o.length;if(c!==s.length)return!1;let l=0;for(;l<Math.min(c,e.elements.length);l++)if(!t[l](o[l],s[l]))return!1;if(n.length>0){for(;l<c-a;l++)if(!r(o[l],s[l]))return!1;for(let e=0;e<a;e++)if(!i[e](o[l+e],s[l+e]))return!1}return!0})}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Er;let t=e.propertySignatures.map(e=>xp(e.type)),n=e.indexSignatures.map(e=>xp(e.type));return Lr((r,i)=>{if(!ri(r)||!ri(i))return!1;for(let n=0;n<t.length;n++){let a=e.propertySignatures[n],o=a.name,s=Object.hasOwn(r,o),c=Object.hasOwn(i,o);if(Su(a.type)&&s!==c||s&&c&&!t[n](r[o],i[o]))return!1}for(let t=0;t<n.length;t++){let a=e.indexSignatures[t],o=sl(r,a.parameter),s=sl(i,a.parameter);if(o.length!==s.length)return!1;for(let e=0;e<o.length;e++){let a=o[e];if(!Object.hasOwn(i,a)||!n[t](r[a],i[a]))return!1}}return!0})}case`Union`:{let t=Du(e).types,n=jl(t),r=t.map((t,n)=>[kd(t),xp(e.types[n])]);return Lr((e,t)=>{let i=n(e,!1);for(let n=0;n<i.length;n++){let[a,o]=r[i[n]];if(a(e)&&a(t))return o(e,t)}return!1})}case`Suspend`:{let t;return Lr((n,r)=>(t??=bp(e.thunk()))(n,r))}}}function Sp(e){let t=e.annotations?.representation;if(t===void 0)return Er;switch(t.id){case`effect/schema/Option`:{let[t]=Cp(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=Cp(e);return(e,r)=>e._tag===r._tag&&(e._tag===`Success`?t(e.success,r.success):n(e.failure,r.failure))}case`effect/schema/CauseReason`:{let[t,n]=Cp(e);return wp(t,n)}case`effect/schema/Cause`:{let[t,n]=Cp(e);return Tp(t,n)}case`effect/schema/Exit`:{let[t,n,r]=Cp(e),i=Tp(n,r);return(e,n)=>e._tag===n._tag&&(e._tag===`Success`?t(e.value,n.value):i(e.cause,n.cause))}case`effect/schema/ReadonlyMap`:{let[t,n]=Cp(e);return Un(t,n)}case`effect/schema/ReadonlySet`:return nn(Cp(e)[0]);case`effect/schema/RegExp`:return(e,t)=>e.source===t.source&&e.flags===t.flags;case`effect/schema/URL`:return(e,t)=>e.toString()===t.toString();default:return Er}}function Cp(e){return e.typeParameters.map(xp)}function wp(e,t){return(n,r)=>{if(n._tag!==r._tag)return!1;switch(n._tag){case`Fail`:return e(n.error,r.error);case`Die`:return t(n.defect,r.defect);case`Interrupt`:return n.fiberId===r.fiberId}}}function Tp(e,t){let r=n(wp(e,t));return(e,t)=>r(e.reasons,t.reasons)}var Ep=a(2,(e,t)=>({...e,...t})),Dp=e=>e,Op=`~effect/Schema/SchemaError`;function kp(e){return yr(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var Ap=Yd;function jp(){return(e,t,n)=>$p(new Rc(e.map(bl),e=>t(e.map(e=>$p(e))),n))}function Mp(e,t){return jp()([],()=>(t,n,r)=>e(t)?x(t):v(new ps(n,t,r)),t)}var Np=class extends zi(`SchemaError`){[Op]=Op;constructor(e){let t=Et();Pt(0);try{super({issue:e})}finally{Pt(t)}}get message(){return As(this.issue)}toString(){return`SchemaError(${this.message})`}};function Pp(e){return kp(e)}function Fp(e){return ft(e)?Ip(e):Br(e,e=>Kr(()=>qi(e,e=>new Np(e))))}function Ip(e){return ca(e)?e:ia(qi(e.cause,e=>new Np(e)))}function Lp(e,t){let n;for(let r of e.reasons){if(!Hi(r)||!Pp(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function Rp(e){let t=Pr(e);if(ca(t))return t.value;throw Lp(t.cause,`Sync adapter can only throw schema errors`)}function zp(e,t){return gp(e,t)}function Bp(e){return yp(e)}var Vp=Dd;function Hp(e,t){let n=Ad(e,t);return(e,t)=>Fp(n(e,t))}function Up(e,t){let n=jd(e,t);return(e,t)=>Ip(n(e,t))}var Wp=Md;function D(e,t){let n=Nd(e,t);return(e,t)=>Jt(n(e,t),e=>new Np(e))}var Gp=D;function O(e,t){let n=Hp(e,t);return(e,t)=>Rp(n(e,t))}var Kp=O;function qp(e,t){let n=Pd(e,t);return(e,t)=>Fp(n(e,t))}function Jp(e,t){let n=Fd(e,t);return(e,t)=>Ip(n(e,t))}function Yp(e,t){let n=Id(e,t);return(e,t)=>Jt(n(e,t),e=>new Np(e))}var Xp=Yp;function Zp(e,t){let n=qp(e,t);return(e,t)=>Rp(n(e,t))}var Qp=Zp,$p=Qd;function em(e){return yr(e,Ap)&&e[Ap]===Ap}var k=Dp(e=>$p(pu(e.ast),{schema:e})),A=Dp(e=>{let t=vm(e);return $p(hu(e.ast),{schema:t})}),tm=Dp(e=>$p(gu(e.ast),{schema:e})),nm=Dp(e=>$p(Du(e.ast),{schema:e})),rm=Dp(e=>$p(Ou(e.ast),{schema:e}));function j(e){let t=$p(new Gc(e),{literal:e,transform(n){return t.pipe(Sm(j(n),{decode:Ws(()=>n),encode:Ws(()=>e)}))}});return t}var im=$p(Uc),am=$p(Wc),om=$p(zc),sm=$p(Hc),M=$p(qc),N=$p(Xc),cm=$p(Zc),lm=$p(Qc),um=$p($c);function dm(e,t){return $p(e,{fields:t,mapFields(e,t){let n=e(this.fields);return dm(yl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e){return dm(yl(e,void 0),e)}function fm(e,t){return $p(xu(e.ast,t.ast),{key:e,value:t})}function pm(e,t){return $p(e,{elements:t,mapElements(e,t){let n=e(this.elements);return pm(xl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function mm(e){return pm(xl(e),e)}var F=Dp(e=>$p(new el(!1,[],[e.ast]),{value:e})),hm=Dp(e=>$p(new el(!1,[e.ast],[e.ast]),{value:e})),gm=Dp(e=>$p(Cl(e.ast),{schema:e}));function _m(e,t){return $p(e,{members:t,mapMembers(e,t){let n=e(this.members);return _m(Sl(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function I(e,t){return _m(Sl(e,t,void 0),e)}function L(e){let t=e.map(j);return $p(Sl(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return I(e(this.members))},pick(e){return L(e)},transform(e){return I(t.map((t,n)=>t.transform(e[n])))}})}var R=Dp(e=>I([e,om])),vm=Dp(e=>I([e,sm]));function ym(e){return $p(new Vl(()=>e().ast))}function z(...e){return t=>t.check(...e)}function bm(e,t){return n=>$p(iu(n.ast,[Gl(e,t)]),{schema:n})}function xm(e){return t=>$p(t.ast,{schema:t,identifier:e})}function Sm(e,t){return n=>$p(yu(n.ast,e.ast,t?lc(t):pc()),{from:n,to:e})}function Cm(){return(e,t)=>jm()(e,{decode:t,encode:Bs})}function wm(e,t){return n=>t?Sm(n,t)(e):Sm(n)(e)}function Tm(e){return t=>$p(vu(t.ast,e),{schema:t})}function Em(e){return Br(e,e=>Kr(()=>qi(e,e=>e.issue)))}function Dm(e,t){let n=t?.encodingStrategy===`omit`?Js():Hs();return t=>A(rm(t)).pipe(Sm(t,{decode:Ys(Em(e)),encode:n}))}function Om(e,t){return n=>nm(n).pipe(Dm(e,t),wm(A(n)))}function km(e){return j(e).pipe(Tm(x(e)))}function Am(e,t){return Mp(t=>t instanceof e,t)}function jm(){return(e,t)=>new Nc(e.ast,lc(t))}var B=Wl,Mm=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Nm(e){let t=new globalThis.RegExp(Mm);return B(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:Mm,flags:``}]},...e})}function Pm(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${S(n)})`:`new RegExp(${S(n)}, ${S(r)})`;return Yl(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var Fm=e=>e?new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;function Im(e,t){let n=Fm(e);return Pm(n,{expected:e?`a UUID v${e}`:`a UUID`,representation:{id:`effect/schema/isUUID`,payload:{version:e??null}},toJsonSchema:()=>({pattern:n.source,format:`uuid`}),toCode:()=>({runtime:e===void 0?`Schema.isUUID()`:`Schema.isUUID(${e})`}),...t})}function Lm(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Pm(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Rm(e,t,n){if(e.length===0)return t.length===0?{}:[{},!0];let r={pattern:new globalThis.RegExp(n).source};return e===t?r:[r,!0]}function zm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${Gf(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return B(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>Rm(i,e,`^${Gf(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Bm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${Gf(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return B(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>Rm(i,e,`${Gf(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Vm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(Gf(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return B(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>Rm(i,e,Gf(i)),toCode:()=>({runtime:`Schema.isIncluding(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Hm=$p(ql),Um=Kl;function Wm(e){let t=ui(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function Gm(e){let t=dn(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function Km(e){let t=ai(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function qm(e){let t=_t(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function Jm(e){let t=dn(e.order),n=ui(e.order),r=_t(e.order),i=ai(e.order),a=e.formatter??S;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return B(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function Ym(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${S(e)}`);return e}var Xm=Wm({order:en,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Ym(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${S(e)})`})})}),V=Gm({order:en,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Ym(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${S(e)})`})})}),Zm=Km({order:en,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Ym(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${S(e)})`})})}),Qm=qm({order:en,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Ym(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${S(e)})`})})}),$m=Jm({order:en,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Ym(e.minimum),maximum:Ym(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function eh(e,t){if(!globalThis.Number.isFinite(e)||e===0)throw new globalThis.RangeError(`Expected a finite non-zero number, got ${globalThis.String(e)}`);return e=globalThis.Math.abs(e),B(t=>Ya(t,e)===0,{expected:`a value that is a multiple of ${e}`,representation:{id:`effect/schema/isMultipleOf`,payload:{divisor:e}},toJsonSchema:()=>({multipleOf:e}),toCode:()=>({runtime:`Schema.isMultipleOf(${S(e)})`}),...t})}function th(e){return B(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var H=N.check(th()),nh=H.check(V(0));function rh(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${S(e)}`);return e.toISOString()}function ih(e){return`new Date(${S(e.getTime())})`}var ah=Wm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${ih(e)})`})})}),oh=Gm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${ih(e)})`})})}),sh=Km({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${ih(e)})`})})}),ch=qm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${ih(e)})`})})}),lh=Jm({order:Fn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:rh(e.minimum),maximum:rh(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${ih(e.minimum)}, maximum: ${ih(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}}),uh=Wm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${S(e)})`})})}),dh=Gm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${S(e)})`})})}),fh=Km({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${S(e)})`})})}),ph=qm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${S(e)})`})})}),mh=Jm({order:Vn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenBigInt`,payload:{minimum:e.minimum.toString(10),maximum:e.maximum.toString(10),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenBigInt({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function hh(e,t){return e=wh(e),gh(e,Math.ceil(e/2),t)}function gh(e,t,n){return B(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Vo]:!0,arbitraryConstraint:{minLength:e},...n})}function _h(e){return gh(1,1,e)}function vh(e,t){return e=wh(e),B(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Vo]:!0,arbitraryConstraint:{maxLength:e},...t})}function yh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.length>=e&&n.length<=t,{expected:e===t?`a value with a length of ${e}`:`a value with a length between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenLength`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`string`?t===0||Math.ceil(e/2)>t?{minLength:Math.ceil(e/2),maxLength:t}:[{minLength:Math.ceil(e/2),maxLength:t},!0]:n===`array`?{minItems:e,maxItems:t}:n===void 0?[{minLength:Math.ceil(e/2),maxLength:t,minItems:e,maxItems:t},!0]:[{},!0],toCode:()=>({runtime:`Schema.isBetweenLength(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function bh(e,t){return e=wh(e),B(t=>Ch(t,e)>=e,{expected:`a string with at least ${e} code points`,representation:{id:`effect/schema/isMinCodePoints`,payload:{minCodePoints:e}},toJsonSchema:()=>({minLength:e}),toCode:()=>({runtime:`Schema.isMinCodePoints(${e})`}),arbitraryConstraint:{minCodePoints:e},...t})}function xh(e,t){return e=wh(e),B(t=>Ch(t,e+1)<=e,{expected:`a string with at most ${e} code points`,representation:{id:`effect/schema/isMaxCodePoints`,payload:{maxCodePoints:e}},toJsonSchema:()=>({maxLength:e}),toCode:()=>({runtime:`Schema.isMaxCodePoints(${e})`}),arbitraryConstraint:{maxCodePoints:e},...t})}function Sh(e,t,n){return e=wh(e),t=wh(t),B(n=>{let r=Ch(n,t+1);return r>=e&&r<=t},{expected:e===t?`a string with ${e} code points`:`a string with between ${e} and ${t} code points`,representation:{id:`effect/schema/isBetweenCodePoints`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>({allOf:[{minLength:e},{maxLength:t}]}),toCode:()=>({runtime:`Schema.isBetweenCodePoints(${e}, ${t})`}),arbitraryConstraint:{minCodePoints:e,maxCodePoints:t},...n})}function Ch(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function wh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Th(e,t){return e=wh(e),B(t=>t.size>=e,{expected:`a value with a size of at least ${e}`,representation:{id:`effect/schema/isMinSize`,payload:{minSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMinSize(${e})`}),[Vo]:!0,arbitraryConstraint:{minSize:e},...t})}function Eh(e,t){return e=wh(e),B(t=>t.size<=e,{expected:`a value with a size of at most ${e}`,representation:{id:`effect/schema/isMaxSize`,payload:{maxSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMaxSize(${e})`}),[Vo]:!0,arbitraryConstraint:{maxSize:e},...t})}function Dh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.size>=e&&n.size<=t,{expected:e===t?`a value with a size of ${e}`:`a value with a size between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenSize`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenSize(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function Oh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e},...t})}function kh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length<=e,{expected:`a value with at most ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMaxProperties`,payload:{maxProperties:e}},toJsonSchema:({type:t})=>t===`object`?{maxProperties:e}:[{maxProperties:e},!0],toCode:()=>({runtime:`Schema.isMaxProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function Ah(e,t,n){return e=wh(e),t=wh(t),B(n=>Reflect.ownKeys(n).length>=e&&Reflect.ownKeys(n).length<=t,{expected:e===t?`a value with exactly ${e===1?`1 entry`:`${e} entries`}`:`a value with between ${e} and ${t} entries`,representation:{id:`effect/schema/isBetweenProperties`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`object`?{minProperties:e,maxProperties:t}:[{minProperties:e,maxProperties:t},!0],toCode:()=>({runtime:`Schema.isBetweenProperties(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var jh=M.check(_h());globalThis.RegExp,globalThis.URL;var Mh=M.annotate({expected:`a string that will be decoded as a Date`}),Nh=Mp(e=>e instanceof globalThis.Date&&!globalThis.Number.isNaN(e.getTime()),{representation:{id:`effect/schema/Date`,payload:null},toCode:()=>({runtime:`Schema.Date`,Type:`globalThis.Date`}),expected:`a valid Date`,toCodecJson:()=>jm()(Mh,gc)}),Ph=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function U(e,t){return Ph.pipe(Sm(e,vc(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var Fh=M.annotate({expected:`a string that will be decoded as a number`}).pipe(Sm(N,mc)),Ih=M.check(Nm()),Lh=M.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(Sm(Ih,dc())),Rh=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),zh=Am(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>jm()(Rh,_c)}),Bh=uc({decode:(e,t)=>Wr(Co(e),{onNone:()=>v(new ms({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>x(wo(e))}),encode:e=>x(To(e))}),Vh=-864e13,Hh=864e13;function Uh(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function Wh(e,t){return H.check($m({minimum:e,maximum:t}))}var Gh=Mp(e=>bo(e)&&xo(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=Uh(e,Vh,Hh);return Cm()(Wh(t,n),Ws(So))},toCodecJson:()=>jm()(M,Bh),toFormatter:()=>e=>e.toString()}),Kh=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(Sm(Gh,Bh));function qh(e){return bp(e.ast)}function Jh(e,t){return pp(e.ast,t)}function Yh(e,t){return up(pp(zf(e.ast),t),t)}var Xh=Rf,Zh=$p(nu(id,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),Qh=fm(M,Zh),$h=e=>crypto.getRandomValues(new Uint8Array(e)),eg=(e,t,n)=>{let r=256-256%e.length;if(r===256){let r=e.length-1;return(i=t)=>{if(!i)return``;let a=``;for(;;){let t=n(i),o=i;for(;o--;)if(a+=e[t[o]&r],a.length>=i)return a}}}let i=Math.ceil(409.6*t/r);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(t[s]<r&&(o+=e[t[s]%e.length],o.length>=a))return o}}},tg=(e,t=21)=>eg(e,t|0,$h),ng=`abcdefghijklmnopqrstuvwxyz0123456789`;function rg(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return tg(ng,e)()}var ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ag=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,og=w().min(1).max(64).regex(ig),sg=w().min(1).max(64).regex(ig),cg=w().min(1).max(32).regex(ag),lg=Zt({prefix:cg}),ug=Zt({family:og,version:vr(1),kinds:si(sg,lg)}).superRefine((e,t)=>{let n=Object.entries(e.kinds);if(n.length<1||n.length>64){t.addIssue({code:`custom`,message:`Identifier families must declare between one and 64 kinds`});return}let r=new Set;for(let[,e]of n){if(r.has(e.prefix)){t.addIssue({code:`custom`,message:`Identifier kind prefixes must be distinct`});return}r.add(e.prefix)}}),dg=w(),fg=/^[a-z0-9]+$/,pg=new TextEncoder;function mg(e){return e===32||e>=9&&e<=13}function hg(e){let t=0,n=e.length;for(;t<n&&mg(e.charCodeAt(t));)t+=1;for(;n>t&&mg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function gg(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&fg.test(n)}let r=_(()=>jr(e=>{let t=dg.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=pg.encode(o).byteLength,c=r.safeParse(o),l=o.startsWith(t)?o.slice(t.length):void 0;if(s<3||s>96)a=`bounds`;else if(l!==void 0&&Array.from(l).length!==21)a=`bounds`;else if(c.success)return{ok:!0,value:c.data};else a=n(hg(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=_(()=>dg.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),Or)}));function o(){let n;try{n=rg(21)}catch{throw e.entropyUnavailable()}return r.parse(`${t}${n}`)}return{family:e.family,kind:e.kind,version:1,generate:o,schema:a,parse:i,is:e=>i(e).ok}}var _g=si(w(),Zt({family:w(),kind:w(),version:vr(1),generate:st(),schema:e(Vt),parse:st(),is:st()})),vg=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},yg=class extends Error{name=`CairnGenerationError`;code=`entropy_unavailable`;family;kind;version=1;constructor(e){super(`Cairn entropy source is unavailable`),this.family=e.family,this.kind=e.kind}};function bg(e){let t;try{t=ug.safeParse(e)}catch{throw new vg}if(!t.success)throw new vg;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=gg({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new yg({family:n.family,kind:t})})}let i=jr(e=>{let t=_g.safeParse(e);if(!t.success)return!1;let r=Object.entries(t.data);return r.length===Object.keys(n.kinds).length&&r.every(([e,t])=>Object.hasOwn(n.kinds,e)&&t.kind===e&&t.family===n.family)}).safeParse(r);if(!i.success)throw new vg;return i.data}var xg=_(()=>cn({id:w().min(1).max(256),name:w().min(1).max(128),kind:vr(`agent`).optional()})),Sg=_(()=>w().min(1).max(256)),Cg=_(()=>cn({agentId:Sg,sessionId:Sg,commandId:Sg,outcome:qt([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:w().min(1).max(200).optional(),waitingOnYou:Tr(cn({itemId:Sg,kind:w().min(1).max(64),summary:w().min(1).max(200)})).min(1).max(8).optional()})),wg=cn({author:xg.optional(),sourceRequestId:Sg.optional(),delegation:cn({ancestors:Tr(Sg).max(8),maxDepth:Mn().int().min(1).max(8),steer:vr(!0).optional(),goal:Qr([w().min(1).max(4e3),vr(!1)]).optional(),reply:Cg.optional()}).optional()});function Tg(e){let t=wg.safeParse(e);return t.success?t.data.author:void 0}var Eg=Symbol.for(`effect/MutableList/Empty`),Dg=()=>({head:void 0,tail:void 0,length:0}),Og=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},kg=()=>({array:[],mutable:!0,offset:0,next:void 0}),Ag=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=kg(),e.tail=e.tail.next):e.head=e.tail=kg(),e.tail.array.push(t),e.length++},jg=e=>{e.head=e.tail=void 0,e.length=0},Mg=(e,t)=>{if(t=_i(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return jg(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?jg(e):Og(e),n;i=i.next}return jg(e),n},Ng=e=>Mg(e,e.length),Pg=e=>{if(!e.head)return Eg;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:jg(e):Og(e),t},Fg=`~effect/Queue`,Ig=`~effect/Queue/Enqueue`,Lg=`~effect/Queue/Dequeue`,Rg={_A:Ve,_E:Ve},zg={[Fg]:Rg,[Ig]:Rg,[Lg]:Rg,...ue,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:n_(this)}}},Bg=e=>xe(t=>{let n=Object.create(zg);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=Dg(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},li(n)}),Vg=e=>Bg({capacity:e}),Hg=e=>Bg({capacity:e,strategy:`dropping`}),Ug=a(2,(e,t)=>ii(()=>Wg(e,t)?i_:e.state._tag===`Open`&&e.strategy===`suspend`?p_(e,t):r_)),Wg=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Pg(e.messages),Ag(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(Ag(e.messages,t),s_(e),!0):(Ag(e.messages,t),c_(e),!0):!1,Gg=a(2,(e,t)=>Kg(e,s(t))),Kg=a(2,(e,t)=>gt(()=>qg(e,t))),qg=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=Ee(t),r=Pe(n,a_);return e.state.offers.size===0&&e.messages.length===0?(y_(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},c_(e),!0)},Jg=e=>qg(e,s(ti())),Yg=e=>gt(()=>Xg(e)),Xg=e=>{if(e.state._tag===`Done`)return!1;jg(e.messages);let t=e.state.offers;y_(e,e.state._tag===`Open`?o_:e.state.exit);for(let e of t)h_(e);return!0},Zg=e=>u_(()=>{if(e.state._tag===`Done`)return Qa(e.state.exit,()=>li([]));let t=v_(e);return __(e),li(t)}),Qg=e=>$g(e,1,1/0),$g=a(3,(e,t,n)=>(t=_i(t),n=_i(n),u_(()=>l_(e,t,n)??Qn(f_(e,()=>d_(e,t)),$g(e,t,n))))),e_=e=>u_(()=>t_(e)??Qn(f_(e,()=>d_(e,1)),e_(e))),t_=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Pg(e.messages);return __(e),Re(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=g_(e.state.offers);return __(e),Re(t)}},n_=e=>e.state._tag===`Done`?0:e.messages.length,r_=Re(!1),i_=Re(!0),a_=me(ti()),o_=f(),s_=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(ye),e.messages.length===0))break}},c_=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,s_(e)},0))},l_=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return Re([]);if(!d_(e,t))return;let r=e.messages.length>0?Mg(e.messages,n):[g_(e.state.offers)];return __(e),Re(r)},u_=At({op:`QueueTake`,[Je](e){let t=this[$e]();return pi(t)?t[Je](e):t}}),d_=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,f_=(e,t)=>Jn(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(ye);let r={ready:t,resume:n};return e.state.takers.add(r),gt(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),p_=(e,t)=>Jn(n=>Wg(e,t)?n(i_):m_(e,{_tag:`Single`,message:t,resume:n})),m_=(e,t)=>{if(e.state._tag!==`Open`)return h_(t);let n=e.state.offers;return n.add(t),gt(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&y_(e,e.state.exit))})},h_=e=>e._tag===`Single`?e.resume(r_):e.resume(Re(e.remaining.slice(e.offset))),g_=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(i_),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(Re([]))),n},__=e=>{if(e.state._tag===`Done`)return $a(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(y_(e,e.state.exit),$a(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)Ag(e.messages,t.message),e.state.offers.delete(t),t.resume(i_);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;Ag(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(Re([]))}let r=e.state;if(r._tag===`Done`)return $a(r.exit.cause)}return!1},v_=e=>{if(e.messages.length>0){let t=Ng(e.messages);return __(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[g_(e.state.offers)];return __(e),t}return[]},y_=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},b_=Cr,x_=Wt,S_=je,C_=Rr,w_=zt,T_=Mr,E_=mr,D_=e=>new k_(e),O_=(e,t,n)=>Jn(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),gt(()=>{e.waiters.delete(i)})}),k_=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=ii(()=>this.free<e?O_(this,e,t):(this.taken+=e,li(e)));return t}takeIfAvailable(e){return ii(()=>this.free<e?li(!1):(this.taken+=e,li(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return xe(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ei))}release(e){return xe(t=>li(this.releaseUnsafe(t,e)))}get releaseAll(){return xe(e=>li(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>ee(n=>{let r=ii(()=>{if(this.free<e){let t=O_(this,e,ei);return wn(n(t),()=>r)}return this.taken+=e,gn(n(t),()=>{this.releaseUnsafe(Rr(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>ee(n=>this.free<e?un:(this.taken+=e,gn(n(c(t)),()=>{this.releaseUnsafe(Rr(),e)},!0)))}},A_=e=>gt(()=>new k_(e)),j_=`~effect/Channel`,M_=e=>yr(e,j_),N_={[j_]:{_Env:Ve,_InErr:Ve,_InElem:Ve,_OutErr:Ve,_OutElem:Ve},pipe(){return Ie(this,arguments)}},P_=e=>{let t=Object.create(N_);return t.transform=(t,n)=>Br(e(t,n),e=>x(Xt(e))),t},F_=(e,t)=>P_((n,r)=>T(R_(e)(n,r),e=>t(e,r))),I_=e=>P_((t,n)=>e),L_=e=>P_(pt(function*(t,n){let r=ka(n),i=e=>Aa(r,ro(e)),a=yield*ge(e(t,n,r),i);return ge(a,i)})),R_=e=>e.transform,z_=4096,B_=(e,t,n)=>Bg({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(In(t=>Da(e,Yg(t))),In(n=>Ta(t(n),e).pipe(Br(e=>Kg(n,e)),Xe(e)))),V_=(e,t)=>P_((n,r)=>Ce(B_(r,e,t),Qg)),H_=e=>P_((t,n)=>sr(()=>R_(e())(t,n))),U_=e=>I_(y(()=>{let t=e();return sr(()=>{let e=t.next();return e.done?ta(e.value):x(e.value)})})),W_=(e,t=z_)=>{let n=vi(t);return I_(y(()=>{let t=e(),r=Sn();return sr(()=>{if(r._tag===`Some`)return ta(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return ta(n.value);r=xr(n.value);break}e.push(n.value)}return x(e)})}))},G_=(e,t=z_)=>W_(()=>e[Symbol.iterator](),t),K_=e=>X_(x(e)),q_=I_(x(ta())),J_=e=>I_(x(v(e))),Y_=e=>I_(Xt(e)),X_=e=>I_(y(()=>{let t=!1;return sr(()=>t?ta():(t=!0,e))})),Z_=e=>I_(x(Qg(e))),Q_=(e,t)=>P_(pt(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*Da(r,Gt(()=>i.return()))),T(fn({try:()=>i.next(),catch:t}),e=>e.done?ta(e.value):x(e.value))})),$_=(e,t)=>ev(Q_(e,t),Nt),ev=a(2,(e,t)=>F_(e,e=>y(()=>{let n=0;return Ce(e,e=>t(e,n++))}))),tv=e=>e===void 0||e!==`unbounded`&&e<=1,nv=a(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?rv(e,t):iv(e,t,n)),rv=(e,t)=>P_((n,r)=>{let i=0;return Ce(R_(e)(n,r),T(e=>t(e,i++)))}),iv=(e,t,n)=>L_(pt(function*(r,i,a){let o=0,s=yield*R_(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Vg(0);yield*Da(a,Yg(l));let u=kr(yield*On()),d=w_(a);if(n.unordered){let e=D_(c),n=Xn(e.release(1)),r=Ot({onFailure:e=>T(Kg(l,e),n),onSuccess:e=>T(Ug(l,e),n)});yield*e.take(1).pipe(T(()=>s),T(e=>{let n=o++;return d(u(r(sr(()=>t(e,n))))),C}),yt({disableYield:!0}),Br(t=>e.withPermits(c-1)(Kg(l,t))),Xe(a))}else{let e=yield*Vg(c-2);yield*Da(a,Yg(e)),yield*e_(e).pipe(ni,T(e=>Ug(l,e)),yt({disableYield:!0}),Br(e=>Kg(l,e)),Xe(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,qg(l,e.cause))};yield*s.pipe(T(i=>{if(n)return Xt(n);let a=o++,s=u(sr(()=>t(i,a)));return d(s),s.addObserver(r),Ug(e,x_(s))}),yt({disableYield:!0}),Br(t=>Ug(e,ia(t)).pipe(g(Kg(e,t)))),Xe(a))}return e_(l)})),av=a(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?ov(e,t):sv(e,t,n)),ov=(e,t)=>P_((n,r)=>Ce(R_(e)(n,r),e=>{let i,a,o=T(e,e=>(a??=ka(r),sn(R_(t(e))(n,a),e=>(i=s(e),i)))),s=Qa(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Aa(a,sa);return a=void 0,T(t,()=>o)});return sr(()=>i??o)})),sv=(e,t,n)=>e.pipe(ev(t),mv(n)),cv=e=>av(e,Ve),lv=e=>F_(e,e=>{let t,n=0,r=sr(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return x(e[0]);default:return t=e,x(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),x(i)});return x(r)}),uv=a(2,(e,t)=>F_(e,e=>x(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return kt(i)?x(i):T(e,n)})))),dv=a(2,(e,t)=>P_((n,r)=>{let i=ka(r);return Ce(R_(e)(n,i),e=>{let a=e.pipe(Br(e=>{if($a(e))return Xt(e);let o=i;return i=ka(r),Aa(o,ia(e)).pipe(g(R_(t(e))(n,i)),T(e=>(a=e,e)))}));return sr(()=>a)})})),fv=a(3,(e,t,n)=>dv(e,e=>{let r=t(e);return ke(r)?Y_(r.failure):n(r.success,e)})),pv=a(2,(e,t)=>fv(e,Yi,e=>t(e))),mv=a(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>L_(pt(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:D_(s),l=yield*E_(!0),u=new Set,d=yield*Vg(t);yield*Da(o,Yg(d));let f=yield*R_(e)(i,a);return yield*b(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*se(f),yield*Dn(c.take(1),g(x_(e),Mt))));let t=e===void 0?yield*f:yield*x_(e),n=ka(o),r=yield*R_(t)(i,n);for(;u.size>=s;){let e=yi(u);u.delete(e),u.size===0&&(yield*l.open),yield*S_(e)}let a=yield*r.pipe(In(()=>de),T(e=>Ug(d,e)),yt({disableYield:!0}),ge(pt(function*(e){let t=ro(e),r=yield*Ln(Aa(n,t));if(!u.has(a))return;let i=fa([t,r]);la(i)&&(yield*Kg(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),se);l.closeUnsafe(),u.add(a)}}).pipe(Br(e=>{let t=to(e);return Ht(t)?l.whenOpen(Kg(d,e)):Kg(d,e)}),Xe(o)),e_(d)}))),hv=a(e=>M_(e[0])&&M_(e[1]),(e,t,n)=>L_(pt(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Vg(0);yield*Da(a,Yg(s));let c=0;function l(e,t){if(c++,!$a(t))return Kg(s,t);switch(o){case`both`:return c===2?Kg(s,t):C;case`left`:case`right`:return e===o?Kg(s,t):C;case`either`:return Kg(s,t)}}let u=(e,t,n)=>R_(t)(r,n).pipe(T(e=>e.pipe(T(e=>Ug(s,e)),yt)),ge(t=>Sr(ro(t),e=>Aa(n,e)).pipe(Ot({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Xe(a));return yield*u(`left`,e,ka(a)),yield*u(`right`,t,ka(a)),e_(s)}))),gv=e=>P_((t,n)=>{let r;return x(sr(()=>r||e.pipe(Ta(n),T(e=>R_(e)(t,n)),T(e=>r=e))))}),_v=a(2,(e,t)=>hv(e,I_(x(T(t,ta))),{haltStrategy:`either`})),vv=a(2,(e,t)=>L_((n,r,i)=>Ea(i,t).pipe(g(R_(e)(n,r))))),yv=a(2,(e,t)=>vv(e,e=>t)),bv=(e,t,n)=>sr(()=>{let r=wa(),i=R_(e)(ta(),r);return Qa(T(i,t),n||x).pipe(Me(e=>Aa(r,e)))}),xv=a(2,(e,t)=>bv(e,e=>yt(T(e,t),{disableYield:!0}))),Sv=pt(function*(e){let t=D_(1),n=yield*On(),r=Te(n,Sa);return(yield*R_(e)(ta(),r)).pipe(ot(n),t.withPermits(1))},Br(e=>x(Xt(e)))),Cv=(e,t)=>R_(e)(ta(),t),wv=`~effect/Stream`,Tv={_R:Ve,_E:Ve,_A:Ve},Ev=function(e){this.channel=e};Ev.prototype={[wv]:Tv,pipe(){return Ie(this,arguments)}};var Dv=e=>new Ev(e),Ov=`~effect/Sink`,kv={_A:Ve,_In:Ve,_L:Ve,_E:Ve,_R:Ve},Av={[Ov]:kv,pipe(){return Ie(this,arguments)}},jv=e=>{let t=Object.create(Av);return t.transform=e,t},Mv=((e,t,n)=>jv(r=>{let i=e(),a;return t(i)?r.pipe(T(e=>{for(let r=0;r<e.length;r++)if(i=n(i,e[r]),!t(i))return r+1<e.length&&(a=e.slice(r+1)),ta();return C}),yt({disableYield:!0}),Qa(()=>x([i,a]))):x([i])}))(Sn,an,(e,t)=>xr(t)),Nv=()=>Mv,Pv=`~effect/Stream`,Fv=e=>yr(e,Pv),Iv=Dv,Lv=e=>Iv(X_(Ce(e,Nt))),Rv=e=>Bv(x(T(e,()=>ta()))),zv=e=>Bv(x(Ce(e,Nt))),Bv=e=>Iv(I_(e)),Vv=(e,t)=>Iv(P_((n,r)=>T(Cv(e.channel,r),e=>t(e,r)))),Hv=e=>e.channel,Uv=(e,t)=>Iv(V_(e,t)),Wv=Iv(q_),Gv=e=>Iv(K_(Nt(e))),Kv=e=>Iv(H_(()=>e().channel)),qv=e=>Iv(J_(e)),Jv=e=>Iv(Y_(e)),Yv=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Xv(e):Iv(G_(e,t?.chunkSize)),Xv=e=>kt(e)?Iv(K_(e)):Wv,Zv=e=>Iv(Z_(e)),Qv=(e,t)=>Iv($_(e,t)),$v=(e,t)=>Bv(y(()=>{let n=e,r=!1;return sr(function e(){return r?ta():T(t(n),([t,i])=>(an(i)?r=!0:n=i.value,kt(t)?x(t):e()))})})),ey=e=>Iv(gv(Ce(e,Hv))),ty=a(2,(e,t)=>Kv(()=>{let n=0;return Iv(ev(e.channel,Tt(e=>t(e,n++))))})),ny=a(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,nv(t,n),ev(Nt),Iv)),ry=e=>e.pipe(ty(t),my(e=>Gv(_e(e)))),iy=a(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,av(e=>t(e).channel,n),Iv)),ay=a(2,(e,t)=>{let n=le(t.duration);if(!ie(n))return e;if(Qe(n))return Kv(t.orElse);let r=Symbol();return py(Kv(()=>{let t=C_().getRef(ja),i=o(n),a,s=T_(!1);return uy(Vv(e,(e,n)=>sr(()=>(a=t.currentTimeMillisUnsafe()+i,s.openUnsafe(),e)).pipe(Ce(e=>(s.closeUnsafe(),a=void 0,e)),x)),Rv(b(function*(){for(;;)if(yield*s.await,a!==void 0&&(yield*jn(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*_r(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Jv(e))}),oy=e=>iy(e,Yv),sy=a(2,(e,t)=>{let n=Iv(cv(U_(()=>ly(e,t))));return cy.set(n,[e,t]),n}),cy=new WeakMap;function*ly(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=cy.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var uy=a(e=>Fv(e[0])&&Fv(e[1]),(e,t,n)=>Iv(hv(Hv(e),Hv(t),n))),dy=a(2,(e,t)=>Iv(uv(Hv(e),t))),fy=a(2,pt(function*(e,t){let n,r=yield*Sv(e.channel),i=Br(r,e=>(n=e,Xt(e))),[a,o]=yield*Gr(e=>t.transform(i,e)),s=n?Wv:Bv(x(r));return o&&(s=sy(Xv(o),s)),[a,s]})),py=a(2,(e,t)=>e.channel.pipe(dv(e=>t(e).channel),Iv)),my=a(2,(e,t)=>Iv(pv(e.channel,e=>t(e).channel))),hy=a(e=>Fv(e[0]),(e,t,n)=>Vv(e,(e,r)=>y(()=>{let r=0,i=!1;return T(sr(()=>i?ta():e),e=>{let a=e.findIndex(e=>t(e,r++));if(a>=0){i=!0;let t=e.slice(0,n?.excludeLast?a:a+1);return kt(t)?x(t):ta()}return x(e)})}))),gy=a(2,(e,t)=>Iv(_v(e.channel,t))),_y=a(2,(e,t)=>Iv(yv(e.channel,t))),vy=a(2,(e,t)=>xv(e.channel,e=>{let n=0;return Ct({while:()=>n<e.length,body:()=>t(e[n++]),step:Ze})})),yy=a(2,(e,t)=>({[Symbol.asyncIterator](){let n=on(t),r=kr(t),i=wa(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Ar(g(t?S_(t):C,Aa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(tt(`Suppressed error while closing Stream async iterator`,e))}};return{async next(){if(c)return c;if(o){let e=o.next();if(!e.done)return e;o=void 0}let t=r(a??T(Cv(e.channel,i),e=>(a=e,e)));s=t;let d=await n(b_(t));if(s===t&&(s=void 0),ca(d))return o=d.value[Symbol.iterator](),o.next();if($a(d.cause))return l(sa);if(c&&Ki(d.cause))return c;throw await u(d),Ji(d.cause)},return(){return l(sa)},async throw(e){throw await u(oa(e)),e}}}})),by=e=>yy(e,pe()),xy=15e3,Sy=45e3,Cy=jh.check(vh(256)),wy=H.check(V(0)),Ty=P({agentId:Cy,sessionId:Cy,name:Cy}),Ey=P({by:Ty,reason:L([`escalated`,`sender_archived`,`sender_absent`]),note:k(M.check(vh(1e3)))}),Dy=P({id:Cy,kind:jh.check(vh(64)),summary:jh.check(vh(200)),since:wy,expiresAt:A(wy),inbox:A(j(!1)),waitingOn:A(Ty),escalated:A(Ey)}),Oy=Dy.mapFields(e=>({...e,extensionId:Cy})),ky=4096,Ay=F(Oy).check(vh(64)),jy=M.pipe(z(hh(1)),z(vh(256))),My=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Ny=P({providerId:jy,modelId:jy,reasoning:A(L(My))}),Py=O(R(Ny)),Fy=O(U(R(Ny))),Iy=L([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),Ly=L([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),Ry=M.pipe(z(hh(1)),z(vh(256))),zy=P({_tag:j(`ShiitakeError`),boundary:Iy,cause:Ly,message:M,requestId:k(Ry)}),W=class extends Error{boundary;requestId;_tag=`ShiitakeError`;cause;underlying;constructor(e,t,n,r,i){super(n),this.boundary=e,this.requestId=r,this.name=`ShiitakeError`,this.cause=t,this.underlying=i}},By=new TextEncoder;function Vy(e){return M.check(hh(1),vh(e),B(t=>By.encode(t).byteLength<=e))}var Hy=/\p{Cs}/u,Uy=Vy(256).check(B(e=>!Hy.test(e))),Wy=Vy(262144),Gy=P({type:j(`image`),data:M.check(hh(1),vh(1048576),Lm()),mimeType:M.check(B(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),Ky=F(Gy).check(hh(1),vh(8)),qy=L([`steer`,`followUp`]),Jy=Uy,Yy=D(P({commandId:Uy,timeoutMs:H.check(V(0),Qm(3e4))}),{onExcessProperty:`error`});D(P({commandId:Uy,timeoutMs:Fh.check(th(),$m({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Xy=D(Vy(512)),Zy=P({requestId:Uy}),Qy=P({delivery:qy,requestId:Uy,type:j(`prompt`),text:M.check(vh(262144),B(e=>By.encode(e).byteLength<=262144)),images:k(Ky)}).check(B(e=>(e.text.length>0||(e.images?.length??0)>0)&&By.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),$y=P({type:j(`abort`)}),eb=P({commandId:Uy,onlyIfPending:A(cm),type:j(`cancel`)}),tb=P({type:j(`operator`),requestId:Uy,author:L([`operator`,`party`]),text:Wy}),nb=P({type:j(`branch`),entryId:Uy}),rb=P({type:j(`fork`),entryId:Uy}),ib=M.check(hh(1),vh(4096)),ab=P({type:j(`compact`),requestId:Uy,instructions:k(ib)}),ob=I([Qy,ab]),sb=M.check(B(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),cb=I([Qy,$y,eb,nb,rb,tb,ab,P({type:j(`title`),title:R(sb)})]),lb=P({command:cb}),ub=P({includeSandboxFailures:A(cm),limit:A(H.check($m({minimum:1,maximum:200}))),before:A(Vy(512))}),db=P({includeSandboxFailures:A(j(`true`)),limit:A(Fh.check(th(),$m({minimum:1,maximum:200}))),before:A(Vy(512))}),fb=P({includeSandboxFailures:A(cm),after:A(M)}),pb=P({includeSandboxFailures:A(j(`true`)),mode:A(j(`subscribe`)),after:A(M),limit:A(Fh.check(th(),$m({minimum:1,maximum:200})))}),mb={onExcessProperty:`error`},hb=D(Jy,mb),gb=D(Zy,mb),_b=D(ob,mb);D(Uy);var vb=D(cb,mb);D(lb,mb);var yb=D(I([ub,sm]),mb);D(db,mb);var bb=D(fb,mb);D(pb,mb);function xb(e){let t=hb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session id is invalid`);return t.success}function Sb(e){let t=Xy(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function Cb(e){let t=gb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function wb(e){let t=yb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Read options are invalid`);let n=t.success??{},r={limit:n.limit??200};return n.before!==void 0&&(r={...r,before:n.before}),n.includeSandboxFailures!==void 0&&(r={...r,includeSandboxFailures:n.includeSandboxFailures}),Object.freeze(r)}function Tb(e){let t=bb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Subscribe options are invalid`);let n={};return t.success.after!==void 0&&(n={...n,after:t.success.after}),t.success.includeSandboxFailures!==void 0&&(n={...n,includeSandboxFailures:t.success.includeSandboxFailures}),Object.freeze(n)}function Eb(e,t){if(ke(e))throw new W(`contract`,`invalid`,t);return e.success}var Db=yn();function Ob(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function kb(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e.charCodeAt(r)-t.charCodeAt(r);if(n!==0)return n}return e.length-t.length}function Ab(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[_./:-]/g,` `).toLowerCase().trim()}function jb(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var Mb=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function Nb(e){return Mb.has(e)}function Pb(e){let t=[],n=n=>{n!==e&&n.length>=3&&!t.includes(n)&&t.push(n)};return e.endsWith(`ing`)&&e.length>4&&n(e.slice(0,-3)),e.endsWith(`ed`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`ation`)&&e.length>6&&n(`${e.slice(0,-3)}e`),e.endsWith(`ies`)&&e.length>4&&(n(e.slice(0,-3)),n(`${e.slice(0,-3)}y`)),e.endsWith(`es`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`s`)&&!e.endsWith(`ss`)&&e.length>3&&n(e.slice(0,-1)),t}function Fb(e){let t=8997,n=33826,r=40164,i=52210;for(let a=0;a<e.length;a+=1){let o=t^e.charCodeAt(a),s=o*435,c=n*435+(s>>>16),l=r*435+(c>>>16)+(o<<8),u=i*435+(l>>>16)+(n<<8);t=s&65535,n=c&65535,r=l&65535,i=u&65535}return i.toString(16).padStart(4,`0`)+r.toString(16).padStart(4,`0`)+n.toString(16).padStart(4,`0`)+t.toString(16).padStart(4,`0`)}function Ib(e){return e.slice(e.indexOf(`.`)+1)}function Lb(e){return e.slice(0,e.indexOf(`.`))}var Rb=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,zb=1e3,Bb=221;function Vb(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Vb(r,t+1));return n}if(!Ob(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Vb(r,t+1));return n}var Hb=_(()=>si(w(),yn()).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:`custom`,message:`Sample exceeds the entry bound`}),JSON.stringify(e).length>4e3&&t.addIssue({code:`custom`,message:`Sample exceeds the byte bound`}),Vb(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Ub=_(()=>Zt({query:w().max(200),maxResults:Mn().int().min(1).max(50).default(50)})),Wb=_(()=>Zt({path:w().max(160),detail:qt([`index`,`full`]).default(`full`),methods:Tr(w().max(80)).max(50).optional()})),Gb=Zt({cursor:w().max(400).optional(),limit:Mn().int().min(1).max(50).default(50),namespace:w().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),Kb=_(()=>Zt({path:w().max(160),capabilityNotes:w().max(500).optional()})),qb=Zt({path:w().max(160),description:w().max(1e3).optional(),score:Mn().min(0).max(Bb),matchReason:w().max(500).optional(),sample:Hb.optional(),capabilityNotes:w().max(500).optional(),peers:Tr(Kb).max(1e3).optional()}),Jb=_(()=>Zt({results:Tr(qb).max(50),total:Mn().int().min(0).max(zb),truncated:fr(),topScore:Mn().min(0).max(Bb),margin:Mn().min(0).max(Bb),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)})),Yb=Zt({results:Tr(qb).max(50),total:Mn().int().min(0).max(zb),nextCursor:w().max(400).nullable(),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)}),Xb=_(()=>Zt({path:w().max(160),description:w().max(1e3).optional(),types:w().max(2e4),inputSchema:yn().refine(e=>JSON.stringify(e).length<=2e4&&Vb(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:qt([`module`,`operation`]),usage:w().max(300).optional()}));_(()=>Zt({code:qt([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:w().max(1e3)}));var Zb=_(()=>Zt({"~standard":Zt({jsonSchema:Zt({input:e(Function),output:e(Function)})})})),Qb=_(()=>jr(e=>Zb.safeParse(e).success,`Expected a Standard JSON Schema`)),$b=_(()=>Zt({path:w().min(3).max(160).regex(Rb),description:w().max(1e3).optional(),input:Qb,output:Qb.optional(),capabilityNotes:w().max(500).optional(),instructions:w().max(1e3).optional()})),ex=_(()=>Zt({revision:w().min(1).max(160),operations:Tr($b).max(zb)})),tx=class extends Error{code;failure;constructor(e,t,n){let r=t.slice(0,1e3);super(r,n),this.name=`ForageError`,this.code=e,this.failure={code:e,message:r}}},nx=Qr([ir({$ref:w().optional(),$defs:si(w(),bt()).optional(),definitions:si(w(),bt()).optional(),const:bt().optional(),enum:Tr(bt()).optional(),oneOf:Tr(bt()).optional(),anyOf:Tr(bt()).optional(),allOf:Tr(bt()).optional(),type:Qr([w(),Tr(w())]).optional(),properties:si(w(),bt()).optional(),additionalProperties:bt().optional(),required:Tr(w()).optional(),prefixItems:Tr(bt()).optional(),items:bt().optional(),examples:Tr(bt()).optional(),default:bt().optional()}),fr()]),rx=new WeakMap;function ix(e,t){let n=rx.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`})}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}sx(i);let a={raw:i};return n===void 0&&(n={},rx.set(e,n)),n[t]=a,a}function ax(e,t){return ix(e,t).raw}function ox(e,t){let n=ix(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function sx(e){let t=nx.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var cx=256,lx=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function ux(e,t,n){let r=lx.exec(e)?.[1];if(r===void 0||n.expanding.has(r))return`unknown`;let i=n.definitions[r];if(i===void 0)return`unknown`;if(n.budget.expansions+=1,n.budget.expansions>cx)throw new tx(`invalid_input`,`Schema references expand more than ${String(cx)} times; flatten its shared definitions`);return fx(sx(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function dx(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=lx.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&dx(sx(r),{definitions:t.definitions,expanding:new Set([...t.expanding,n]),budget:t.budget})}return e.const===void 0?e.enum!==void 0&&e.enum.length>1||e.oneOf!==void 0&&e.oneOf.length>1||e.anyOf!==void 0&&e.anyOf.length>1:!1}function fx(e,t,n){if(t>12||e===!0||e===!1)return`unknown`;let r=n??{definitions:{...e.definitions,...e.$defs},expanding:new Set,budget:{expansions:0}};if(e.$ref)return ux(e.$ref,t,r);if(e.const!==void 0)return JSON.stringify(e.const);if(e.enum)return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(e.oneOf)return e.oneOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=sx(e),i=fx(n,t+1,r);return dx(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>kb(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${fx(sx(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/compat-bF01jZNd.js","assets/preload-helper-DY31Aviq.js","assets/openai-codex.models-B_MCwO6E.js","assets/provider-env-CcCbsTJq.js","assets/rolldown-runtime-hePW80VL.js","assets/diagnostics-CxvqSC4Q.js","assets/models-BM_0GHMS.js","assets/json-parse-M7s0500m.js","assets/openai-codex-responses-BgrNR8T1.js","assets/headers-FK4rgixo.js","assets/transform-messages-C3pBaiQJ.js","assets/runtime-core-B_1gibxC.js","assets/Effect-DeiDqvoz.js","assets/index-Vpqb1PUB.js","assets/sigil-CEqXOKdC.js","assets/animation-Ca8A_H2p.js","assets/document-CEriO-BY.js","assets/base-face-Biu4f93I.js","assets/index-BMSpLCqV.css","assets/error-body-pkrba6pf.js","assets/openai-prompt-cache-DXo9f3w5.js","assets/openai-responses-shared-SmcOX-CT.js","assets/sanitize-unicode-DmIE6hZJ.js","assets/hash-yQufAZII.js","assets/abort-signals-joV34wzR.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{$a as e,$i as t,$n as n,$r as r,$t as i,A as a,Ai as o,An as s,Ar as c,At as l,B as u,Bn as d,Br as f,Bt as p,C as m,Ci as ee,Cn as te,Ct as ne,D as re,Di as ie,Dn as ae,Dr as oe,Dt as se,E as ce,Ei as le,En as ue,Er as de,Et as fe,Fi as pe,Fn as me,Fr as he,Ft as ge,G as _e,Gn as ve,Gr as ye,Gt as be,H as xe,Hr as Se,Ht as Ce,I as we,Ii as Te,In as Ee,Ir as De,It as Oe,J as ke,Jn as Ae,Jr as je,Jt as Me,K as Ne,Kr as Pe,Kt as Fe,L as Ie,Li as Le,Ln as Re,Lr as ze,Lt as Be,M as Ve,Mi as He,Mn as Ue,Mr as We,Mt as Ge,N as Ke,Ni as qe,Nn as Je,Nr as Ye,Nt as Xe,O as Ze,Oi as Qe,On as $e,Or as et,Ot as tt,P as nt,Pi as rt,Pn as it,Pr as at,Pt as ot,Q as st,Qi as ct,Qr as h,Qt as lt,R as ut,Rn as dt,Rr as ft,Rt as pt,S as mt,Sa as ht,Si as gt,Sn as _t,Sr as vt,St as yt,T as bt,Ta as xt,Ti as St,Tn as Ct,Tt as wt,U as Tt,Un as Et,Ur as Dt,Ut as Ot,V as kt,Vn as At,Vr as jt,Vt as Mt,W as Nt,Wn as Pt,Wr as Ft,Wt as It,X as Lt,Xa as Rt,Xn as zt,Xr as Bt,Xt as Vt,Y as Ht,Yi as Ut,Yn as Wt,Yr as Gt,Yt as Kt,Z as qt,Zi as Jt,Zn as Yt,Zt as Xt,_ as Zt,_a as Qt,_i as $t,_n as en,_r as tn,a as g,aa as nn,ai as rn,an,ar as on,at as sn,b as cn,ba as ln,bi as un,bn as dn,br as fn,bt as pn,c as mn,ca as hn,ci as gn,cn as _n,cr as vn,d as yn,da as bn,di as xn,dn as Sn,dr as Cn,ea as wn,en as Tn,er as En,et as Dn,f as On,fa as _,fi as kn,fn as An,ft as jn,g as v,ga as Mn,gi as Nn,gn as Pn,gr as Fn,gt as In,h as Ln,ha as Rn,hi as zn,hn as Bn,hr as Vn,ht as y,i as Hn,ii as Un,in as Wn,ir as Gn,it as Kn,j as b,jr as qn,jt as Jn,k as Yn,ki as Xn,kr as Zn,kt as Qn,l as $n,li as er,ln as tr,lt as nr,m as rr,ma as ir,mi as ar,mn as or,mt as sr,ni as cr,nn as lr,no as ur,nt as dr,o as fr,oa as pr,oi as mr,on as hr,or as gr,ot as _r,p as vr,pa as yr,pi as br,pn as xr,pr as Sr,pt as x,q as Cr,qr as S,qt as wr,r as Tr,ra as Er,ri as Dr,rn as Or,rt as kr,s as Ar,sa as jr,sn as Mr,sr as Nr,st as Pr,t as Fr,ta as Ir,ti as Lr,tn as Rr,tt as zr,u as Br,ua as Vr,ui as Hr,un as Ur,ur as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wa as Qr,wi as $r,wn as ei,wr as ti,wt as C,x as ni,xa as w,xi as ri,xn as ii,xr as ai,xt as oi,y as T,ya as si,yi as ci,yn as li,yr as ui,yt as di,z as fi,zr as pi,zt as mi}from"./Effect-DeiDqvoz.js";import{l as hi,t as gi}from"./preload-helper-DY31Aviq.js";var _i=e=>e>0?Math.floor(e):0,vi=e=>Math.max(1,_i(e)),yi=e=>{let t=e[Symbol.iterator]().next();if(t.done)throw Error(`headUnsafe: empty iterable`);return t.value},bi=`~effect/BigDecimal`,xi={[bi]:bi,[kn](){let e=ki(this);return gn(xn(String(e.value)),Hr(e.scale))},[mr](e){return Si(e)&&Pi(this,e)===0},toString(){return`BigDecimal(${Ii(this)})`},toJSON(){return{_id:`BigDecimal`,value:String(this.value),scale:this.scale}},[Pe](){return this.toJSON()},pipe(){return Le(this,arguments)}},Si=e=>br(e,bi),Ci=(e,t)=>{if(!Number.isSafeInteger(t))throw RangeError(`Scale must be a safe integer, got ${t}`);let n=Object.create(xi);return n.value=e,n.scale=t,n},wi=(e,t)=>{let n=Ci(e,t);return n.normalized=n,n},Ti=BigInt(0),Ei=BigInt(1),Di=BigInt(10),Oi=wi(Ti,0),ki=e=>{if(e.normalized===void 0){if(e.value===Ti)e.normalized=Oi;else{let t=`${e.value}`,n=t.length;for(;t[n-1]===`0`;)n--;e.normalized=wi(BigInt(t.slice(0,n)),e.scale-(t.length-n))}}return e.normalized},Ai=100,ji=[Ei],Mi=(e,t)=>e===t?0:e<t?-1:1,Ni=(e,t)=>{let n=`${e.value<Ti?-e.value:e.value}`,r=`${t.value<Ti?-t.value:t.value}`,i=BigInt(n.length-r.length)-BigInt(e.scale)+BigInt(t.scale);if(i!==Ti)return i<Ti?-1:1;let a=Math.max(n.length,r.length);return Yr(n.padEnd(a,`0`),r.padEnd(a,`0`))},Pi=(e,t)=>{if(e.scale===t.scale)return Mi(e.value,t.value);let n=Fi(e),r=Fi(t);if(n!==r)return n<r?-1:1;if(n===0)return 0;let i=e.scale-t.scale,a=Math.abs(i);if(a>Ai)return n===-1?Ni(t,e):Ni(e,t);let o=ji[a]??=Di**BigInt(a);return i>0?Mi(e.value,t.value*o):Mi(e.value*o,t.value)},Fi=e=>e.value===Ti?0:e.value<Ti?-1:1,Ii=e=>{let t=ki(e);if(Math.abs(t.scale)>=16)return Li(t);let n=t.value<Ti,r=`${n?-t.value:t.value}`,i=t.scale>0?r.padStart(t.scale+1,`0`):r.padEnd(r.length-t.scale,`0`),a=i.length-t.scale,o=t.scale>0?`${i.slice(0,a)}.${i.slice(a)}`:i;return n?`-${o}`:o},Li=e=>{if(Ri(e))return`0e+0`;let t=ki(e),n=`${t.value}`,r=t.value<Ti?2:1,i=n.slice(0,r),a=n.slice(r),o=a.length-t.scale;return`${i}${a===``?``:`.${a}`}e${o>=0?`+`:``}${o}`},Ri=e=>e.value===Ti,zi=oe,Bi=`~effect/encoding/EncodingError`,Vi=class extends zi(`EncodingError`){[Bi]=Bi},Hi=f,Ui=qn,Wi=c,Gi=Zn,Ki=Or,qi=Xe,Ji=ge,Yi=lt,Xi=i,Zi=Xt,Qi=lr,$i=ot,ea=ft,ta=We,na=tt;Je()(`effect/Cause/StackTrace`),Je()(`effect/Cause/InterruptorStackTrace`);var ra=ze,ia=De,aa=he,oa=at,sa=be,ca=Ce,la=Mt,ua=It,da=Ot,fa=mi,pa={"~effect/Deferred":{_A:He,_E:He},pipe(){return Le(this,arguments)}},ma=function(){this.resumes=void 0,this.effect=void 0};ma.prototype=pa;var ha=()=>new ma,ga=()=>_t(()=>ha()),_a=e=>Jn(t=>e.effect?t(e.effect):(e.resumes??=[],e.resumes.push(t),_t(()=>{let n=e.resumes;if(n===void 0)return;let r=n.indexOf(t);r>=0&&n.splice(r,1)}))),va=o(2,(e,t)=>_t(()=>xa(e,t))),ya=o(2,(e,t)=>va(e,he(t))),ba=o(2,(e,t)=>va(e,ze(t))),xa=(e,t)=>{if(e.effect)return!1;if(e.effect=t,e.resumes){let n=e.resumes;e.resumes=void 0;for(let e=0;e<n.length;e++)n[e](t)}return!0},Sa=Jr,Ca=Pn,wa=en,Ta=tr,Ea=An,Da=Sn,Oa=or,ka=Bn,Aa=xr,ja=se,Ma=Be,Na=`~effect/DateTime`,Pa=`~effect/DateTime/TimeZone`,Fa={[Na]:Na,pipe(){return Le(this,arguments)},[Pe](){return this.toString()},toJSON(){return Ka(this).toJSON()}},Ia={...Fa,_tag:`Utc`,[kn](){return Hr(this.epochMilliseconds)},[mr](e){return Ra(e)&&e._tag===`Utc`&&this.epochMilliseconds===e.epochMilliseconds},toString(){return`DateTime.Utc(${Ka(this).toJSON()})`}};({...Fa});var La={[Pa]:Pa,[Pe](){return this.toString()}};({...La}),{...La};var Ra=e=>br(e,Na),za=e=>e._tag===`Utc`,Ba=e=>{let t=Object.create(Ia);return t.epochMilliseconds=e,Object.defineProperty(t,"partsUtc",{value:void 0,enumerable:!1,writable:!0}),t},Va=e=>{let t=e.getTime();if(Number.isNaN(t))throw new na(`Invalid date`);return Ba(t)},Ha=e=>{if(Ra(e))return e;if(e instanceof Date)return Va(e);if(typeof e==`object`){if(`epochMilliseconds`in e)return Va(new Date(e.epochMilliseconds));let t=new Date(0);return qa(t,e),Va(t)}return typeof e==`string`&&!Ua(e)?Va(new Date(e+`Z`)):Va(new Date(e))},Ua=e=>/Z|GMT|[+-]\d{2}$|[+-]\d{2}:?\d{2}$|\]$/.test(e),Wa=vn(Ha),Ga=e=>Ba(e.epochMilliseconds),Ka=e=>new Date(e.epochMilliseconds),qa=(e,t)=>{if((t.year!==void 0||t.month!==void 0||t.day!==void 0)&&e.setUTCFullYear(t.year??e.getUTCFullYear(),t.month===void 0?e.getUTCMonth():t.month-1,t.day??e.getUTCDate()),t.weekDay!==void 0){let n=t.weekDay-e.getUTCDay();e.setUTCDate(e.getUTCDate()+n)}t.hour!==void 0&&e.setUTCHours(t.hour),t.minute!==void 0&&e.setUTCMinutes(t.minute),t.second!==void 0&&e.setUTCSeconds(t.second),t.millisecond!==void 0&&e.setUTCMilliseconds(t.millisecond)},Ja=e=>Ka(e).toISOString();globalThis.Number;var Ya=o(2,(e,t)=>{if(!globalThis.Number.isFinite(e)||!globalThis.Number.isFinite(t)||t===0)return NaN;if(globalThis.Number.isInteger(e)&&globalThis.Number.isInteger(t))return e%t;let[n,r]=Xa(e),[i,a]=Xa(t),o=Math.min(r,a),s=n*BigInt(10)**BigInt(r-o)%(i*BigInt(10)**BigInt(a-o));if(s===BigInt(0))return e<0||Object.is(e,-0)?-0:0;let c=globalThis.Number(`${s}e${o}`);return c===0?Math.sign(e)*globalThis.Number.MIN_VALUE:c});function Xa(e){if(globalThis.Number.isInteger(e))return[BigInt(e),0];let t=Math.abs(e).toExponential(),n=t.indexOf(`e`),r=t.slice(0,n).replace(`.`,``);return[BigInt(r)*(e<0?-BigInt(1):BigInt(1)),globalThis.Number(t.slice(n+1))-r.length+1]}globalThis.String;var Za=e=>e.trim(),Qa=o(2,(e,t)=>Ge(e,no,e=>t(e))),$a=e=>e.reasons.some(eo),eo=e=>e._tag===`Fail`&&ea(e.error),to=e=>{let t,r=!1;for(let n of e.reasons)eo(n)?t??=n.error:n._tag!==`Interrupt`&&(r=!0);return t===void 0?ve(e):r?ve(Ui(e.reasons.filter(e=>!eo(e)))):n(t)},no=e=>{let t=to(e);return Ae(t)?t:n(t.success.value)},ro=e=>{let t=to(e);return Ae(t)?ia(t.failure):ra(t.success.value)},io=Ue(`effect/Metric/CurrentMetricAttributes`,{defaultValue:()=>({})}),ao=Ue(`effect/Metric/MetricRegistry`,{defaultValue:()=>new Map}),oo=`~effect/Metric`,so=class{[oo]=oo;#e;#t=``;id;description;attributes;constructor(e,t,n){this.id=e,this.description=t,this.attributes=n}valueUnsafe(e){return this.hook(e).get(e)}modifyUnsafe(e,t){return this.hook(t).modify(e,t)}updateUnsafe(e,t){return this.hook(t).update(e,t)}hook(e){let t=Ee(e,io);t!==this.#e&&(this.#e=t,this.#t=ho(this,_o(this.attributes,t)));let n=Ee(e,ao),r=n.get(this.#t);return le(r)&&(r={id:this.id,type:this.type,description:this.description,attributes:Object.keys(t).length>0?_o(this.attributes,t):this.attributes,hooks:this.createHooks()},n.set(this.#t,r)),r.hooks}pipe(){return Le(this,arguments)}},co=BigInt(0),lo=class extends so{type=`Counter`;#e;#t;constructor(e,t){super(e,t?.description,vo(t?.attributes)),this.#e=t?.bigint??!1,this.#t=t?.incremental??!1}createHooks(){let e=this.#e?co:0,t=this.#t?this.#e?e=>e>=co:e=>e>=0:e=>!0;return go(()=>({count:e,incremental:this.#t}),n=>{t(n)&&(e+=n)})}},uo=class extends so{type;metric;valueUnsafe;updateUnsafe;modifyUnsafe;constructor(e,t,n,r){super(e.id,e.description,e.attributes),this.metric=e,this.valueUnsafe=t,this.updateUnsafe=n,this.modifyUnsafe=r,this.type=e.type}createHooks(){return this.metric.createHooks()}},fo=(e,t)=>new lo(e,t),po=o(2,(e,t)=>Oe(n=>_t(()=>e.updateUnsafe(t,n)))),mo=o(2,(e,t)=>{let n=yo(t);return new uo(e,t=>e.valueUnsafe(n(t)),(t,r)=>e.updateUnsafe(t,n(r)),(t,r)=>e.modifyUnsafe(t,n(r)))});function ho(e,t){let n=Object.entries(t).sort((e,t)=>e[0]<t[0]?-1:+(e[0]>t[0]));return JSON.stringify([e.type,e.id,e.description,n])}function go(e,t,n){return{get:e,update:t,modify:n??t}}function _o(e,t){return{...vo(e),...vo(t)}}function vo(e){return ci(e)&&Array.isArray(e)?e.reduce((e,[t,n])=>(h(e,t,n),e),{}):e}function yo(e){let t,n={};return r=>{let i=Ee(r,io);return i!==t&&(t=i,n=_o(i,e)),it(r,io,n)}}var bo=Ra,xo=za,So=Ha,Co=Wa,wo=Ga;Je()(`effect/DateTime/CurrentTimeZone`);var To=Ja,Eo=e=>Oo(typeof e==`string`?ko.encode(e):e),Do=e=>{let t=Ao(e),r=t.length;if(r%4!=0)return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:`Length must be a multiple of 4, but is ${r}`}));let i=t.indexOf(`=`);if(i!==-1&&(i<r-2||i===r-2&&t[r-1]!==`=`))return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:`Found a '=' character, but it is not at the end`}));try{let e=t.endsWith(`==`)?2:+!!t.endsWith(`=`),i=new Uint8Array(r/4*3-e);for(let e=0,n=0;e<r;e+=4,n+=3){let r=No(t.charCodeAt(e))<<18|No(t.charCodeAt(e+1))<<12|No(t.charCodeAt(e+2))<<6|No(t.charCodeAt(e+3));i[n]=r>>16,i[n+1]=r>>8&255,i[n+2]=r&255}return n(i)}catch(e){return ve(new Vi({kind:`Decode`,module:`Base64`,input:t,message:e instanceof Error?e.message:`Invalid input`}))}},Oo=e=>{let t=e.length,n=``,r;for(r=2;r<t;r+=3)n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2|e[r]>>6],n+=jo[e[r]&63];return r===t+1&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4],n+=`==`),r===t&&(n+=jo[e[r-2]>>2],n+=jo[(e[r-2]&3)<<4|e[r-1]>>4],n+=jo[(e[r-1]&15)<<2],n+=`=`),n},ko=new TextEncoder,Ao=e=>e.replace(/[\n\r]/g,``),jo=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`,Mo=new Uint8Array(123).fill(255);for(let e=0;e<64;e++)Mo[jo.charCodeAt(e)]=e;Mo[61]=0;var No=e=>{if(e>=Mo.length||Mo[e]===255)throw TypeError(`Invalid character ${String.fromCharCode(e)}`);return Mo[e]};zi(`CookiesError`),{...ye},{...ye};var Po=new WeakMap,Fo=`~effect/Redacted`,Io=e=>br(e,Fo),Lo=(e,t)=>{let n=Object.create(Ro);return t?.label&&(n.label=t.label),Po.set(n,e),n},Ro={[Fo]:{_A:e=>e},label:void 0,...de,toJSON(){return this.toString()},toString(){return`<redacted${$r(this.label)?`:`+this.label:``}>`},[kn](){return er(Po.get(this))},[mr](e){return Io(e)&&Dr(Po.get(this),Po.get(e))}};({...de});function zo(e){return e.checks?e.checks[e.checks.length-1].annotations:e.annotations}function Bo(e){return t=>zo(t)?.[e]}var Vo=`~structural`,Ho=`~identifier`,Uo=`~sentinels`,Wo=`~constructor`,Go=[`title`,`description`,`default`,`examples`,`readOnly`,`writeOnly`,`format`,`contentEncoding`,`contentMediaType`,`contentSchema`],Ko=Bo(`identifier`),qo=Bo(Ho),Jo=Bo(`title`),Yo=Bo(`description`),Xo=qe(e=>{let t=zo(e)?.identifier;return typeof t==`string`?t:e.getExpected(Xo)}),Zo=new Set([Uo,Vo,`representation`,`arbitraryConstraint`,`toJsonSchema`,`toCode`,`toEquivalence`,`toFormatter`,`toCodec`,`toCodecJson`,`toCodecStringTree`,`toCodecIso`,`toCodecArbitrary`]),E=Symbol(),Qo=ra,$o=Qo(E),es=Qo(E),ts=e=>e===E?Cn():Sr(e),ns=e=>e._tag===`None`?$o:Qo(e.value),rs=`~effect/SchemaIssue/Issue`;function is(e){return br(e,rs)&&e[rs]===rs}function as(e){return Object.hasOwn(e,`input`)}var os=class{[rs]=rs;constructor(e,t){t?.reportInput===!0&&e!==E&&(this.input=e)}},ss=class extends os{_tag=`Filter`;filter;issue;constructor(e,t,n,r){super(n,r),this.filter=e,this.issue=t}},cs=class extends os{_tag=`Encoding`;ast;issue;constructor(e,t,n,r){super(n,r),this.ast=e,this.issue=t}},ls=class extends os{_tag=`Pointer`;path;issue;constructor(e,t){super(),this.path=e,this.issue=t}},us=class extends os{_tag=`MissingKey`;annotations;constructor(e){super(),this.annotations=e}},ds=class extends os{_tag=`UnexpectedKey`;ast;constructor(e,t,n){super(t,n),this.ast=e}},fs=class extends os{_tag=`Composite`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},ps=class extends os{_tag=`InvalidType`;ast;constructor(e,t,n){super(t,n),this.ast=e}},ms=class extends os{_tag=`InvalidValue`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},hs=class extends os{_tag=`Forbidden`;annotations;constructor(e,t,n){super(t,n),this.annotations=e}},gs=class extends os{_tag=`AnyOf`;ast;issues;constructor(e,t,n,r){super(n,r),this.ast=e,this.issues=t}},_s=class extends os{_tag=`OneOf`;ast;successes;constructor(e,t,n,r){super(n,r),this.ast=e,this.successes=t}};function vs(e,t,n){if(is(e))return e;if(typeof e==`string`)return new ms({message:e},t,n);let r=typeof e.issue==`string`?new ms({message:e.issue},t,n):e.issue;return new ls(e.path,r)}function ys(e,t,n){if(e!==void 0)return typeof e==`boolean`?e?void 0:new ms(void 0,t,n):vs(e,t,n)}function bs(e,t,n,r){return Array.isArray(t)?At(t)?t.length===1?vs(t[0],n,r):new fs(e,Et(t,e=>vs(e,n,r)),n,r):void 0:ys(t,n,r)}var xs=e=>{let t=Ms(e);if(t!==void 0)return t;switch(e._tag){case`InvalidType`:return Es(Xo(e.ast),e);case`InvalidValue`:{let t=Ts(e);if(t!==void 0)return Es(t,e);let n=ws(e);return n===void 0?`Expected a valid value`:`Invalid data ${n}`}case`MissingKey`:return`Missing key`;case`UnexpectedKey`:{let t=ws(e);return t===void 0?`Expected no excess property`:`Unexpected key with value ${t}`}case`Forbidden`:return`Forbidden operation`;case`OneOf`:{let t=ws(e);return t===void 0?`Expected exactly one member to match`:`Expected exactly one member to match the input ${t}`}}},Ss=e=>Ms(e.issue)??Ms(e);function Cs(e){return t=>({issues:Ds(t,[],e?.leafHook??xs,e?.checkHook??Ss)})}function ws(e){return as(e)?S(e.input):void 0}function Ts(e){let t=e.annotations?.expected;return typeof t==`string`?t:void 0}function Es(e,t){let n=ws(t);return n===void 0?`Expected ${e}`:`Expected ${e}, got ${n}`}function Ds(e,t,n,r){switch(e._tag){case`Filter`:{let i=r(e);if(i!==void 0)return[{path:t,message:i}];if(e.issue._tag!==`InvalidValue`)return Ds(e.issue,t,n,r);let a=Ts(e.issue);return[{path:t,message:a===void 0?Es(Os(e.filter),e):Es(a,e.issue)}]}case`Encoding`:return Ds(e.issue,t,n,r);case`Pointer`:return Ds(e.issue,[...t,...e.path],n,r);case`Composite`:return e.issues.flatMap(e=>Ds(e,t,n,r));case`AnyOf`:return e.issues.length===0?[{path:t,message:Ms(e)??Es(Xo(e.ast),e)}]:e.issues.flatMap(e=>Ds(e,t,n,r));default:return[{path:t,message:n(e)}]}}function Os(e){let t=e.annotations?.expected;if(typeof t==`string`)return t;switch(e._tag){case`Filter`:return`<filter>`;case`FilterGroup`:return e.checks.map(e=>Os(e)).join(` & `)}}function ks(){return e=>js(e,``)}var As=ks();function js(e,t){let n;switch(e._tag){case`Filter`:{let r=Ss(e);if(r!==void 0)n=r;else{if(e.issue._tag!==`InvalidValue`)return js(e.issue,t);let r=Ts(e.issue);n=r===void 0?Es(Os(e.filter),e):Es(r,e.issue)}break}case`Encoding`:return js(e.issue,t);case`Pointer`:return js(e.issue,t+Gt(e.path));case`Composite`:case`AnyOf`:if(e._tag===`Composite`||e.issues.length>0)return e.issues.map(e=>js(e,t)).join(`
|
|
3
|
+
`);n=Ms(e)??Es(Xo(e.ast),e);break;default:n=xs(e)}return t?`${n}\n at ${t}`:n}function Ms(e){if(e._tag===`Pointer`)return;if(e._tag===`Encoding`)return Ms(e.issue);let t=(e._tag===`Filter`?e.filter.annotations:`annotations`in e?e.annotations:e.ast.annotations)?.[e._tag===`MissingKey`?`messageMissingKey`:e._tag===`UnexpectedKey`?`messageUnexpectedKey`:`message`];if(typeof t==`string`)return t}function Ns(e){let t;for(let n of e.reasons){if(!Hi(n)||!is(n.error))return;t??=n.error}return t}function Ps(e,t){let n=Ns(e);if(n===void 0)throw Error(t,{cause:e});return n}var Fs=e=>Eo(e).replace(/=/g,``).replace(/\+/g,`-`).replace(/\//g,`_`),Is=e=>{let t=e.replace(/[\n\r]/g,``),n=t.length;if(n%4==1)return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Length should be a multiple of 4, but is ${n}`}));if(!/^[-_A-Z0-9]*?={0,2}$/i.test(t))return ve(new Vi({module:`Base64Url`,kind:`Decode`,input:t,message:`Invalid input`}));let r=n%4==2?`${t}==`:n%4==3?`${t}=`:t;return r=r.replace(/-/g,`+`).replace(/_/g,`/`),Do(r)},Ls=e=>Object.assign(Object.create(Te),e);function Rs(e){return qs((t,n)=>v(e(t,n)))}function zs(e){return Rs((t,n)=>{let r={message:e(t)};return Nr(t)?new hs(r,t.value,n):new hs(r)})}var Bs=zs(()=>`Encoding is not supported`),Vs=Ls({_tag:`Passthrough`});function Hs(){return Vs}function Us(){return Vs}function Ws(e){return Ls({_tag:`Transform`,transform:e})}function Gs(e){return Ls({_tag:`TransformEffect`,transform:e})}function Ks(e){return Ls({_tag:`TransformOptional`,transform:e})}function qs(e){return Ls({_tag:`TransformOptionalEffect`,transform:e})}function Js(){return Ks(()=>Cn())}function Ys(e){return qs(t=>{let n=En(t,ci);return Nr(n)?x(n):Ie(e,Sr)})}function Xs(){return Ws(globalThis.String)}function Zs(){return Ws(globalThis.Number)}function Qs(){return Ws(globalThis.BigInt)}function $s(){return Ws(e=>new globalThis.Date(e))}function ec(){return Ws(Za)}function tc(e){return Gs((t,n)=>oi({try:()=>JSON.parse(t,e?.reviver),catch:()=>new ms({expected:`a valid JSON string`},t,n)}))}function nc(e){return Gs((t,n)=>oi({try:()=>{let n=JSON.stringify(t,e?.replacer,e?.space);if(n===void 0)throw TypeError(`Value cannot be represented as JSON`);return n},catch:()=>new ms({expected:`a JSON-serializable value`},t,n)}))}function rc(){return Ws(Eo)}function ic(){return Gs((e,t)=>fi(a(Do(e)),()=>new ms({expected:`a valid Base64 string`},e,t)))}var ac=class extends pe{_tag=`Middleware`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new ac(this.encode,this.decode)}},oc=`~effect/SchemaTransformation/Transformation`,sc=class extends pe{[oc]=oc;_tag=`Transformation`;decode;encode;constructor(e,t){super(),this.decode=e,this.encode=t}flip(){return new sc(this.encode,this.decode)}};function cc(e){return br(e,oc)&&e[oc]===oc}var lc=e=>cc(e)?e:new sc(e.decode,e.encode);function uc(e){return new sc(Gs(e.decode),Gs(e.encode))}function dc(){return new sc(ec(),Hs())}var fc=new sc(Hs(),Hs());function pc(){return fc}var mc=new sc(Zs(),Xs()),hc=new sc(Qs(),Xs()),gc=new sc($s(),Ws(je)),_c=new sc(ic(),rc());function vc(e){return new sc(tc(e??{}),nc(e))}function yc(e){return t=>t._tag===e}var bc=yc(`Declaration`),xc=yc(`Null`),Sc=yc(`Undefined`),Cc=yc(`Never`),wc=yc(`String`),Tc=yc(`Number`),Ec=yc(`Boolean`),Dc=yc(`Literal`),Oc=yc(`UniqueSymbol`),kc=yc(`Arrays`),Ac=yc(`Objects`),jc=yc(`Union`),Mc=yc(`Suspend`),Nc=class{to;transformation;constructor(e,t){this.to=e,this.transformation=t}},Pc={},Fc=class{isOptional;isMutable;constructorDefault;annotations;constructor(e,t,n=void 0,r=void 0){this.isOptional=e,this.isMutable=t,this.constructorDefault=n,this.annotations=r}},Ic=`~effect/Schema`,Lc=class{[Ic]=Ic;annotations;checks;encoding;context;constructor(e=void 0,t=void 0,n=void 0,r=void 0){this.annotations=e,this.checks=t,this.encoding=n,this.context=r}toString(){return`<${this._tag}>`}},Rc=class extends Lc{_tag=`Declaration`;typeParameters;run;encodingChecks;encodingRun;constructor(e,t,n,r,i,a,o,s){super(n,r,i,a),this.typeParameters=e,this.run=t,this.encodingChecks=o,this.encodingRun=s}getParser(){let e;return(t,n)=>t===E?$o:(e??=this.run(this.typeParameters))(t,this,n)}_rebuild(e,t,n,r,i){let a=du(this.typeParameters,e);return a===this.typeParameters&&t===this.checks&&n===this.encodingChecks&&r===this.run&&i===this.encodingRun?this:new Rc(a,r,this.annotations,t,void 0,this.context,n,i)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks,this.run,this.encodingRun)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks,this.encodingRun??this.run,this.run)}getExpected(){let e=this.annotations?.expected;return typeof e==`string`?e:`<Declaration>`}},zc=new class extends Lc{_tag=`Null`;getParser(){return Mu(this,null)}getExpected(){return`null`}},Bc=class extends Lc{_tag=`Undefined`;getParser(){return Mu(this,void 0)}toCodecJson(){return $l(this,[Vc])}getExpected(){return`undefined`}},Vc=new Nc(zc,new sc(Ws(()=>void 0),Ws(()=>null))),Hc=new Bc,Uc=new class extends Lc{_tag=`Never`;getParser(){return Nu(this,$t)}getExpected(){return`never`}},Wc=new class extends Lc{_tag=`Unknown`;getParser(){return Nu(this,ie)}getExpected(){return`unknown`}},Gc=class extends Lc{_tag=`Literal`;literal;constructor(e,t,n,r,i){if(super(t,n,r,i),typeof e==`number`&&!globalThis.Number.isFinite(e))throw Error(`A numeric literal must be finite, got ${S(e)}`);this.literal=e}getParser(){return Mu(this,this.literal)}matchPart(e,t){return e===globalThis.String(this.literal)?this.literal:void 0}toCodecJson(){return typeof this.literal==`bigint`?Kc(this):this}toCodecStringTree(){return typeof this.literal==`string`?this:Kc(this)}getExpected(){return typeof this.literal==`string`?JSON.stringify(this.literal):globalThis.String(this.literal)}};function Kc(e){let t=globalThis.String(e.literal);return $l(e,[new Nc(new Gc(t),new sc(Ws(()=>e.literal),Ws(()=>t)))])}var qc=new class extends Lc{_tag=`String`;getParser(){return Nu(this,$r)}matchPart(e,t){let n=this.checks;return n&&!t.disableChecks&&Yu(n,e,void 0,this,t)?void 0:e}getExpected(){return`string`}},Jc=class extends Lc{_tag=`Number`;getParser(){return Nu(this,un)}matchKey(e,t){return this._match(Ru,e,t)}matchPart(e,t){return this._match(Lu,e,t)}_match(e,t,n){if(!e.test(t))return;let r=globalThis.Number(t);return n.disableChecks||!this.checks?r:Yu(this.checks,r,void 0,this,n)?void 0:r}toCodecJson(){return this.checks&&(Yc(this.checks,`effect/schema/isFinite`)||Yc(this.checks,`effect/schema/isInt`))?this:$l(this,[Jl])}toCodecStringTree(){return this.toCodecJson()===this?$l(this,[Vu]):$l(this,[Hu])}getExpected(){return`number`}};function Yc(e,t){return e.some(e=>e.annotations?.representation?.id===t||e._tag===`FilterGroup`&&Yc(e.checks,t))}var Xc=new Jc,Zc=new class extends Lc{_tag=`Boolean`;getParser(){return Nu(this,zn)}getExpected(){return`boolean`}},Qc=new class extends Lc{_tag=`Symbol`;getParser(){return Nu(this,St)}matchKey(e,t){return t.disableChecks||!this.checks?e:Yu(this.checks,e,void 0,this,t)?void 0:e}toCodecStringTree(){return $l(this,[qu])}getExpected(){return`symbol`}},$c=new class extends Lc{_tag=`BigInt`;getParser(){return Nu(this,ar)}matchPart(e,t){if(!Uu.test(e))return;let n=globalThis.BigInt(e);return t.disableChecks||!this.checks?n:Yu(this.checks,n,void 0,this,t)?void 0:n}toCodecStringTree(){return $l(this,[Gu])}getExpected(){return`bigint`}},el=class extends Lc{_tag=`Arrays`;isMutable;elements;rest;encodingChecks;constructor(e,t,n,r,i,a,o,s){super(r,i,a,o),this.isMutable=e,this.elements=t,this.rest=n,this.encodingChecks=s;let c=!1;for(let e=0;e<t.length;e++)if(Su(t[e]))c=!0;else if(c)throw Error(`A required element cannot follow an optional element. ts(1257)`);if(c&&n.length>1)throw Error(`A required element cannot follow an optional element. ts(1257)`);for(let e=1;e<n.length;e++)if(Su(n[e]))throw Error(`An optional element cannot follow a rest element. ts(1266)`)}getParser(e,t=e){let n=this,r,i,a=n.elements.length,o=Math.max(0,n.rest.length-1);function s(e,t){return t<a?r[t]:t>=e?i[t-e+1]:i[0]}let c=e=>{let{input:t,len:r,options:i}=e;if(n.rest.length===0&&r>a)for(let o=a;o<r;o++){let r=new ds(n,t[o],i),a=new ls([o],r);if(i.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return v(new fs(n,[a],t,i))}return e.issues?v(new fs(n,e.issues,t,i)):Qo(e.output)},l=(e,t)=>{let r=e.length,i={ast:n,getParser:s,input:e,len:r,tailThreshold:Math.max(a,r-o),output:new globalThis.Array(r),issues:void 0,options:t},u=n.rest.length===0?a:Math.max(r,a+o),d=t.concurrency===void 0?1:Ur(t.concurrency),f=d===1?rl(i,e,0,u):il(i,e,{concurrency:d,end:u});if(!f)return c(i);if(pt(f))return cn(f,()=>c(i));let p=!0;return sr(()=>p?(p=!1,T(f,()=>c(i))):l(e,t))};return(e,a)=>{if(e===E)return $o;try{return Array.isArray(e)?(r||(r=n.elements.map(e=>({ast:e,parser:t(e)})),i=n.rest.map(e=>({ast:e,parser:t(e)}))),l(e,a)):v(new ps(n,e,a))}catch(e){return vr(e)}}}_rebuild(e,t,n){let r=du(this.elements,e),i=du(this.rest,e);return r===this.elements&&i===this.rest&&t===this.checks&&n===this.encodingChecks?this:new el(this.isMutable,r,i,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}getExpected(){return`array`}};function tl(e,t,n,r){if(n._tag===`Failure`)return al(e,e.ast,r,n);let i=n===es?t:n[et];if(i!==E)e.output[r]=i;else{let t=e.getParser(e.tailThreshold,r);if(Su(t.ast))return;let n=new ls([r],new us(t.ast.context?.annotations));if(e.options.errors===`all`)e.issues?e.issues.push(n):e.issues=[n];else return aa(new fs(e.ast,[n],e.input,e.options))}}var nl={onItem(e,t,n){let r=n<e.len?t:E;return e.getParser(e.tailThreshold,n).parser(r,e.options)},step:tl},rl=an()(nl),il=Wn()(nl),al=(e,t,n,r)=>{if(r.cause.reasons.length===0)return r;let i=Ns(r.cause);if(i===void 0)return ia(qi(r.cause,r=>new fs(t,[new ls([n],r)],e.input,e.options)));let a=new ls([n],i);if(e.options.errors===`all`)e.issues?e.issues.push(a):e.issues=[a];else return aa(new fs(t,[a],e.input,e.options))},ol=`[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?`;function sl(e,t,n=Pc){let r,i;function a(t){switch(t._tag){case`String`:case`TemplateLiteral`:return(r??=Object.keys(e)).filter(e=>t.matchPart(e,n)!==void 0);case`Number`:return(r??=Object.keys(e)).filter(e=>t.matchKey(e,n)!==void 0);case`Symbol`:return(i??=Object.getOwnPropertySymbols(e)).filter(r=>Object.prototype.propertyIsEnumerable.call(e,r)&&t.matchKey(r,n)!==void 0);case`Union`:return[...new Set(t.types.flatMap(a))];default:return[]}}return a(Pu(Ou(t)))}var cl=class{name;type;constructor(e,t){this.name=e,this.type=t}};function ll(e){switch(e._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return e.types.every(ll);default:return!1}}function ul(e){let t=tu(e);switch(t._tag){case`String`:case`Number`:case`Symbol`:case`TemplateLiteral`:return!0;case`Union`:return t.types.every(ul);default:return!1}}function dl(e){return ll(e)&&ul(e)}var fl=class{parameter;type;constructor(e,t){if(!dl(e))throw Error(`Invalid index signature parameter ${e._tag}`);if(this.parameter=e,this.type=t,Su(t)&&!ju(t))throw Error("Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.")}},pl=class extends Lc{_tag=`Objects`;propertySignatures;indexSignatures;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.propertySignatures=e,this.indexSignatures=t,this.encodingChecks=o}getParser(e,t=e){let n=this,r=n.propertySignatures.length,i=n.indexSignatures.length;if(!r&&!i)return Nu(n,qr);let a,o,s=()=>(a||(a=n.propertySignatures.map(e=>({parser:t(e.type),name:e.name,type:e.type})),o=i?n.indexSignatures.map(n=>({is:n,parserKey:e(Pu(n.parameter)),parserValue:t(n.type)})):void 0),a),c=()=>{let e=new Set(n.propertySignatures.map(e=>typeof e.name==`number`?globalThis.String(e.name):e.name)),t=(t,i,a,o,s)=>{if(s._tag===`Failure`)return al(t,n,i,s)??sa;let c=s===es?o:s[et];if(a!==E&&c!==E){if(r&&(e.has(i)||e.has(typeof a==`number`?globalThis.String(a):a)))return sa;h(t.out,a,c)}return sa},c=(e,r,i,a)=>{if(!a){let t=i.parserKey(r,e.options);if(!pt(t))return T(Ln(t),t=>c(e,r,i,t));a=t}if(a._tag===`Failure`)return al(e,n,r,a)??sa;let o=a===es?r:a[et],s=e.input[r],l=i.parserValue(s,e.options);return pt(l)?t(e,r,o,s,l):T(Ln(l),n=>t(e,r,o,s,n))},l=(e,n,r)=>{let i=e.input[n],a=r.parserValue(i,e.options);return pt(a)?t(e,n,n,i,a):T(Ln(a),r=>t(e,n,n,i,r))},u=i?Wn()({onItem:(e,[t,n])=>n.is.parameter===qc?l(e,t,n):c(e,t,n),step:(e,t,n)=>n._tag===`Failure`?n:void 0}):void 0;return m(function*(t,d){if(t===E)return E;if(!(typeof t==`object`&&t&&!Array.isArray(t)))return yield*v(new ps(n,t,d));s();let f=t,p={},m={ast:n,input:f,out:p,issues:void 0,options:d},ee=d.errors===`all`,te=d.onExcessProperty===`error`,ne=d.concurrency===void 0?1:Ur(d.concurrency),re=i&&te?n.indexSignatures.map(e=>sl(f,e.parameter,d)):void 0;if(te){let r=re?new Set(e):e;if(re)for(let e of re)for(let t of e)r.add(t);let i=Reflect.ownKeys(f);for(let e=0;e<i.length;e++){let a=i[e];if(!r.has(a)&&Object.prototype.propertyIsEnumerable.call(f,a)){let e=new ds(n,f[a],d),r=new ls([a],e);if(ee){m.issues?m.issues.push(r):m.issues=[r];continue}return yield*v(new fs(n,[r],t,d))}}}if(r){let e=ne===1?gl(m,a):_l(m,a,{concurrency:ne});e&&(yield*e)}if(i&&ne===1)for(let e=0;e<i;e++){let t=o[e],n=t.is.parameter===qc?l:c,r=re?.[e]??(t.is.parameter===qc?Object.keys(f):sl(f,t.is.parameter,d));for(let e=0;e<r.length;e++){let i=n(m,r[e],t);if(!pt(i))yield*i;else if(i._tag===`Failure`)return yield*i}}else if(u){let e=dt();for(let t=0;t<i;t++){let n=o[t],r=re?.[t]??(n.is.parameter===qc?Object.keys(f):sl(f,n.is.parameter,d));for(let t=0;t<r.length;t++)e.push([r[t],n])}let t=u(m,e,{concurrency:ne});t&&(yield*t)}return m.issues?yield*v(new fs(n,m.issues,t,d)):p})};if(i)return c();let l,u=(e,t,n)=>{let r=a[t];return T(Ln(n),n=>{let i=ml(e,r,n);if(i)return i;let o=()=>Qo(e.out),s=gl(e,a.slice(t+1));return s?cn(s,o):o()})};return(e,t)=>{if(e===E)return $o;if(t.errors===`all`||t.onExcessProperty!==void 0||t.concurrency!==void 0&&Ur(t.concurrency)!==1)return(l??=c())(e,t);if(!(typeof e==`object`&&e&&!Array.isArray(e)))return v(new ps(n,e,t));let r=s(),i=e,a={},o={ast:n,input:i,out:a,issues:void 0,options:t};try{for(let e=0;e<r.length;e++){let n=r[e],s=n.name,c=Al(i,s),l=c?i[s]:E,d=n.parser(l,t);if(!pt(d))return u(o,e,d);if(d===es){c&&h(a,s,l);continue}let f=ml(o,n,d);if(f)return f}}catch(e){return vr(e)}return Qo(a)}}_rebuild(e,t,n,r){let i=du(this.propertySignatures,t=>{let n=e(t.type);return n===t.type?t:new cl(t.name,n)}),a=du(this.indexSignatures,n=>{let r=t(n.parameter),i=e(n.type);return r===n.parameter&&i===n.type?n:new fl(r,i)});return i===this.propertySignatures&&a===this.indexSignatures&&n===this.checks&&r===this.encodingChecks?this:new pl(i,a,this.annotations,n,void 0,this.context,r)}flip(e){return this._rebuild(e,e,this.encodingChecks,this.checks)}recur(e,t=e){return this._rebuild(e,t,this.checks,this.encodingChecks)}getExpected(){return this.propertySignatures.length===0&&this.indexSignatures.length===0?`object | array`:`object`}};function ml(e,t,n){if(n._tag===`Failure`)return al(e,e.ast,t.name,n);if(n===es)return;let r=n[et];if(r!==E){h(e.out,t.name,r);return}if(delete e.out[t.name],!Su(t.type)){let n=new ls([t.name],new us(t.type.context?.annotations));if(e.options.errors===`all`){e.issues?e.issues.push(n):e.issues=[n];return}return aa(new fs(e.ast,[n],e.input,e.options))}}var hl={onItem(e,t){if(!Al(e.input,t.name))return t.parser(E,e.options);let n=e.input[t.name];return h(e.out,t.name,n),t.parser(n,e.options)},step:ml},gl=an()(hl),_l=Wn()(hl);function vl(e,t){return e?t?[...e,...t]:e:t}function yl(e,t,n){return new pl(Reflect.ownKeys(e).map(t=>new cl(t,e[t].ast)),[],n,t)}function bl(e){return e.ast}function xl(e,t=void 0){return new el(!1,e.map(e=>e.ast),[],void 0,t)}function Sl(e,t,n){return new Ml(e.map(bl),t,void 0,n)}function Cl(e){if(e.encoding)throw Error(`mutable does not support encodings`);return new el(!0,e.elements,e.rest,e.annotations,e.checks,void 0,e.context,e.encodingChecks)}var wl=rt(e=>{for(;;){if(Mc(e))return Wc;let t=e.encoding;if(!t)return e.recur?.(wl,He)??e;if(t.some(e=>e.transformation._tag===`Middleware`&&e.transformation.decode!==He))return Wc;e=t[t.length-1].to}});function Tl(e){switch(e._tag){case`Null`:return[`null`];case`Undefined`:return[`undefined`];case`String`:case`TemplateLiteral`:return[`string`];case`Number`:return[`number`];case`Boolean`:return[`boolean`];case`Symbol`:case`UniqueSymbol`:return[`symbol`];case`BigInt`:return[`bigint`];case`Arrays`:return[`array`];case`ObjectKeyword`:return[`object`,`array`,`function`];case`Objects`:return e.propertySignatures.length||e.indexSignatures.length?[`object`]:[`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`];case`Enum`:return Array.from(new Set(e.enums.map(([,e])=>typeof e)));case`Literal`:return[typeof e.literal];case`Union`:return Array.from(new Set(e.types.flatMap(Tl)));default:return[`null`,`undefined`,`string`,`number`,`boolean`,`symbol`,`bigint`,`object`,`array`,`function`]}}function El(e){switch(e._tag){default:return[];case`Declaration`:{let t=e.annotations?.[Uo];return Array.isArray(t)?t:[]}case`Objects`:return e.propertySignatures.flatMap(e=>{let t=e.type;if(!Su(t)){if(Dc(t))return[{key:e.name,literal:t.literal}];if(Oc(t))return[{key:e.name,literal:t.symbol}]}return[]});case`Arrays`:return e.elements.flatMap((e,t)=>{if(!Su(e)){if(Dc(e))return[{key:t,literal:e.literal}];if(Oc(e))return[{key:t,literal:e.symbol}]}return[]});case`Union`:{if(e.types.length===0)return[];let t=e.types.map(e=>El(wl(e)));return t[0].filter(e=>t.every(t=>t.some(t=>t.key===e.key&&t.literal===e.literal)))}case`Suspend`:return El(e.thunk())}}var Dl=new WeakMap,Ol=Object.freeze([]),kl=e=>e===null?`null`:Array.isArray(e)?`array`:typeof e,Al=(e,t)=>t===`__proto__`?Object.hasOwn(e,t):t in e;function jl(e){let t=Dl.get(e);if(t)return t;let n,r=0,i,a,o=!0,s=[];for(let t=0;t<e.length;t++){let c=e[t],l=wl(c);if(Cc(l))continue;if(Dc(l)||Oc(l)){a??=new Map;let e=Dc(l)?l.literal:l.symbol;s[t]=e;let n=a.get(e);n||a.set(e,n=[]),n.push(t)}else o=!1;let u=El(l);if(u.length){n??=new Map,r++;for(let{key:e,literal:r}of u){let i=n.get(e);i||n.set(e,i=[new Map,new Set]),i[1].add(t);let a=i[0].get(r);a||i[0].set(r,a=new Set),a.add(t)}}else{i??={};let e=Tl(l);for(let n of e)(i[n]??=[]).push(t)}}let c={},l=e=>c[e]??=Object.freeze(i?.[e]??Ol);if(o&&a)a.forEach(Object.freeze),t=e=>a.get(e)??Ol;else if(n?.size===1&&!i){let[r,[i]]=n.entries().next().value,a=new Map;for(let[e,t]of i)a.set(e,Object.freeze(Array.from(t)));let o=Object.freeze(e.map((e,t)=>t));t=(e,t)=>{if(gt(e)){let n=Al(e,r)?e[r]:void 0;if(n!==void 0)return a.get(n)??Ol;if(t)return o}return Ol}}else if(n){let e;for(let t of n)(!e||t[1][0].size>e[1][0].size)&&t[1][1].size===r&&(e=t);t=(t,r)=>{let a=kl(t);if(!gt(t))return l(a);let o=new Set(i?.[a]),s;if(e){let[n,[i]]=e,c=Al(t,n),u=c?t[n]:void 0;if(c&&(!r||u!==void 0)){let e=i.get(u);if(!e)return l(a);for(let t of e)o.add(t);s=n}}if(s===void 0)for(let[e,[i,a]]of n){let n=Al(t,e),s=n?t[e]:void 0;if(n&&(!r||s!==void 0)){let e=i.get(s);if(e)for(let t of e)o.add(t)}else if(r)for(let e of a)o.add(e)}for(let[e,[i,a]]of n){if(e===s)continue;let n=Al(t,e),c=n?t[e]:void 0;if(n&&(!r||c!==void 0)){let e=i.get(c);for(let t of o)a.has(t)&&!e?.has(t)&&o.delete(t)}}return Array.from(o).sort((e,t)=>e-t)}}else t=e=>{let t=l(kl(e));return a?t.filter(t=>s[t]===void 0||s[t]===e):t};return Dl.set(e,t),t}var Ml=class extends Lc{_tag=`Union`;types;options;encodingChecks;constructor(e,t,n,r,i,a,o){super(n,r,i,a),this.types=e,this.options=t,this.encodingChecks=o}getParser(e,t){let n=this,r=t!==void 0,i=[],a=t=>i[t]??=e(n.types[t]),o;return(e,t)=>{if(e===E)return $o;let i=(o??=jl(n.types))(e,r);if(i.length===0)return v(new gs(n,[],e,t));if(i.length===1){let r=a(i[0])(e,t);return r._tag===`Success`?r:pt(r)?Nl(n,r.cause,e,t):Pl(n,r,e,t)}return Fl(n,a,i,e,t)}}_rebuild(e,t,n){let r=du(this.types,e);return r===this.types&&t===this.checks&&n===this.encodingChecks?this:new Ml(r,this.options,this.annotations,t,void 0,this.context,n)}recur(e){return this._rebuild(e,this.checks,this.encodingChecks)}flip(e){return this._rebuild(e,this.encodingChecks,this.checks)}matchPart(e,t){for(let n of this.types){let r=n.matchPart(e,t);if(r!==void 0)return r}}getExpected(e){let t=this.annotations?.expected;if(typeof t==`string`)return t;if(this.types.length===0)return`never`;let n=this.types.map(t=>{let n=Ou(t);switch(n._tag){case`Arrays`:{let t=n.elements.filter(Dc);if(t.length>0)return`${zl(n.isMutable)}[ ${t.map(t=>e(t)+Bl(t.context?.isOptional)).join(`, `)}, ... ]`;break}case`Objects`:{let t=n.propertySignatures.filter(e=>Dc(e.type));if(t.length>0)return`{ ${t.map(t=>`${zl(t.type.context?.isMutable)}${Bt(t.name)}${Bl(t.type.context?.isOptional)}: ${e(t.type)}`).join(`, `)}, ... }`;break}}return e(n)});return Array.from(new Set(n)).join(` | `)}};function Nl(e,t,n,r){let i=Ns(t);return i?aa(new gs(e,[i],n,r)):ia(t)}function Pl(e,t,n,r){return Br(t,t=>Nl(e,t,n,r))}function Fl(e,t,n,r,i){let a={ast:e,parser:t,input:r,out:void 0,successes:e.options?.mode===`oneOf`?[]:void 0,issues:void 0,options:i},o=Ll(a,n);if(!o)return a.out?a.out:v(new gs(e,a.issues??[],r,i));if(pt(o))return Il(o,a);let s=!0;return sr(()=>s?(s=!1,Il(o,a)):Fl(e,t,n,r,i))}function Il(e,t){return cn(e,e=>t.out===es?x(t.input):t.out?t.out:v(new gs(t.ast,t.issues??[],t.input,t.options)))}var Ll=an()({onItem(e,t){return e.parser(t)(e.input,e.options)},step(e,t,n){if(n._tag===`Failure`){let t=Ns(n.cause);if(t===void 0)return n;e.issues?e.issues.push(t):e.issues=[t]}else{if(e.out&&e.successes)return e.successes.push(e.ast.types[t]),aa(new _s(e.ast,e.successes,e.input,e.options));if(e.out=n,e.successes)e.successes.push(e.ast.types[t]);else return sa}}}),Rl=new Ml([new Gc(`Infinity`),new Gc(`-Infinity`),new Gc(`NaN`)]);function zl(e){return e?``:`readonly `}function Bl(e){return e?`?`:``}var Vl=class extends Lc{_tag=`Suspend`;thunk;constructor(e,t,n,r,i){if(n)throw Error(`Cannot add checks to Suspend`);super(t,void 0,r,i);let a;this.thunk=()=>a??=e()}getParser(e){let t;return(n,r)=>(t??=e(this.thunk()))(n,r)}recur(e){return new Vl(()=>e(this.thunk()),this.annotations,void 0,void 0,this.context)}getExpected(e){return e(this.thunk())}},Hl=class extends pe{_tag=`Filter`;run;annotations;aborted;constructor(e,t=void 0,n=!1){super(),this.run=e,this.annotations=t,this.aborted=n}annotate(e){return new Hl(this.run,{...this.annotations,...e},this.aborted)}abort(){return new Hl(this.run,this.annotations,!0)}and(e,t){return new Ul([this,e],t)}},Ul=class extends pe{_tag=`FilterGroup`;checks;annotations;constructor(e,t=void 0){super(),this.checks=e,this.annotations=t}annotate(e){return new Ul(this.checks,{...this.annotations,...e})}and(e,t){return new Ul([this,e],t)}};function Wl(e,t,n=!1){return new Hl((t,n,r)=>bs(n,e(t,n,r),t,r),t,n)}function Gl(e,t){return new Hl((t,n,r)=>e(t)?void 0:new ms(void 0,t,r),t,!0)}function Kl(e){return Wl(e=>globalThis.Number.isFinite(e),{expected:`a finite number`,representation:{id:`effect/schema/isFinite`,payload:null},toJsonSchema:()=>({type:`number`}),toCode:()=>({runtime:`Schema.isFinite()`}),arbitraryConstraint:{number:`finite`},...e})}var ql=iu(Xc,[Kl()]),Jl=new Nc(new Ml([ql,Rl]),new sc(Zs(),Ws(e=>globalThis.Number.isFinite(e)?e:globalThis.String(e))));function Yl(e,t){let n=new globalThis.RegExp(e),r={source:n.source,flags:n.flags};return Wl(e=>(n.lastIndex=0,n.test(e)),{expected:`a string matching the RegExp ${r.source}`,representation:{id:`effect/schema/isPattern`,payload:r},toJsonSchema:()=>[{},!0],arbitraryConstraint:{patterns:[r]},...t})}var Xl=new WeakMap;function Zl(e,t){let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,t);return Reflect.ownKeys(t).every(e=>e===`context`||e===`encoding`)&&Xl.set(n,Ql(e)),n}function Ql(e){let t=Xl.get(e);if(t!==void 0)return t;if(e.encoding===void 0)return e;let n=Object.assign(Object.create(Object.getPrototypeOf(e)),e,{encoding:void 0});return Xl.set(e,n),n}function $l(e,t){return e.encoding===t?e:Zl(e,{encoding:t})}function eu(e,t){if(e.context===t)return e;let n=Ql(e);return n.context===t&&n.encoding===e.encoding?n:Zl(e,{context:t})}function tu(e){return e.encoding?tu(e.encoding[e.encoding.length-1].to):e}function nu(e,t){if(e.checks){let n=e.checks[e.checks.length-1];return ru(e,Re(e.checks.slice(0,-1),n.annotate(t)))}return Zl(e,{annotations:{...e.annotations,...t}})}function ru(e,t){if(e._tag===`Suspend`&&t)throw Error(`Cannot add checks to Suspend`);return e.checks===t?e:Zl(e,{checks:t})}function iu(e,t){return ru(e,vl(e.checks,t))}function au(e,t){let n=t(e.to);return n===e.to?e:new Nc(n,e.transformation)}function ou(e,t){let n=e,r=n[n.length-1],i=au(r,t);return i===r?e:Re(e.slice(0,e.length-1),i)}function su(e){return t=>t.encoding?$l(t,ou(t.encoding,e)):t}function cu(e,t){return su(e=>eu(e,t))(e)}function lu(e,t){function n(r){if(r.encoding){let e=r.encoding[r.encoding.length-1];return t?.stopAt?.(e)?r:$l(r,ou(r.encoding,n))}return e(r)}return rt(n)}function uu(e,t,n){let r=new Nc(e,t);return $l(n,n.encoding?[...n.encoding,r]:[r])}function du(e,t){let n;for(let r=0;r<e.length;r++){let i=e[r],a=t(i);if(n)n[r]=a;else if(a!==i){n=Array(e.length);for(let t=0;t<r;t++)n[t]=e[t];n[r]=a}}return n??e}function fu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,e.context.constructorDefault,{...e.context.annotations,...t}):new Fc(!1,!1,void 0,t))}var pu=rt(e=>mu(eu(e,e.context?e.context.isOptional===!1?new Fc(!0,e.context.isMutable,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!0,!1)))),mu=su(pu),hu=qe(e=>pu(new Ml([e,Hc]))),gu=rt(e=>_u(eu(e,e.context?e.context.isMutable===!1?new Fc(e.context.isOptional,!0,e.context.constructorDefault,e.context.annotations):e.context:new Fc(!1,!0)))),_u=su(gu);function vu(e,t){return eu(e,e.context?new Fc(e.context.isOptional,e.context.isMutable,t,e.context.annotations):new Fc(!1,!1,t))}function yu(e,t,n){return uu(e,n,t)}function bu(e){let t=[],n=[];function r(e){switch(e._tag){case`Literal`:ee(e.literal)&&!t.includes(e.literal)&&t.push(e.literal);return;case`UniqueSymbol`:t.includes(e.symbol)||t.push(e.symbol);return;case`Never`:return;case`Union`:for(let t=0;t<e.types.length;t++)r(e.types[t]);return;default:n.push(e)}}return r(e),{literals:t,parameters:n}}function xu(e,t){let{literals:n,parameters:r}=bu(e);return new pl(n.map(e=>new cl(e,t)),r.map(e=>new fl(e,t)))}function Su(e){return e.context?.isOptional??!1}function Cu(e){return e.context?.isMutable??!1}function wu(e){return e.annotations?.[`~structural`]===!0||e._tag===`FilterGroup`&&e.checks.every(wu)}function Tu(e){function t(e){return wu(e)?[e]:e._tag===`FilterGroup`?e.checks.flatMap(t):[]}let n=e.flatMap(t);return d(n)?n:void 0}function Eu(e){let t=!0;function n(e){return t=t&&!e.encoding&&!Mc(e),t&&`recur`in e&&e.recur(n),e}return`recur`in e&&e.recur(n),t}var Du=rt(e=>{let t=Ql(e);if(t!==e){let n=Du(t);return n===t&&e.encoding===void 0?e:eu(n,e.context)}let n=`recur`in e?e.recur(Du):e;if(`encodingChecks`in n&&n.encodingChecks){let t=Eu(e)?n.encodingChecks:kc(n)||Ac(n)||bc(n)&&n.typeParameters.length>0?Tu(n.encodingChecks):void 0;return Zl(n,{encodingChecks:void 0,checks:vl(n.checks,t)})}return n}),Ou=rt(e=>Du(Au(e)));function ku(e,t){let n=t,r=n.length,i=n[r-1],a=[new Nc(Au($l(e,void 0)),n[0].transformation.flip())];for(let e=1;e<r;e++)a.unshift(new Nc(Au(n[e-1].to),n[e].transformation.flip()));let o=Au(i.to);return o.encoding?$l(o,[...o.encoding,...a]):$l(o,a)}var Au=qe(e=>{if(e.encoding)return ku(e,e.encoding);let t=Ql(e);if(t!==e){let n=Au(t);return n===t?e:eu(n,e.context)}return`flip`in e?e.flip(Au):`recur`in e?e.recur(Au):e});function ju(e){switch(e._tag){case`Undefined`:return!0;case`Union`:return e.types.some(ju);default:return!1}}function Mu(e,t){let n=t===0?es:Qo(t);return(r,i)=>r===E?$o:r===t?n:v(new ps(e,r,i))}function Nu(e,t){return(n,r)=>n===E?$o:t(n)?es:v(new ps(e,n,r))}var Pu=lu(e=>{switch(e._tag){default:return e;case`Number`:return e.toCodecStringTree();case`Union`:return e.recur(Pu)}}),Fu=lu(e=>{switch(e._tag){default:return e;case`Symbol`:case`UniqueSymbol`:return e.toCodecStringTree();case`Union`:return e.recur(Fu)}}),Iu=`[\\s\\S]*?`,Lu=new globalThis.RegExp(`^${ol}$`),Ru=new globalThis.RegExp(`^(?:${ol}|Infinity|-Infinity|NaN)$`);function zu(e){return Yl(Lu,{expected:`a string representing a finite number`,representation:{id:`effect/schema/isStringFinite`,payload:null},toJsonSchema:()=>({pattern:Lu.source}),...e})}var Bu=iu(qc,[zu()]),Vu=new Nc(Bu,mc),Hu=new Nc(new Ml([Bu,Rl]),mc),Uu=new globalThis.RegExp(`^-?\\d+$`);function Wu(e){return Yl(Uu,{expected:`a string representing a bigint`,representation:{id:`effect/schema/isStringBigInt`,payload:null},toJsonSchema:()=>({pattern:Uu.source}),...e})}var Gu=new Nc(iu(qc,[Wu({expected:`a string representing a bigint`})]),hc),Ku=new globalThis.RegExp(`^Symbol\\(([\\s\\S]*)\\)$`),qu=new Nc(iu(qc,[Ju()]),new sc(Ws(e=>globalThis.Symbol.for(Ku.exec(e)[1])),Gs((e,t)=>globalThis.Symbol.keyFor(e)===void 0?v(new hs({message:`cannot serialize to string, Symbol is not registered`},e,t)):x(globalThis.String(e)))));function Ju(e){return Yl(Ku,{expected:`a string representing a symbol`,representation:{id:`effect/schema/isStringSymbol`,payload:null},toJsonSchema:()=>({pattern:Ku.source}),...e})}function Yu(e,t,n,r,i){for(let a=0;a<e.length;a++){let o=e[a];if(o._tag===`FilterGroup`){if(n=Yu(o.checks,t,n,r,i),n&&(i.errors!==`all`||n[n.length-1].filter.aborted))return n}else{let e=o.run(t,r,i);if(e){let r=new ss(o,e,t,i);if(n?n.push(r):n=[r],i.errors!==`all`||o.aborted)return n}}}return n}function Xu(e){if(!bc(e))return;let t=e.annotations?.[Wo];return Nn(t)?t(e.typeParameters):void 0}var Zu=zo,Qu=Jo,$u=Yo;function ed(e){return e===null||typeof e==`string`||typeof e==`boolean`||typeof e==`number`&&globalThis.Number.isFinite(e)}function td(e){return e===void 0||typeof e==`string`}function nd(e,t){let n=new WeakMap,r=[];outer:for(;;){if(typeof e!=`object`||!e){if(!t(e))return!1}else{let t=e,i=n.get(t);if(i===!1)return!1;if(i===void 0){let e=Array.isArray(t);if(!e){let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype&&Object.getPrototypeOf(e)!==null)return!1}n.set(t,!1),r.push({value:t,keys:e?t.length:Object.keys(t),index:0})}}for(;r.length>0;){let t=r[r.length-1],i=t.keys;if(typeof i==`number`){if(t.index<i){e=t.value[t.index++];continue outer}}else if(t.index<i.length){e=t.value[i[t.index++]];continue outer}n.set(t.value,!0),r.pop()}return!0}}function rd(e){return nd(e,ed)}var id=new Rc([],()=>(e,t,n)=>rd(e)?es:v(new ps(t,e,n)),{representation:{id:`effect/schema/Json`,payload:null},expected:`JSON value`,toCodecJson:()=>void 0,toCodecStringTree:()=>cd}),ad=new Nc(id,pc()),od=new Nc(new Ml([new el(!1,[],[id]),new pl([],[new fl(qc,id)])]),pc());function sd(e){return nd(e,td)}var cd=new Nc(new Rc([],()=>(e,t,n)=>sd(e)?es:v(new ps(t,e,n)),{expected:`StringTree`,toCodecStringTree:()=>void 0}),pc()),ld=(e,t,n)=>e===es?n(t):cn(e,n);function ud(e){if(e._tag===`Middleware`)return(t,n,r)=>dd(t===es?e.decode(Qo(ts(n)),r):e.decode(Ie(t,ts),r));let t=e.decode;switch(t._tag){case`Passthrough`:return(e,t)=>e===es?Qo(t):e;case`Transform`:{let e=e=>e===E?$o:Qo(t.transform(e));return(t,n)=>ld(t,n,e)}case`TransformOptional`:{let e=e=>ns(t.transform(ts(e)));return(t,n)=>ld(t,n,e)}case`TransformEffect`:return(e,n,r)=>ld(e,n,e=>e===E?$o:t.transform(e,r));case`TransformOptionalEffect`:return(e,n,r)=>ld(e,n,e=>dd(t.transform(ts(e),r)))}}var dd=e=>cn(e,ns),fd=(e,t,n,r)=>Br(r,r=>Kr(()=>qi(r,r=>new cs(e,r,t,n))));function pd(e,t){let n=ud(e.link.transformation),r;return(i,a)=>{if(i===E)return $o;if(e.isConstructed(i))return es;let o=(r??=t(e.link.to))(i,a);return n(o,i,a)}}function md(e,t){let n=e.context.constructorDefault;return(r,i)=>{if(r!==E&&r!==void 0)return t(r,i);let a=n;if(pt(a)&&a._tag===`Success`){let e=t(a[et],i);return e===es?a:e}return cn(fd(e,r,i,a),e=>{let n=t(e,i);return n===es?Qo(e):n})}}function hd(e,t){let n=t(e);return e.context?.constructorDefault===void 0?n:md(e,n)}function gd(e,t,n,r,i){if(e._tag===`Declaration`)for(let n of e.typeParameters)t(n);let a=n?Xu(e):void 0,o=a?pd(a,t):r??e.getParser(t,n),s=e.checks,c=e.encoding,l=c?.map(e=>ud(e.transformation)),u=e.encodingChecks;if(!c&&!s&&!u)return o;let d,f=(t,n)=>{let r=o(t,n);if(u&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(t!==E&&i!==E){let i=Yu(u,t,void 0,e,n);i&&(r=v(new fs(e,i,t,n)))}}}else r=T(r,r=>{if(t!==E&&r!==E){let r=Yu(u,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(r)})}if(s&&!n.disableChecks){if(pt(r)){if(r._tag===`Success`){let i=r===es?t:r[et];if(i===E)return r;let a=Yu(s,i,void 0,e,n);a&&(r=v(new fs(e,a,i,n)))}}else r=T(r,t=>{if(t!==E){let r=Yu(s,t,void 0,e,n);if(r)return v(new fs(e,r,t,n))}return x(t)})}return r},p=i===void 0?f:i(f);return c?(n,r)=>{let i=d??=c.map(e=>t(e.to)),a=n,o=i[i.length-1](n,r);for(let e=c.length-1;e>=0;e--)if(o=l[e](o,a,r),e!==0){let t=i[e-1];o._tag===`Success`?(a=o[et],o=t(a,r)):o=cn(o,e=>{let n=t(e,r);return n===es?Qo(e):n})}if(o._tag===`Success`){let e=o[et],t=p(e,r);return t===es?o:t}return o=fd(e,n,r,o),cn(o,e=>{let t=p(e,r);return t===es?Qo(e):t})}:p}var _d=Symbol(),vd=new WeakMap,yd=e=>Cd(e).parser,bd=e=>Cd(e).makeEffect,xd=e=>hd(e,bd),Sd=class{ast;constructor(e){this.ast=e}get decodeEffect(){return this.cachedDecodeEffect??=gd(this.ast,yd)}get parser(){return this.decodeEffect}get makeEffect(){return this.cachedMakeEffect??=gd(this.ast,bd,xd)}};function Cd(e){let t=vd.get(e);if(t!==void 0)return t;let n=new Sd(e);return vd.set(e,n),n}function wd(e){let t=e.ast,n;return(e,r)=>(n??=Vd(Jd,Du(t)))(e,r?.disableChecks?r?.parseOptions?{...r.parseOptions,disableChecks:!0}:{disableChecks:!0}:r?.parseOptions)}function Td(e){let t=wd(e);return(e,n)=>{let r=Pr(t(e,n));return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Ed(e){return Kd(Du(e.ast))}function Dd(e){return kd(e.ast)}function Od(e){{let t=Hd(zd(e));return e=>{let n=t(e,Pc);return ca(n)?!0:(Ps(n.cause,`Type guard adapter can only return false for schema issues`),!1)}}}function kd(e){let t=Du(e),n=e=>(n=Od(t),n(e));return e=>n(e)}function Ad(e,t){let n=zd(e.ast);return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function jd(e,t){return Hd(Ad(e,t))}function Md(e,t){return Ud(Ad(e,t))}function Nd(e,t){return Wd(Ad(e,t))}function Pd(e,t){let n=zd(Au(e.ast));return t===void 0?n:(e,r)=>n(e,Ld(t,r))}function Fd(e,t){return Hd(Pd(e,t))}function Id(e,t){return Wd(Pd(e,t))}var Ld=(e,t)=>t?{...e,...t}:e,Rd=e=>e===E?v(new ms):x(e);function zd(e){return Vd(qd,e)}function Bd(e,t){return e===es?x(t):pt(e)?e[et]===E?Rd(E):e:cn(e,Rd)}function Vd(e,t){let n;return(r,i)=>{let a=(n??=e(t))(r,i??Pc);return a===es?x(r):pt(a)?a[et]===E?Rd(E):a:cn(a,Rd)}}function Hd(e){return(t,n)=>Pr(e(t,n))}function Ud(e){let t=Hd(e);return(e,n)=>{let r=t(e,n);return ca(r)?Sr(r.value):(Ps(r.cause,`Option adapter can only return none for schema issues`),Cn())}}function Wd(e){let t=Hd(e);return(e,r)=>{let i=t(e,r);return ca(i)?n(i.value):ve(Ps(i.cause,`Result adapter can only return schema issues`))}}function Gd(e,t){let n=Pr(e);if(ca(n))return n.value;let r=Ps(n.cause,t);throw Error(`Schema validation failed`,{cause:r})}function Kd(e){let t,n;return(r,i)=>{t??=Cd(e);let a=i?.disableChecks?i.parseOptions?{...i.parseOptions,disableChecks:!0}:{disableChecks:!0}:i?.parseOptions??Pc,o=t.make;if(o!==void 0&&r!==E){let e;try{e=o(r,a)}catch(e){throw Ps(Gi(e),`Constructor adapter can only throw schema issues`),e}if(e!==_d&&e!==E)return e}return Gd(Bd((n??=t.makeEffect)(r,a),r),`Constructor adapter can only throw schema issues`)}}var qd=e=>Cd(e).parser,Jd=e=>Cd(e).makeEffect,Yd=`~effect/Schema/Schema`,Xd=Symbol(),Zd={[Yd]:Yd,get make(){let e=Ed(this);return Object.defineProperty(this,"make",{value:e,enumerable:!0}),e},get makeEffect(){let e=wd(this);return Object.defineProperty(this,"makeEffect",{value:e,enumerable:!0}),e},get makeOption(){let e=Td(this);return Object.defineProperty(this,"makeOption",{value:e,enumerable:!0}),e},pipe(){return Le(this,arguments)},annotate(e){return this.rebuild(nu(this.ast,e))},annotateKey(e){return this.rebuild(fu(this.ast,e))},check(...e){return this.rebuild(iu(this.ast,e))},rebuild(e){return Qd(e,this[Xd])}};function Qd(e,t){function n(){}let r=Object.setPrototypeOf(n,Zd);return t&&(Object.hasOwn(t,`name`)||Object.hasOwn(t,`length`)||Object.hasOwn(t,`__proto__`))?Object.defineProperties(r,Object.getOwnPropertyDescriptors({...t})):Object.assign(r,t),r[Xd]=t,r.ast=e,r}function $d(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ef(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function tf(e){return encodeURI($d(e)).replace(/#/g,`%23`)}function nf(e){if(e.length===0||e===`#`)return``;if(!e.startsWith(`#`))return;let t=e.slice(1);try{if(encodeURI(t).replace(/%25/g,`%`).replace(/#/g,`%23`)!==t)return;let e=decodeURIComponent(t);return e.startsWith(`/`)&&!/~(?:[^01]|$)/.test(e)?e:void 0}catch{return}}function rf(e){let t=nf(e);return t===void 0?void 0:t.length===0?[]:t.slice(1).split(`/`).map(ef)}function af(e){return e.reduce((e,t)=>`${e}/${tf(t)}`,`#`)}var of=`http://json-schema.org/draft-07/schema#`;function sf(e,t){return e===t||e===(t.endsWith(`#`)?t.slice(0,-1):`${t}#`)}function cf(e){return{dialect:`draft-07`,...bf(e,Mf)}}function lf(e,t){return n(e,!1,!0);function n(e,r,i=!1){if(!ri(e))return e;let a=r||!i&&yf(e.$id),o={};for(let t of Object.keys(e)){let r=e[t],i=r;switch(t){case`$defs`:case`properties`:case`patternProperties`:case`dependentSchemas`:i=ff(r,e=>n(e,a))??r;break;case`allOf`:case`anyOf`:case`oneOf`:case`prefixItems`:i=Array.isArray(r)?r.map(e=>n(e,a)):r;break;case`not`:case`additionalProperties`:case`propertyNames`:case`unevaluatedProperties`:case`items`:case`contains`:case`unevaluatedItems`:case`if`:case`then`:case`else`:case`contentSchema`:i=n(r,a)}h(o,t,i)}return t(o,a),o}}function uf(e,t){return lf(e,e=>{df(e,t)})}function df(e,t){typeof e.$ref==`string`&&h(e,`$ref`,t(e.$ref,`$ref`)),typeof e.$dynamicRef==`string`&&h(e,`$dynamicRef`,t(e.$dynamicRef,`$dynamicRef`))}function ff(e,t){if(!ri(e))return;let n={};for(let r of Object.keys(e))h(n,r,t(e[r],r));return n}function pf(e,t,n){let r=new Map,i=[],a=mf;function o(e,n=[],r=[]){return n.length===0&&t?.trackIds&&(a=gf(ri(e)?u(e):void 0,mf)??mf),l(e,n,r,{sourceRoot:[],targetRoot:[],uri:a})}function s(){for(let[e,t,n]of i){let i=t,a=hf(t,n);if(a!==void 0){let e=rf(a.hash);if(a.hash=``,e!==void 0){let n=r.get(vf(a.href,e));n!==void 0&&(i=_f(t,n))}}h(e,`$ref`,i)}}let c=n(o);return s(),c;function l(n,r,a,o){if(typeof n==`boolean`)return d(r,a,o),t?.booleanAdapter?.(n)??n;if(!ri(n))return n;let s=o,c=u(n);if(r.length>0&&t?.trackIds&&yf(c)){let e=gf(c,o.uri);e!==void 0&&(s={parent:o,sourceRoot:r,targetRoot:a,uri:e})}d(r,a,s);let f=s.uri;return e(n,{isDocumentRoot:r.length===0,schema(e,t,n=t){return l(e,[...r,t],[...a,n],s)},schemaAt(e,t,n){return l(e,[...r,...t],[...a,...n],s)},schemaArray(e,t,n=t){return Array.isArray(e)?e.map((e,i)=>l(e,[...r,t,String(i)],[...a,n,String(i)],s)):e},schemaMap(e,t,n=t){return ri(e)?ff(e,(e,i)=>l(e,[...r,t,i],[...a,n,i],s)):e},reference(e,t){typeof t==`string`?i.push([e,t,f]):h(e,`$ref`,t)}})}function u(e){return t?.ignoreRefSiblings===!0&&typeof e.$ref==`string`?void 0:e.$id}function d(e,t,n){n.parent!==void 0&&d(e,t,n.parent),r.set(vf(n.uri,e.slice(n.sourceRoot.length)),t.slice(n.targetRoot.length))}}var mf=`https://effect.invalid/.json-schema/`;function hf(e,t){return URL.canParse(e,t)?new URL(e,t):void 0}function gf(e,t){if(typeof e!=`string`)return;let n=hf(e,t);if(n!==void 0)return n.hash=``,n.href}function _f(e,t){let n=e.indexOf(`#`);return n===-1&&t.length===0?e:`${n===-1?e:e.slice(0,n)}${af(t)}`}function vf(e,t){return`${e}\u0000${JSON.stringify(t)}`}function yf(e){return typeof e==`string`&&e.length>0&&e[0]!==`#`}function bf(e,t,n){return pf(t,{...n,trackIds:!0},t=>({schema:t(e.schema),definitions:ff(e.definitions,(e,n)=>t(e,[`$defs`,n],[`definitions`,n]))}))}var xf=new Set([`properties`,`patternProperties`]),Sf=new Set([`allOf`,`anyOf`,`oneOf`]),Cf=new Set([`not`,`additionalProperties`,`propertyNames`,`contains`,`if`,`then`,`else`,`contentSchema`]);function wf(e,t,n,r,i,a=xf){let o;if(a.has(t))o=r.schemaMap(n,t);else if(Sf.has(t))o=r.schemaArray(n,t);else if(i.has(t))o=r.schema(n,t);else return!1;return h(e,t,o),!0}var Tf=[`$anchor`,`$defs`,`$dynamicAnchor`,`$dynamicRef`,`$vocabulary`,`contentSchema`,`dependentRequired`,`dependentSchemas`,`maxContains`,`minContains`,`prefixItems`,`unevaluatedItems`,`unevaluatedProperties`];[...Tf],[...Tf];var Ef=/^[A-Za-z_][-A-Za-z0-9._]*$/,Df=/^[A-Za-z][-A-Za-z0-9._:]*$/;function Of(e,t,n){throw Error(`Cannot convert JSON Schema keyword "${e}" to ${t}: ${n}`)}function kf(e,t,n,r){for(let i of t)Object.hasOwn(e,i)&&Of(i,n,`it is not active in ${r} but would become active in the target`)}var Af=[`additionalItems`,`definitions`,`dependencies`];function jf(e,t,n,r,i){n.isDocumentRoot?h(e,`$schema`,sf(t,`https://json-schema.org/draft/2020-12/schema`)?r:t):sf(t,`https://json-schema.org/draft/2020-12/schema`)||Of(`$schema`,i,`an embedded resource cannot declare a different dialect`)}function Mf(e,t){kf(e,Af,`Draft-07`,`Draft 2020-12`);let n={},r,i,a;for(let o of Object.keys(e)){let s=e[o];if(!wf(n,o,s,t,Cf))switch(o){case`$ref`:r=s;break;case`$schema`:jf(n,s,t,of,`Draft-07`);break;case`$id`:case`$anchor`:break;case`$defs`:h(n,`definitions`,t.schemaMap(s,o,`definitions`));break;case`prefixItems`:i=s;break;case`items`:a=s;break;case`dependentRequired`:case`dependentSchemas`:case`minContains`:case`maxContains`:break;case`$dynamicRef`:case`$dynamicAnchor`:case`$vocabulary`:case`unevaluatedProperties`:case`unevaluatedItems`:Of(o,`Draft-07`,`the target dialect has no equivalent`);case`required`:if(Array.isArray(s)&&s.length===0)break;h(n,o,s);break;default:h(n,o,s)}}if(Nf(n,i,a,t),Object.hasOwn(e,`contains`)){let t=e.minContains,r=e.maxContains;(t!==void 0&&t!==1||r!==void 0)&&Of(`minContains/maxContains`,`Draft-07`,`contains cardinality cannot be represented`),Object.hasOwn(e,`minContains`)&&h(n,`minContains`,t)}else Object.hasOwn(e,`minContains`)&&h(n,`minContains`,e.minContains),Object.hasOwn(e,`maxContains`)&&h(n,`maxContains`,e.maxContains);return Ff(e,n,t,`draft-07`),Lf(e,n,`$id`,`Draft-07`),Pf(n,r,t),n}function Nf(e,t,n,r){if(t===void 0){n!==void 0&&h(e,`items`,r.schema(n,`items`));return}h(e,`items`,r.schemaArray(t,`prefixItems`,`items`)),n!==void 0&&h(e,`additionalItems`,r.schema(n,`items`,`additionalItems`))}function Pf(e,t,n){if(t!==void 0){if(typeof t==`string`&&Object.keys(e).length>0){let r={};n.reference(r,t),If(e,r)}else n.reference(e,t)}}function Ff(e,t,n,r){let i=ri(e.dependentRequired)?e.dependentRequired:void 0,a=ri(e.dependentSchemas)?e.dependentSchemas:void 0;if(i===void 0&&a===void 0)return;let o={},s=new Set([...Object.keys(i??{}),...Object.keys(a??{})]);for(let e of s){let t=i?.[e],s=a?.[e],c=r===`draft-04`&&Array.isArray(t)&&t.length===0;s===void 0?c||h(o,e,t):t===void 0||c?h(o,e,n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e])):h(o,e,{allOf:[n.schemaAt(s,[`dependentSchemas`,e],[`dependencies`,e,`allOf`,`0`]),{required:t}]})}Object.keys(o).length>0&&h(t,`dependencies`,o)}function If(e,t){Array.isArray(e.allOf)?e.allOf.push(t):h(e,`allOf`,[t])}function Lf(e,t,n,r){let i=e.$id,a=e.$anchor;if(a===void 0){i!==void 0&&h(t,n,i);return}(typeof a!=`string`||!Ef.test(a))&&Of(`$anchor`,r,`the anchor is not valid`),Df.test(a)||Of(`$anchor`,r,`the anchor cannot be represented as a plain-name fragment identifier`),i===void 0?h(t,n,`#${a}`):Of(`$anchor`,r,`it cannot be combined with the schema $id`)}function Rf(e){return Qd(zf(e.ast),{schema:e})}var zf=lu(e=>{let t=Wf(e,zf),n=e.context;return t===e||n===void 0?t:cu(t,Bf(n))});function Bf(e){return e.constructorDefault===void 0?e:new Fc(e.isOptional,e.isMutable,void 0,e.annotations)}function Vf(e){if(e.propertySignatures.some(e=>typeof e.name!=`string`))throw new globalThis.Error(`Objects property names must be strings`,{cause:e})}function Hf(e){return t=>{let n=[...t].sort((t,n)=>e(Ou(t))-e(Ou(n)));return n.some((e,n)=>e!==t[n])?n:t}}var Uf=Hf(e=>{switch(e._tag){case`BigInt`:case`Symbol`:case`UniqueSymbol`:return 0;default:return 1}});function Wf(e,t){switch(e._tag){case`Declaration`:{let n=e.annotations?.toCodecJson??e.annotations?.toCodec;if(!Nn(n))return $l(e,[ad]);let r=n(e.typeParameters.map(e=>Qd(Ou(e))));return r===void 0?e:$l(e,[au(r,t)])}case`Unknown`:return $l(e,[ad]);case`ObjectKeyword`:return $l(e,[od]);case`Undefined`:case`Void`:case`Literal`:case`Number`:return e.toCodecJson();case`UniqueSymbol`:case`Symbol`:case`BigInt`:return e.toCodecStringTree();case`Objects`:return Vf(e),e.recur(t,Fu);case`Union`:{let n=Uf(e.types);return n===e.types?e.recur(t):new Ml(n,e.options,e.annotations,e.checks,e.encoding,e.context,e.encodingChecks).recur(t)}case`Arrays`:case`Suspend`:return e.recur(t)}return e}globalThis.RegExp;var Gf=e=>e.replace(/[/\\^$*+?.()|[\]{}]/g,`\\$&`);function Kf(e,t){return t.length>0&&(e+=`\n at ${Gt(t)}`),Error(e)}function qf(e){return`#/$defs/${tf(e)}`}var Jf=new Set([...Zo,Ho,...Go]);function Yf(e,t){if(e===void 0)return;let n={},r=e.title;typeof r==`string`&&(n.title=r);let i=e.description,a=e.expected;typeof i==`string`?n.description=i:t?.generateDescriptions===!0&&typeof a==`string`&&(n.description=a);let o=e.default;rd(o)&&(n.default=o);let s=e.examples;Array.isArray(s)&&rd(s)&&(n.examples=s);let c=e.readOnly;typeof c==`boolean`&&(n.readOnly=c);let l=e.writeOnly;typeof l==`boolean`&&(n.writeOnly=l);let u=e.format;typeof u==`string`&&(n.format=u);let d=e.contentEncoding;typeof d==`string`&&(n.contentEncoding=d);let f=e.contentMediaType;typeof f==`string`&&(n.contentMediaType=f);let p=e.contentSchema;if(rd(p)&&(n.contentSchema=p),t?.includeAnnotationKey!==void 0)for(let[r,i]of Object.entries(e))Jf.has(r)||!t.includeAnnotationKey(r)||rd(i)&&h(n,r,i);return Object.keys(n).length===0?void 0:n}function Xf(e){let t=e.type===`number`||e.type===`integer`?e.type:void 0,n=e;if(t!==void 0&&(n={...e},delete n.type),Array.isArray(n.allOf)){let e=[],r=!1;for(let i of n.allOf){let n=Xf(i);n.type!==void 0&&(r=!0,(t===void 0||n.type===`integer`)&&(t=n.type)),Object.keys(n.schema).length>0&&e.push(n.schema)}if(r){let{allOf:t,...r}=n;n=e.length===0?r:{...r,allOf:e}}}return{type:t,schema:n}}function Zf(e){if(!Array.isArray(e.anyOf)||e.anyOf.length!==2||e.anyOf[0]?.type!==`number`)return!1;let t=e.anyOf[1];return t?.type===`string`&&Array.isArray(t.enum)&&t.enum.length===3&&t.enum.includes(`NaN`)&&t.enum.includes(`Infinity`)&&t.enum.includes(`-Infinity`)}var Qf=`|type|format|pattern|multipleOf|minimum|maximum|exclusiveMinimum|exclusiveMaximum|minLength|maxLength|minItems|maxItems|uniqueItems|minProperties|maxProperties|propertyNames|`;function $f(e,t){return Object.keys(e).every(e=>t.includes(`|${e}|`))}function ep(e,t){return typeof e.$ref!=`string`&&t.every(t=>!Object.hasOwn(e,t))}var tp=`|title|description|default|examples|readOnly|writeOnly|`,np=Qf+tp;function rp(e,t,n){if(Object.keys(e).length===0)return t;let r=Object.keys(t);if(r.length===0)return e;let i=e.type===`number`||e.type===`integer`?e.type:void 0,a=Zf(e);if(i!==void 0||a){let r=Xf(t);if(r.type!==void 0){let t=i===`integer`||r.type===`integer`?`integer`:`number`,o={...e,type:t};a&&delete o.anyOf;let s=Object.keys(r.schema);return s.length===0?o:$f(r.schema,tp)&&ep(o,s)?{...o,...r.schema}:rp(o,r.schema,n)}}if(n&&ep(e,r))return{...e,...t};let o=Array.isArray(t.allOf)&&r.length===1?t.allOf:[t];return Array.isArray(e.allOf)?{...e,allOf:[...e.allOf,...o]}:typeof e.$ref==`string`?{allOf:[e,...o]}:{...e,allOf:o}}function ip(e,t=new Set){return typeof e==`boolean`?e:t.has(e)?!0:(t.add(e),e.every(e=>ip(e,t)))}function ap(e){return Array.isArray(e)}function op(e,t,n,r){let i=new Map,a=new Map,o=new WeakMap,s=new Map,c=new Map,l=Object.keys(n);for(let e of l)m(e,[`references`,e]);let u=Et(e,(e,n)=>re(e,t[n],[]));for(let[e,t]of s.values())if(!ip(e))for(let e of t)Array.isArray(e.oneOf)&&(e.anyOf=e.oneOf,delete e.oneOf);for(let e of l){let t=n[e],r=te(t);if(r===void 0)continue;let o=i.get(e)[0],s=c.get(r),l=s?.find(e=>Dr(i.get(e)[0],o));l===void 0?s===void 0?c.set(r,[e]):s.push(e):a.set(e,l)}let d=Et(u,ee),f={};for(let e of l)a.has(e)||h(f,e,ee(i.get(e)[0]));return{dialect:`draft-2020-12`,schemas:d,definitions:f};function p(e){return Array.isArray(e.oneOf)&&s.get(e.oneOf)?.[1].push(e),e}function m(e,t){if(!Object.hasOwn(n,e))throw Kf(`Invalid reference ${e}`,[...t,`$ref`]);let r=i.get(e);if(r!==void 0)return r;let a=[{},[]];return i.set(e,a),a[0]=re(n[e],[`references`,e],a[1]),a}function ee(e){return uf(e,e=>{let t=nf(e);if(t===void 0){if(/^#(?:\/|%2f)/i.test(e))throw Error(`Invalid JSON Pointer URI fragment ${JSON.stringify(e)}`);return e}if(!t.startsWith(`/$defs/`))return e;let n=t.indexOf(`/`,7),r=a.get(ef(t.slice(7,n<0?void 0:n)));return r===void 0?e:e.replace(/^#(?:\/|%2f).*?(?:\/|%2f).*?(?=\/|%2f|$)/i,qf(r))})}function te(e){if(e._tag===`Reference`)return;let t=e.checks.length===0?e.annotations:e.checks[e.checks.length-1].annotations;return typeof t?.identifier!=`string`&&typeof t?.[`~identifier`]==`string`?t[Ho]:void 0}function ne(e,t,n,i){let a=e.annotations,o=a?.toJsonSchema;if(o!==void 0){let s=o({type:t,schemas:e.representation?.schemas?.map((e,t)=>re(e,[...n,`representation`,`schemas`,t],i))??[]}),c=ap(s);c&&i.push(!1);let l=c?s[0]:s,u=Yf(a,r),d=u===void 0?l:{...l,...u},f=u===void 0?Qf:np;return[d,e._tag===`Filter`&&$f(d,f)&&(u===void 0||$f(u,tp))?!0:void 0]}if(e._tag===`Filter`){i.push(!1);return}let s=e.checks.flatMap((e,r)=>{let a=ne(e,t,[...n,`checks`,r],i);return a===void 0?[]:[a[0]]});if(s.length===0)return;let c=Yf(a,r),l={allOf:s};return[c===void 0?l:{...l,...c}]}function re(e,t,n){if(e._tag===`Reference`)return n.push(m(e.$ref,t)[1]),{$ref:qf(e.$ref)};let i=o.get(e);if(i!==void 0)return n.push(i[1]),i[0];let a=[];n.push(a);let s=ie(e,t,a),c=Yf(e.annotations,r);c!==void 0&&(s={...s,...c});for(let n=0;n<e.checks.length;n++){let r=typeof s.type==`string`&&sp(s.type)?s.type:void 0,i=ne(e.checks[n],r,[...t,`checks`,n],a);i!==void 0&&(s=rp(s,...i))}return o.set(e,[s,a]),p(s)}function ie(e,t,n){switch(e._tag){case`Any`:case`Unknown`:return{};case`ObjectKeyword`:return{anyOf:[{type:`object`},{type:`array`}]};case`Void`:case`Undefined`:case`Null`:return{type:`null`};case`BigInt`:return{type:`string`,allOf:[{pattern:`^-?\\d+$`}]};case`Symbol`:return{type:`string`,allOf:[{pattern:`^Symbol\\(([\\s\\S]*)\\)$`}]};case`UniqueSymbol`:return globalThis.Symbol.keyFor(e.symbol)===void 0?{not:{}}:{type:`string`,enum:[globalThis.String(e.symbol)]};case`Declaration`:return n.push(!1),{};case`Suspend`:return re(e.thunk,[...t,`thunk`],n);case`Never`:return{not:{}};case`String`:return{type:`string`};case`Number`:return{anyOf:[{type:`number`},{type:`string`,enum:[`NaN`,`Infinity`,`-Infinity`]}]};case`Boolean`:return{type:`boolean`};case`Literal`:{let t=e.literal;return typeof t==`bigint`?{type:`string`,enum:[globalThis.String(t)]}:{type:typeof t,enum:[t]}}case`Enum`:{let n=e.enums.map(([e,n],r)=>{if(typeof n==`number`&&!globalThis.Number.isFinite(n))throw Kf(`Invalid numeric enum value ${globalThis.String(n)}`,[...t,`enums`,r,1]);return{type:typeof n,enum:[n],title:e}});return n.length===0?{not:{}}:{anyOf:n}}case`TemplateLiteral`:return{type:`string`,pattern:`^${e.parts.map(lp).join(``)}$`};case`Arrays`:{if(e.rest.length>1)throw Kf(`Invalid schema representation document`,[...t,`rest`]);let i={type:`array`},a=e.elements.length,o=e.elements.map((e,i)=>{e.isOptional&&a--;let o=re(e.type,[...t,`elements`,i,`type`],n),s=Yf(e.annotations,r);return s===void 0?o:p(rp(o,s))});if(o.length>0?(i.prefixItems=o,i.maxItems=e.elements.length,a>0&&(i.minItems=a)):i.items=!1,e.rest.length===1){delete i.maxItems;let r=re(e.rest[0],[...t,`rest`,0],n);Object.keys(r).length>0?i.items=r:delete i.items}return i}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return{not:{type:`null`}};let i={type:`object`},a={},o=[];for(let i=0;i<e.propertySignatures.length;i++){let s=e.propertySignatures[i];if(typeof s.name!=`string`)throw Kf(`Invalid schema representation document`,[...t,`propertySignatures`,i,`name`]);let c=s.name,l=re(s.type,[...t,`propertySignatures`,i,`type`],n),u=Yf(s.annotations,r);h(a,c,u===void 0?l:p(rp(l,u))),s.isOptional||o.push(c)}e.propertySignatures.length>0&&(i.properties=a),o.length>0&&(i.required=o);let s={},c=[],l=[],u=!1;for(let r=0;r<e.indexSignatures.length;r++){let i=e.indexSignatures[r],a=re(i.type,[...t,`indexSignatures`,r,`type`],n);Dr(a,{not:{}})&&(a=!1),l.push(a);let o=ae(i.parameter,[...t,`indexSignatures`,r,`parameter`],new Set);if(o===void 0){u=!0,n.push(!1);continue}if(o.length===0)c.push(a);else for(let e of o){let t=s[e];h(s,e,t===void 0?a:t===!1||a===!1?!1:p(rp(t,a)))}}let d=Object.keys(s).length>0;if(d&&(i.patternProperties=s),u&&r?.onExcessProperty===`error`){let r=[];e.propertySignatures.length>0&&r.push({enum:Object.keys(a)});for(let i=0;i<e.indexSignatures.length;i++)r.push(re(e.indexSignatures[i].parameter,[...t,`indexSignatures`,i,`parameter`],n));i.propertyNames=r.length===1?r[0]:{anyOf:r},i.additionalProperties=l.length===1?l[0]:{anyOf:l},c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})))}else c.length===0?i.additionalProperties=u||r?.onExcessProperty!==`error`:c.length===1&&e.propertySignatures.length===0&&!d?i.additionalProperties=c[0]:c.length>0&&(i.allOf=c.map(e=>({type:`object`,additionalProperties:e})));return typeof i.additionalProperties==`object`&&i.additionalProperties!==null&&Object.keys(i.additionalProperties).length===0&&delete i.additionalProperties,i}case`Union`:{let r=[],i=e.types.map((e,n)=>re(e,[...t,`types`,n],r));if(n.push(r),i.length===0)return{not:{}};let a=e.options?.mode??`anyOf`;if(a===`anyOf`&&i.length>1){let e=cp(i);if(e!==void 0)return e}return a===`oneOf`&&s.set(i,[r,[]]),{[a]:i}}}}function ae(e,t,r){switch(e._tag){case`Reference`:{if(!Object.hasOwn(n,e.$ref))throw Kf(`Invalid reference ${e.$ref}`,[...t,`$ref`]);if(m(e.$ref,t),r.has(e.$ref))return;let i=new Set(r).add(e.$ref);return ae(n[e.$ref],[`references`,e.$ref],i)}case`String`:{if(e.checks.length===0)return[];if(e.checks.length!==1||e.checks[0]._tag!==`Filter`||e.checks[0].annotations?.toJsonSchema===void 0)return;let n=[],r=re(e,t,n);return ip(n)&&r.type===`string`&&typeof r.pattern==`string`&&$f(r,`|type|pattern|title|description|default|examples|readOnly|writeOnly|`)?[r.pattern]:void 0}case`TemplateLiteral`:return e.checks.length===0?[`^${e.parts.map(lp).join(``)}$`]:void 0;case`Union`:{if(e.types.length===0||e.checks.length>0||e.options?.mode===`oneOf`)return;let n=[];for(let i=0;i<e.types.length;i++){let a=ae(e.types[i],[...t,`types`,i],r);if(a===void 0)return;if(a.length===0)return[];n.push(...a)}return n}default:throw Kf(`Invalid schema representation document`,t)}}}function sp(e){return e===`string`||e===`number`||e===`boolean`||e===`array`||e===`object`||e===`null`||e===`integer`}function cp(e){let t,n=[];for(let r of e){if(Object.keys(r).length!==2||r.type===void 0||!Array.isArray(r.enum)||r.enum.length===0)return;if(t===void 0)t=r.type;else if(r.type!==t)return;for(let e of r.enum){if(n.includes(e))return;n.push(e)}}return{type:t,enum:n}}function lp(e){switch(e._tag){case`Literal`:return Gf(globalThis.String(e.literal));case`String`:return Iu;case`Number`:return ol;case`TemplateLiteral`:return e.parts.map(lp).join(``);case`Union`:return`(?:${e.types.map(lp).join(`|`)})`;default:throw Kf(`Invalid schema representation document`,[])}}function up(e,t){let n=op([e.representation],[[`representation`]],e.references,t);return{dialect:n.dialect,schema:n.schemas[0],definitions:n.definitions}}var dp=({identifier:e})=>e;function fp(e){return e===void 0?void 0:{annotations:e}}function pp(e,t){let{references:n,representations:r}=mp([e],t);return{representation:r[0],references:n}}function mp(e,t){let n={},r=new Map,i=new Set,a=new Map,o=new Set;for(let t of e)f(t);let s=t?.referencePolicy??dp;for(let e of a.values())for(let t of e.values()){let e=s({ast:t.ast,occurrences:t.occurrences,identifier:t.identifier});e===void 0?t.isRecursive&&(t.reference=c(`${t.ast._tag}_`,t,``)):t.reference=c(e,t,e===t.identifier||!e.endsWith(`_`)?`_`:``)}return{representations:Et(e,e=>m(e)),references:n};function c(e,t,n=`_`){let i=e,a=0;for(;r.has(i);){if(r.get(i)===t)return i;i=`${e}${n}${++a}`}return r.set(i,t),i}function l(e,t,n){let r=t.fallback;return r===void 0?n===t.identifier?e:nu(e,{identifier:n}):qo(e)===r?e:nu(e,{[Ho]:r})}function u(e,t){if(!Object.hasOwn(n,e)&&!i.has(e)){i.add(e);let r=ee(t);i.delete(e),h(n,e,r)}return{_tag:`Reference`,$ref:e}}function d(e){let t=tu(e),n=Ql(t),r=Ko(t),i=r===void 0?(t===e?void 0:Ko(e))??qo(t):void 0;i!==void 0&&(r=`${i}Encoded`);let o=a.get(n);o===void 0&&(o=new Map,a.set(n,o));let s=o.get(r);return s===void 0&&(s={ast:n,identifier:r,fallback:i,occurrences:0,isRecursive:!1,reference:void 0},o.set(r,s)),s}function f(e){let t=d(e),n=t.ast;if(t.occurrences++,o.has(t)){t.isRecursive=!0;return}if(!(t.occurrences>1)){switch(o.add(t),p(n.checks),n._tag){case`Declaration`:case`Arrays`:case`Objects`:case`Union`:n.recur(e=>(f(e),e));break;case`TemplateLiteral`:n.parts.forEach(f);break;case`Suspend`:f(n.thunk())}o.delete(t)}}function p(e){e?.forEach(e=>{e.annotations?.representation?.schemas?.forEach(e=>f(Du(e))),e._tag===`FilterGroup`&&p(e.checks)})}function m(e){let t=d(e),n=t.ast,r=t.reference;return r===void 0?ee(n):u(r,t.identifier===void 0?n:l(n,t,r))}function ee(e){let t=te(e.checks);switch(e._tag){case`Declaration`:return{_tag:`Declaration`,typeParameters:e.typeParameters.map(e=>m(e)),checks:t,...re(e.annotations)};case`Null`:case`Undefined`:case`Void`:case`Never`:case`Unknown`:case`Any`:case`String`:case`Boolean`:case`Number`:case`BigInt`:case`Symbol`:case`ObjectKeyword`:return{_tag:e._tag,checks:t,...fp(e.annotations)};case`Literal`:return{_tag:`Literal`,literal:e.literal,checks:t,...fp(e.annotations)};case`UniqueSymbol`:return{_tag:`UniqueSymbol`,symbol:e.symbol,checks:t,...fp(e.annotations)};case`Enum`:return{_tag:`Enum`,enums:e.enums,checks:t,...fp(e.annotations)};case`TemplateLiteral`:return{_tag:`TemplateLiteral`,parts:e.parts.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Arrays`:return{_tag:`Arrays`,elements:e.elements.map(e=>{let t=tu(e),n=t.context?.annotations;return{isOptional:Su(t),type:m(e),...fp(n)}}),rest:e.rest.map(e=>m(e)),checks:t,...fp(e.annotations)};case`Objects`:return{_tag:`Objects`,propertySignatures:e.propertySignatures.map(e=>{let t=tu(e.type),n=t.context?.annotations;return{name:e.name,type:m(e.type),isOptional:Su(t),isMutable:Cu(t),...fp(n)}}),indexSignatures:e.indexSignatures.map(e=>({parameter:m(e.parameter),type:m(e.type)})),checks:t,...fp(e.annotations)};case`Union`:return{_tag:`Union`,types:e.types.map(e=>m(e)),...e.options===void 0?{}:{options:e.options},checks:t,...fp(e.annotations)};case`Suspend`:return{_tag:`Suspend`,checks:[],thunk:m(e.thunk()),...fp(e.annotations)}}}function te(e){return e?.map(ne)??[]}function ne(e){switch(e._tag){case`Filter`:return{_tag:`Filter`,aborted:e.aborted,...ie(e.annotations)};case`FilterGroup`:return{_tag:`FilterGroup`,checks:Et(e.checks,ne),...ie(e.annotations)}}}function re(e){if(e===void 0)return;let{representation:t,...n}=e;return{...t===void 0?void 0:{representation:t},...Object.keys(n).length===0?void 0:{annotations:n}}}function ie(e){if(e===void 0)return;let{representation:t,...n}=e,r=t===void 0?void 0:t.schemas===void 0?t:{...t,schemas:t.schemas.map(e=>m(Du(e)))};return{...r===void 0?void 0:{representation:r},...Object.keys(n).length===0?void 0:{annotations:n}}}}function hp(e){return ca(e)?e.value:{issues:[{message:$i(e.cause)}]}}function gp(e,t){let n=Ad(e),r={errors:`all`,...t?.parseOptions},i=Cs(t),a=e=>{let t=new Ct(`sync`),a=dr(u(n(e,r),{onFailure:i,onSuccess:e=>({value:e})}),{scheduler:t});a.currentDispatcher?.flush();let o=a.pollUnsafe();return o?hp(o):new Promise(e=>{a.addObserver(t=>{e(hp(t))})})};if(Object.hasOwn(e,`~standard`)){let t=e;return`validate`in t[`~standard`]||Object.assign(t[`~standard`],{validate:a}),t}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,validate:a}})}function _p(e){return up(pp(zf(e)))}function vp(e,t){let n=_p(e);if(t===`draft-2020-12`){let e=n.schema;return Object.keys(n.definitions).length>0&&(e.$defs=n.definitions),e}if(t===`draft-07`){let e=cf(n),t=e.schema;return Object.keys(e.definitions).length>0&&(t.definitions=e.definitions),t}throw new globalThis.Error(`Unsupported target: ${t}`)}function yp(e){let t={input(t){return vp(e.ast,t.target)},output(t){return vp(Du(e.ast),t.target)}};if(Object.hasOwn(e,`~standard`)){let n=e;return`jsonSchema`in n[`~standard`]||Object.assign(n[`~standard`],{jsonSchema:t}),n}return Object.assign(e,{"~standard":{version:1,vendor:`effect`,jsonSchema:t}})}var bp=qe(e=>xp(e));function xp(e){let t=zo(e)?.toEquivalence;if(t)return t(bc(e)?e.typeParameters.map(xp):[]);switch(e._tag){case`Never`:return cr();case`Declaration`:return Sp(e);case`Null`:case`Undefined`:case`Void`:case`Unknown`:case`Any`:case`String`:case`Number`:case`Boolean`:case`BigInt`:case`Symbol`:case`Literal`:case`UniqueSymbol`:case`ObjectKeyword`:case`Enum`:case`TemplateLiteral`:return Dr;case`Arrays`:{let t=e.elements.map(xp),n=e.rest.map(xp),[r,...i]=n,a=i.length;return Lr((o,s)=>{if(!Array.isArray(o)||!Array.isArray(s))return!1;let c=o.length;if(c!==s.length)return!1;let l=0;for(;l<Math.min(c,e.elements.length);l++)if(!t[l](o[l],s[l]))return!1;if(n.length>0){for(;l<c-a;l++)if(!r(o[l],s[l]))return!1;for(let e=0;e<a;e++)if(!i[e](o[l+e],s[l+e]))return!1}return!0})}case`Objects`:{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Dr;let t=e.propertySignatures.map(e=>xp(e.type)),n=e.indexSignatures.map(e=>xp(e.type));return Lr((r,i)=>{if(!ri(r)||!ri(i))return!1;for(let n=0;n<t.length;n++){let a=e.propertySignatures[n],o=a.name,s=Object.hasOwn(r,o),c=Object.hasOwn(i,o);if(Su(a.type)&&s!==c||s&&c&&!t[n](r[o],i[o]))return!1}for(let t=0;t<n.length;t++){let a=e.indexSignatures[t],o=sl(r,a.parameter),s=sl(i,a.parameter);if(o.length!==s.length)return!1;for(let e=0;e<o.length;e++){let a=o[e];if(!Object.hasOwn(i,a)||!n[t](r[a],i[a]))return!1}}return!0})}case`Union`:{let t=Du(e).types,n=jl(t),r=t.map((t,n)=>[kd(t),xp(e.types[n])]);return Lr((e,t)=>{let i=n(e,!1);for(let n=0;n<i.length;n++){let[a,o]=r[i[n]];if(a(e)&&a(t))return o(e,t)}return!1})}case`Suspend`:{let t;return Lr((n,r)=>(t??=bp(e.thunk()))(n,r))}}}function Sp(e){let t=e.annotations?.representation;if(t===void 0)return Dr;switch(t.id){case`effect/schema/Option`:{let[t]=Cp(e);return(e,n)=>e._tag===n._tag&&(e._tag===`None`||t(e.value,n.value))}case`effect/schema/Result`:{let[t,n]=Cp(e);return(e,r)=>e._tag===r._tag&&(e._tag===`Success`?t(e.success,r.success):n(e.failure,r.failure))}case`effect/schema/CauseReason`:{let[t,n]=Cp(e);return wp(t,n)}case`effect/schema/Cause`:{let[t,n]=Cp(e);return Tp(t,n)}case`effect/schema/Exit`:{let[t,n,r]=Cp(e),i=Tp(n,r);return(e,n)=>e._tag===n._tag&&(e._tag===`Success`?t(e.value,n.value):i(e.cause,n.cause))}case`effect/schema/ReadonlyMap`:{let[t,n]=Cp(e);return Un(t,n)}case`effect/schema/ReadonlySet`:return rn(Cp(e)[0]);case`effect/schema/RegExp`:return(e,t)=>e.source===t.source&&e.flags===t.flags;case`effect/schema/URL`:return(e,t)=>e.toString()===t.toString();default:return Dr}}function Cp(e){return e.typeParameters.map(xp)}function wp(e,t){return(n,r)=>{if(n._tag!==r._tag)return!1;switch(n._tag){case`Fail`:return e(n.error,r.error);case`Die`:return t(n.defect,r.defect);case`Interrupt`:return n.fiberId===r.fiberId}}}function Tp(e,t){let n=r(wp(e,t));return(e,t)=>n(e.reasons,t.reasons)}var Ep=o(2,(e,t)=>({...e,...t})),Dp=e=>e,Op=`~effect/Schema/SchemaError`;function kp(e){return br(e,`~effect/Schema/SchemaError`)&&e[`~effect/Schema/SchemaError`]===`~effect/Schema/SchemaError`}var Ap=Yd;function jp(){return(e,t,n)=>$p(new Rc(e.map(bl),e=>t(e.map(e=>$p(e))),n))}function Mp(e,t){return jp()([],()=>(t,n,r)=>e(t)?x(t):v(new ps(n,t,r)),t)}var Np=class extends zi(`SchemaError`){[Op]=Op;constructor(e){let t=Dt();Ft(0);try{super({issue:e})}finally{Ft(t)}}get message(){return As(this.issue)}toString(){return`SchemaError(${this.message})`}};function Pp(e){return kp(e)}function Fp(e){return pt(e)?Ip(e):Br(e,e=>Kr(()=>qi(e,e=>new Np(e))))}function Ip(e){return ca(e)?e:ia(qi(e.cause,e=>new Np(e)))}function Lp(e,t){let n;for(let r of e.reasons){if(!Hi(r)||!Pp(r.error))throw new globalThis.Error(t,{cause:e});n??=r.error}if(n===void 0)throw new globalThis.Error(t,{cause:e});return n}function Rp(e){let t=Pr(e);if(ca(t))return t.value;throw Lp(t.cause,`Sync adapter can only throw schema errors`)}function zp(e,t){return gp(e,t)}function Bp(e){return yp(e)}var Vp=Dd;function Hp(e,t){let n=Ad(e,t);return(e,t)=>Fp(n(e,t))}function Up(e,t){let n=jd(e,t);return(e,t)=>Ip(n(e,t))}var Wp=Md;function D(e,t){let n=Nd(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Gp=D;function O(e,t){let n=Hp(e,t);return(e,t)=>Rp(n(e,t))}var Kp=O;function qp(e,t){let n=Pd(e,t);return(e,t)=>Fp(n(e,t))}function Jp(e,t){let n=Fd(e,t);return(e,t)=>Ip(n(e,t))}function Yp(e,t){let n=Id(e,t);return(e,t)=>Yt(n(e,t),e=>new Np(e))}var Xp=Yp;function Zp(e,t){let n=qp(e,t);return(e,t)=>Rp(n(e,t))}var Qp=Zp,$p=Qd;function em(e){return br(e,Ap)&&e[Ap]===Ap}var k=Dp(e=>$p(pu(e.ast),{schema:e})),A=Dp(e=>{let t=vm(e);return $p(hu(e.ast),{schema:t})}),tm=Dp(e=>$p(gu(e.ast),{schema:e})),nm=Dp(e=>$p(Du(e.ast),{schema:e})),rm=Dp(e=>$p(Ou(e.ast),{schema:e}));function j(e){let t=$p(new Gc(e),{literal:e,transform(n){return t.pipe(Sm(j(n),{decode:Ws(()=>n),encode:Ws(()=>e)}))}});return t}var im=$p(Uc),am=$p(Wc),om=$p(zc),sm=$p(Hc),M=$p(qc),N=$p(Xc),cm=$p(Zc),lm=$p(Qc),um=$p($c);function dm(e,t){return $p(e,{fields:t,mapFields(e,t){let n=e(this.fields);return dm(yl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function P(e){return dm(yl(e,void 0),e)}function fm(e,t){return $p(xu(e.ast,t.ast),{key:e,value:t})}function pm(e,t){return $p(e,{elements:t,mapElements(e,t){let n=e(this.elements);return pm(xl(n,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function mm(e){return pm(xl(e),e)}var F=Dp(e=>$p(new el(!1,[],[e.ast]),{value:e})),hm=Dp(e=>$p(new el(!1,[e.ast],[e.ast]),{value:e})),gm=Dp(e=>$p(Cl(e.ast),{schema:e}));function _m(e,t){return $p(e,{members:t,mapMembers(e,t){let n=e(this.members);return _m(Sl(n,this.ast.options,t?.unsafePreserveChecks?this.ast.checks:void 0),n)}})}function I(e,t){return _m(Sl(e,t,void 0),e)}function L(e){let t=e.map(j);return $p(Sl(t,void 0,void 0),{literals:e,members:t,mapMembers(e){return I(e(this.members))},pick(e){return L(e)},transform(e){return I(t.map((t,n)=>t.transform(e[n])))}})}var R=Dp(e=>I([e,om])),vm=Dp(e=>I([e,sm]));function ym(e){return $p(new Vl(()=>e().ast))}function z(...e){return t=>t.check(...e)}function bm(e,t){return n=>$p(iu(n.ast,[Gl(e,t)]),{schema:n})}function xm(e){return t=>$p(t.ast,{schema:t,identifier:e})}function Sm(e,t){return n=>$p(yu(n.ast,e.ast,t?lc(t):pc()),{from:n,to:e})}function Cm(){return(e,t)=>jm()(e,{decode:t,encode:Bs})}function wm(e,t){return n=>t?Sm(n,t)(e):Sm(n)(e)}function Tm(e){return t=>$p(vu(t.ast,e),{schema:t})}function Em(e){return Br(e,e=>Kr(()=>qi(e,e=>e.issue)))}function Dm(e,t){let n=t?.encodingStrategy===`omit`?Js():Hs();return t=>A(rm(t)).pipe(Sm(t,{decode:Ys(Em(e)),encode:n}))}function Om(e,t){return n=>nm(n).pipe(Dm(e,t),wm(A(n)))}function km(e){return j(e).pipe(Tm(x(e)))}function Am(e,t){return Mp(t=>t instanceof e,t)}function jm(){return(e,t)=>new Nc(e.ast,lc(t))}var B=Wl,Mm=`^\\S[\\s\\S]*\\S$|^\\S$|^$`;function Nm(e){let t=new globalThis.RegExp(Mm);return B(e=>e.trim()===e,{expected:`a string with no leading or trailing whitespace`,representation:{id:`effect/schema/isTrimmed`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isTrimmed()`}),arbitraryConstraint:{patterns:[{source:Mm,flags:``}]},...e})}function Pm(e,t){let n=e.source,r=e.flags,i=/^[dg]*uy?$/.test(r),a=r===``?`new RegExp(${S(n)})`:`new RegExp(${S(n)}, ${S(r)})`;return Yl(e,{toJsonSchema:()=>i?{pattern:r.endsWith(`y`)?`^(?:${n})`:n}:[{},!0],toCode:()=>({runtime:`Schema.isPattern(${a})`}),...t})}var Fm=e=>e?new globalThis.RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/;function Im(e,t){let n=Fm(e);return Pm(n,{expected:e?`a UUID v${e}`:`a UUID`,representation:{id:`effect/schema/isUUID`,payload:{version:e??null}},toJsonSchema:()=>({pattern:n.source,format:`uuid`}),toCode:()=>({runtime:e===void 0?`Schema.isUUID()`:`Schema.isUUID(${e})`}),...t})}function Lm(e){let t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;return Pm(t,{expected:`a base64 encoded string`,representation:{id:`effect/schema/isBase64`,payload:null},toJsonSchema:()=>({pattern:t.source}),toCode:()=>({runtime:`Schema.isBase64()`}),...e})}function Rm(e,t,n){if(e.length===0)return t.length===0?{}:[{},!0];let r={pattern:new globalThis.RegExp(n).source};return e===t?r:[r,!0]}function zm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`^${Gf(e)}`),i=e.replace(/[\uD800-\uDBFF]$/,``);return B(t=>t.startsWith(e),{expected:`a string starting with ${n}`,representation:{id:`effect/schema/isStartingWith`,payload:{startsWith:e}},toJsonSchema:()=>Rm(i,e,`^${Gf(i)}`),toCode:()=>({runtime:`Schema.isStartingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Bm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(`${Gf(e)}$`),i=e.replace(/^[\uDC00-\uDFFF]/,``);return B(t=>t.endsWith(e),{expected:`a string ending with ${n}`,representation:{id:`effect/schema/isEndingWith`,payload:{endsWith:e}},toJsonSchema:()=>Rm(i,e,`${Gf(i)}$`),toCode:()=>({runtime:`Schema.isEndingWith(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}function Vm(e,t){let n=JSON.stringify(e),r=new globalThis.RegExp(Gf(e)),i=e.replace(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/g,``);return B(t=>t.includes(e),{expected:`a string including ${n}`,representation:{id:`effect/schema/isIncluding`,payload:{includes:e}},toJsonSchema:()=>Rm(i,e,Gf(i)),toCode:()=>({runtime:`Schema.isIncluding(${S(e)})`}),arbitraryConstraint:{patterns:[{source:r.source,flags:r.flags}]},...t})}var Hm=$p(ql),Um=Kl;function Wm(e){let t=ui(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r,exclusiveMinimum:!0},...e.annotate?.(r),...i})}function Gm(e){let t=fn(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value greater than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,minimum:r},...e.annotate?.(r),...i})}function Km(e){let t=ai(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r,exclusiveMaximum:!0},...e.annotate?.(r),...i})}function qm(e){let t=vt(e.order),n=e.formatter??S;return(r,i)=>B(e=>t(e,r),{expected:`a value less than or equal to ${n(r)}`,arbitraryConstraint:{order:e.order,maximum:r},...e.annotate?.(r),...i})}function Jm(e){let t=fn(e.order),n=ui(e.order),r=vt(e.order),i=ai(e.order),a=e.formatter??S;return(o,s)=>{let c=o.exclusiveMinimum?n:t,l=o.exclusiveMaximum?i:r;return B(e=>c(e,o.minimum)&&l(e,o.maximum),{expected:`a value between ${a(o.minimum)}${o.exclusiveMinimum?` (excluded)`:``} and ${a(o.maximum)}${o.exclusiveMaximum?` (excluded)`:``}`,arbitraryConstraint:{order:e.order,minimum:o.minimum,maximum:o.maximum,...o.exclusiveMinimum&&{exclusiveMinimum:!0},...o.exclusiveMaximum&&{exclusiveMaximum:!0}},...e.annotate?.(o),...s})}}function Ym(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${S(e)}`);return e}var Xm=Wm({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThan`,payload:{exclusiveMinimum:Ym(e)}},toJsonSchema:()=>({exclusiveMinimum:e}),toCode:()=>({runtime:`Schema.isGreaterThan(${S(e)})`})})}),V=Gm({order:tn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualTo`,payload:{minimum:Ym(e)}},toJsonSchema:()=>({minimum:e}),toCode:()=>({runtime:`Schema.isGreaterThanOrEqualTo(${S(e)})`})})}),Zm=Km({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThan`,payload:{exclusiveMaximum:Ym(e)}},toJsonSchema:()=>({exclusiveMaximum:e}),toCode:()=>({runtime:`Schema.isLessThan(${S(e)})`})})}),Qm=qm({order:tn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualTo`,payload:{maximum:Ym(e)}},toJsonSchema:()=>({maximum:e}),toCode:()=>({runtime:`Schema.isLessThanOrEqualTo(${S(e)})`})})}),$m=Jm({order:tn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetween`,payload:{minimum:Ym(e.minimum),maximum:Ym(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>({[t?`exclusiveMinimum`:`minimum`]:e.minimum,[n?`exclusiveMaximum`:`maximum`]:e.maximum}),toCode:()=>({runtime:`Schema.isBetween({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function eh(e,t){if(!globalThis.Number.isFinite(e)||e===0)throw new globalThis.RangeError(`Expected a finite non-zero number, got ${globalThis.String(e)}`);return e=globalThis.Math.abs(e),B(t=>Ya(t,e)===0,{expected:`a value that is a multiple of ${e}`,representation:{id:`effect/schema/isMultipleOf`,payload:{divisor:e}},toJsonSchema:()=>({multipleOf:e}),toCode:()=>({runtime:`Schema.isMultipleOf(${S(e)})`}),...t})}function th(e){return B(e=>globalThis.Number.isSafeInteger(e),{expected:`an integer`,representation:{id:`effect/schema/isInt`,payload:null},toJsonSchema:()=>[{type:`integer`},!0],toCode:()=>({runtime:`Schema.isInt()`}),arbitraryConstraint:{number:`integer`},...e})}var H=N.check(th()),nh=H.check(V(0));function rh(e){if(globalThis.Number.isNaN(e.getTime()))throw new globalThis.RangeError(`Expected a valid Date, got ${S(e)}`);return e.toISOString()}function ih(e){return`new Date(${S(e.getTime())})`}var ah=Wm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanDate`,payload:{exclusiveMinimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanDate(${ih(e)})`})})}),oh=Gm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToDate`,payload:{minimum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToDate(${ih(e)})`})})}),sh=Km({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanDate`,payload:{exclusiveMaximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanDate(${ih(e)})`})})}),ch=qm({order:Fn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToDate`,payload:{maximum:rh(e)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToDate(${ih(e)})`})})}),lh=Jm({order:Fn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenDate`,payload:{minimum:rh(e.minimum),maximum:rh(e.maximum),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenDate({ minimum: ${ih(e.minimum)}, maximum: ${ih(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}}),uh=Wm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanBigInt`,payload:{exclusiveMinimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanBigInt(${S(e)})`})})}),dh=Gm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isGreaterThanOrEqualToBigInt`,payload:{minimum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isGreaterThanOrEqualToBigInt(${S(e)})`})})}),fh=Km({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanBigInt`,payload:{exclusiveMaximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanBigInt(${S(e)})`})})}),ph=qm({order:Vn,annotate:e=>({representation:{id:`effect/schema/isLessThanOrEqualToBigInt`,payload:{maximum:e.toString(10)}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isLessThanOrEqualToBigInt(${S(e)})`})})}),mh=Jm({order:Vn,annotate:e=>{let t=e.exclusiveMinimum?!0:void 0,n=e.exclusiveMaximum?!0:void 0;return{representation:{id:`effect/schema/isBetweenBigInt`,payload:{minimum:e.minimum.toString(10),maximum:e.maximum.toString(10),...t&&{exclusiveMinimum:t},...n&&{exclusiveMaximum:n}}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenBigInt({ minimum: ${S(e.minimum)}, maximum: ${S(e.maximum)}, exclusiveMinimum: ${S(t)}, exclusiveMaximum: ${S(n)} })`})}}});function hh(e,t){return e=wh(e),gh(e,Math.ceil(e/2),t)}function gh(e,t,n){return B(t=>t.length>=e,{expected:`a value with a length of at least ${e}`,representation:{id:`effect/schema/isMinLength`,payload:{minLength:e}},toJsonSchema:({type:n})=>n===`string`?e<=1?{minLength:t}:[{minLength:t},!0]:n===`array`?{minItems:e}:n===void 0?[{minLength:t,minItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMinLength(${e})`}),[Vo]:!0,arbitraryConstraint:{minLength:e},...n})}function _h(e){return gh(1,1,e)}function vh(e,t){return e=wh(e),B(t=>t.length<=e,{expected:`a value with a length of at most ${e}`,representation:{id:`effect/schema/isMaxLength`,payload:{maxLength:e}},toJsonSchema:({type:t})=>t===`string`?e===0?{maxLength:e}:[{maxLength:e},!0]:t===`array`?{maxItems:e}:t===void 0?[{maxLength:e,maxItems:e},!0]:[{},!0],toCode:()=>({runtime:`Schema.isMaxLength(${e})`}),[Vo]:!0,arbitraryConstraint:{maxLength:e},...t})}function yh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.length>=e&&n.length<=t,{expected:e===t?`a value with a length of ${e}`:`a value with a length between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenLength`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`string`?t===0||Math.ceil(e/2)>t?{minLength:Math.ceil(e/2),maxLength:t}:[{minLength:Math.ceil(e/2),maxLength:t},!0]:n===`array`?{minItems:e,maxItems:t}:n===void 0?[{minLength:Math.ceil(e/2),maxLength:t,minItems:e,maxItems:t},!0]:[{},!0],toCode:()=>({runtime:`Schema.isBetweenLength(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minLength:e,maxLength:t},...n})}function bh(e,t){return e=wh(e),B(t=>Ch(t,e)>=e,{expected:`a string with at least ${e} code points`,representation:{id:`effect/schema/isMinCodePoints`,payload:{minCodePoints:e}},toJsonSchema:()=>({minLength:e}),toCode:()=>({runtime:`Schema.isMinCodePoints(${e})`}),arbitraryConstraint:{minCodePoints:e},...t})}function xh(e,t){return e=wh(e),B(t=>Ch(t,e+1)<=e,{expected:`a string with at most ${e} code points`,representation:{id:`effect/schema/isMaxCodePoints`,payload:{maxCodePoints:e}},toJsonSchema:()=>({maxLength:e}),toCode:()=>({runtime:`Schema.isMaxCodePoints(${e})`}),arbitraryConstraint:{maxCodePoints:e},...t})}function Sh(e,t,n){return e=wh(e),t=wh(t),B(n=>{let r=Ch(n,t+1);return r>=e&&r<=t},{expected:e===t?`a string with ${e} code points`:`a string with between ${e} and ${t} code points`,representation:{id:`effect/schema/isBetweenCodePoints`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>({allOf:[{minLength:e},{maxLength:t}]}),toCode:()=>({runtime:`Schema.isBetweenCodePoints(${e}, ${t})`}),arbitraryConstraint:{minCodePoints:e,maxCodePoints:t},...n})}function Ch(e,t){if(t===0)return 0;let n=0;for(let r of e)if(++n>=t)break;return n}function wh(e){if(!globalThis.Number.isFinite(e))throw new globalThis.RangeError(`Expected a finite number, got ${e}`);return Math.max(0,Math.floor(e))}function Th(e,t){return e=wh(e),B(t=>t.size>=e,{expected:`a value with a size of at least ${e}`,representation:{id:`effect/schema/isMinSize`,payload:{minSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMinSize(${e})`}),[Vo]:!0,arbitraryConstraint:{minSize:e},...t})}function Eh(e,t){return e=wh(e),B(t=>t.size<=e,{expected:`a value with a size of at most ${e}`,representation:{id:`effect/schema/isMaxSize`,payload:{maxSize:e}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isMaxSize(${e})`}),[Vo]:!0,arbitraryConstraint:{maxSize:e},...t})}function Dh(e,t,n){return e=wh(e),t=wh(t),B(n=>n.size>=e&&n.size<=t,{expected:e===t?`a value with a size of ${e}`:`a value with a size between ${e} and ${t}`,representation:{id:`effect/schema/isBetweenSize`,payload:{minimum:e,maximum:t}},toJsonSchema:()=>[{},!0],toCode:()=>({runtime:`Schema.isBetweenSize(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minSize:e,maxSize:t},...n})}function Oh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length>=e,{expected:`a value with at least ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMinProperties`,payload:{minProperties:e}},toJsonSchema:({type:t})=>t===`object`?{minProperties:e}:[{minProperties:e},!0],toCode:()=>({runtime:`Schema.isMinProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e},...t})}function kh(e,t){return e=wh(e),B(t=>Reflect.ownKeys(t).length<=e,{expected:`a value with at most ${e===1?`1 entry`:`${e} entries`}`,representation:{id:`effect/schema/isMaxProperties`,payload:{maxProperties:e}},toJsonSchema:({type:t})=>t===`object`?{maxProperties:e}:[{maxProperties:e},!0],toCode:()=>({runtime:`Schema.isMaxProperties(${e})`}),[Vo]:!0,arbitraryConstraint:{maxProperties:e},...t})}function Ah(e,t,n){return e=wh(e),t=wh(t),B(n=>Reflect.ownKeys(n).length>=e&&Reflect.ownKeys(n).length<=t,{expected:e===t?`a value with exactly ${e===1?`1 entry`:`${e} entries`}`:`a value with between ${e} and ${t} entries`,representation:{id:`effect/schema/isBetweenProperties`,payload:{minimum:e,maximum:t}},toJsonSchema:({type:n})=>n===`object`?{minProperties:e,maxProperties:t}:[{minProperties:e,maxProperties:t},!0],toCode:()=>({runtime:`Schema.isBetweenProperties(${e}, ${t})`}),[Vo]:!0,arbitraryConstraint:{minProperties:e,maxProperties:t},...n})}var jh=M.check(_h());globalThis.RegExp,globalThis.URL;var Mh=M.annotate({expected:`a string that will be decoded as a Date`}),Nh=Mp(e=>e instanceof globalThis.Date&&!globalThis.Number.isNaN(e.getTime()),{representation:{id:`effect/schema/Date`,payload:null},toCode:()=>({runtime:`Schema.Date`,Type:`globalThis.Date`}),expected:`a valid Date`,toCodecJson:()=>jm()(Mh,gc)}),Ph=M.annotate({expected:`a string that will be decoded as JSON`,contentMediaType:`application/json`});function U(e,t){return Ph.pipe(Sm(e,vc(t)))}globalThis.File,globalThis.FormData,globalThis.URLSearchParams;var Fh=M.annotate({expected:`a string that will be decoded as a number`}).pipe(Sm(N,mc)),Ih=M.check(Nm()),Lh=M.annotate({expected:`a string that will be decoded as a trimmed string`}).pipe(Sm(Ih,dc())),Rh=M.annotate({expected:`a base64 encoded string that will be decoded as Uint8Array`,format:`byte`,contentEncoding:`base64`}),zh=Am(globalThis.Uint8Array,{representation:{id:`effect/schema/Uint8Array`,payload:null},toCode:()=>({runtime:`Schema.Uint8Array`,Type:`globalThis.Uint8Array`}),expected:`Uint8Array`,toCodecJson:()=>jm()(Rh,_c)}),Bh=uc({decode:(e,t)=>Wr(Co(e),{onNone:()=>v(new ms({expected:`a valid UTC DateTime string`},e,t)),onSome:e=>x(wo(e))}),encode:e=>x(To(e))}),Vh=-864e13,Hh=864e13;function Uh(e,t,n){let r=Math.max(t,e?.minimum===void 0?t:e.minimum.epochMilliseconds+ +(e.exclusiveMinimum===!0)),i=Math.min(n,e?.maximum===void 0?n:e.maximum.epochMilliseconds-+(e.exclusiveMaximum===!0));return r<=i?[r,i]:[t,n]}function Wh(e,t){return H.check($m({minimum:e,maximum:t}))}var Gh=Mp(e=>bo(e)&&xo(e),{representation:{id:`effect/schema/DateTimeUtc`,payload:null},toCode:()=>({runtime:`Schema.DateTimeUtc`,Type:`DateTime.Utc`,importDeclarations:[`import * as DateTime from "effect/DateTime"`]}),expected:`DateTime.Utc`,toCodecArbitrary:({constraint:e})=>{let[t,n]=Uh(e,Vh,Hh);return Cm()(Wh(t,n),Ws(So))},toCodecJson:()=>jm()(M,Bh),toFormatter:()=>e=>e.toString()}),Kh=M.annotate({expected:`a string that will be decoded as a DateTime.Utc`}).pipe(Sm(Gh,Bh));function qh(e){return bp(e.ast)}function Jh(e,t){return pp(e.ast,t)}function Yh(e,t){return up(pp(zf(e.ast),t),t)}var Xh=Rf,Zh=$p(nu(id,{toCode:()=>({runtime:`Schema.Json`,Type:`Schema.Json`})})),Qh=fm(M,Zh),$h=e=>crypto.getRandomValues(new Uint8Array(e)),eg=(e,t,n)=>{let r=256-256%e.length;if(r===256){let r=e.length-1;return(i=t)=>{if(!i)return``;let a=``;for(;;){let t=n(i),o=i;for(;o--;)if(a+=e[t[o]&r],a.length>=i)return a}}}let i=Math.ceil(409.6*t/r);return(a=t)=>{if(!a)return``;let o=``;for(;;){let t=n(i),s=i;for(;s--;)if(t[s]<r&&(o+=e[t[s]%e.length],o.length>=a))return o}}},tg=(e,t=21)=>eg(e,t|0,$h),ng=`abcdefghijklmnopqrstuvwxyz0123456789`;function rg(e=21){if(e===1/0||e===-1/0)throw RangeError(`nanoid length must be finite`);return tg(ng,e)()}var ig=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/,ag=/^[a-z][a-z0-9]*(?:_[a-z][a-z0-9]*)*$/,og=w().min(1).max(64).regex(ig),sg=w().min(1).max(64).regex(ig),cg=w().min(1).max(32).regex(ag),lg=Qt({prefix:cg}),ug=Qt({family:og,version:yr(1),kinds:si(sg,lg)}).superRefine((e,t)=>{let n=Object.entries(e.kinds);if(n.length<1||n.length>64){t.addIssue({code:`custom`,message:`Identifier families must declare between one and 64 kinds`});return}let r=new Set;for(let[,e]of n){if(r.has(e.prefix)){t.addIssue({code:`custom`,message:`Identifier kind prefixes must be distinct`});return}r.add(e.prefix)}}),dg=w(),fg=/^[a-z0-9]+$/,pg=new TextEncoder;function mg(e){return e===32||e>=9&&e<=13}function hg(e){let t=0,n=e.length;for(;t<n&&mg(e.charCodeAt(t));)t+=1;for(;n>t&&mg(e.charCodeAt(n-1));)--n;return e.slice(t,n).replace(/[A-Z]/g,e=>String.fromCharCode(e.charCodeAt(0)+32))}function gg(e){let t=`${e.prefix}_`;function n(e){if(!e.startsWith(t))return!1;let n=e.slice(t.length);return n.length===21&&fg.test(n)}let r=_(()=>jr(e=>{let t=dg.safeParse(e);return t.success&&n(t.data)}));function i(i){let a,o=i,s=pg.encode(o).byteLength,c=r.safeParse(o),l=o.startsWith(t)?o.slice(t.length):void 0;if(s<3||s>96)a=`bounds`;else if(l!==void 0&&Array.from(l).length!==21)a=`bounds`;else if(c.success)return{ok:!0,value:c.data};else a=n(hg(o))?`non_canonical`:`grammar`;return{ok:!1,error:{code:`invalid_id`,family:e.family,kind:e.kind,version:1,reason:a}}}let a=_(()=>dg.transform((e,t)=>{let n=i(e);return n.ok?n.value:(t.addIssue({code:`custom`,message:n.error.reason}),ur)}));function o(){let n;try{n=rg(21)}catch{throw e.entropyUnavailable()}return r.parse(`${t}${n}`)}return{family:e.family,kind:e.kind,version:1,generate:o,schema:a,parse:i,is:e=>i(e).ok}}var _g=si(w(),Qt({family:w(),kind:w(),version:yr(1),generate:ct(),schema:t(Ut),parse:ct(),is:ct()})),vg=class extends Error{name=`CairnDefinitionError`;code=`invalid_definition`;constructor(){super(`Cairn identifier family definition is invalid`)}},yg=class extends Error{name=`CairnGenerationError`;code=`entropy_unavailable`;family;kind;version=1;constructor(e){super(`Cairn entropy source is unavailable`),this.family=e.family,this.kind=e.kind}};function bg(e){let t;try{t=ug.safeParse(e)}catch{throw new vg}if(!t.success)throw new vg;let n=t.data,r={};for(let[t,i]of Object.entries(n.kinds)){let a=i.prefix;r[t]=gg({family:e.family,kind:t,prefix:a,entropyUnavailable:()=>new yg({family:n.family,kind:t})})}let i=jr(e=>{let t=_g.safeParse(e);if(!t.success)return!1;let r=Object.entries(t.data);return r.length===Object.keys(n.kinds).length&&r.every(([e,t])=>Object.hasOwn(n.kinds,e)&&t.kind===e&&t.family===n.family)}).safeParse(r);if(!i.success)throw new vg;return i.data}var xg=_(()=>ln({id:w().min(1).max(256),name:w().min(1).max(128),kind:yr(`agent`).optional()})),Sg=_(()=>w().min(1).max(256)),Cg=_(()=>ln({agentId:Sg,sessionId:Sg,commandId:Sg,outcome:Jt([`completed`,`failed`,`interrupted`,`cancelled`,`outcome_unknown`]),diagnostic:w().min(1).max(200).optional(),waitingOnYou:Er(ln({itemId:Sg,kind:w().min(1).max(64),summary:w().min(1).max(200)})).min(1).max(8).optional()})),wg=ln({author:xg.optional(),sourceRequestId:Sg.optional(),delegation:ln({ancestors:Er(Sg).max(8),maxDepth:Mn().int().min(1).max(8),steer:yr(!0).optional(),goal:Qr([w().min(1).max(4e3),yr(!1)]).optional(),reply:Cg.optional()}).optional()});function Tg(e){let t=wg.safeParse(e);return t.success?t.data.author:void 0}var Eg=Symbol.for(`effect/MutableList/Empty`),Dg=()=>({head:void 0,tail:void 0,length:0}),Og=e=>{let t=e.head;t.offset>=1024&&t===e.tail&&t.mutable&&(t.array.length-t.offset)*8<=t.offset&&(e.head=e.tail={array:t.array.slice(t.offset),mutable:!0,offset:0,next:void 0})},kg=()=>({array:[],mutable:!0,offset:0,next:void 0}),Ag=(e,t)=>{e.tail?e.tail.mutable||(e.tail.next=kg(),e.tail=e.tail.next):e.head=e.tail=kg(),e.tail.array.push(t),e.length++},jg=e=>{e.head=e.tail=void 0,e.length=0},Mg=(e,t)=>{if(t=_i(t),t<=0||!e.head)return[];if(t=Math.min(t,e.length),t===e.length&&e.head?.offset===0&&!e.head.next){let t=e.head.array;return jg(e),t}let n=Array(t),r=0,i=e.head;for(;i;){for(;i.offset<i.array.length;)if(n[r++]=i.array[i.offset],i.mutable&&(i.array[i.offset]=void 0),i.offset++,r===t)return e.head=i.offset===i.array.length&&i.next?i.next:i,e.length-=t,e.length===0?jg(e):Og(e),n;i=i.next}return jg(e),n},Ng=e=>Mg(e,e.length),Pg=e=>{if(!e.head)return Eg;let t=e.head.array[e.head.offset];return e.head.mutable&&(e.head.array[e.head.offset]=void 0),e.head.offset++,e.length--,e.head.offset===e.head.array.length?e.head.next?e.head=e.head.next:jg(e):Og(e),t},Fg=`~effect/Queue`,Ig=`~effect/Queue/Enqueue`,Lg=`~effect/Queue/Dequeue`,Rg={_A:He,_E:He},zg={[Fg]:Rg,[Ig]:Rg,[Lg]:Rg,...de,toJSON(){return{_id:`effect/Queue`,state:this.state._tag,size:n_(this)}}},Bg=e=>Se(t=>{let n=Object.create(zg);return n.dispatcher=t.currentDispatcher,n.capacity=e?.capacity??1/0,n.strategy=e?.strategy??`suspend`,n.messages=Dg(),n.scheduleRunning=!1,n.state={_tag:`Open`,takers:new Set,offers:new Set,awaiters:new Set},li(n)}),Vg=e=>Bg({capacity:e}),Hg=e=>Bg({capacity:e,strategy:`dropping`}),Ug=o(2,(e,t)=>ii(()=>Wg(e,t)?i_:e.state._tag===`Open`&&e.strategy===`suspend`?p_(e,t):r_)),Wg=(e,t)=>e.state._tag===`Open`?e.messages.length>=e.capacity?e.strategy===`sliding`?(Pg(e.messages),Ag(e.messages,t),!0):e.capacity<=0&&e.state.takers.size>0&&(Ag(e.messages,t),s_(e),!0):(Ag(e.messages,t),c_(e),!0):!1,Gg=o(2,(e,t)=>Kg(e,c(t))),Kg=o(2,(e,t)=>_t(()=>qg(e,t))),qg=(e,t)=>{if(e.state._tag!==`Open`)return!1;let n=De(t),r=Fe(n,a_);return e.state.offers.size===0&&e.messages.length===0?(y_(e,r),!0):(e.state={...e.state,_tag:`Closing`,exit:r},c_(e),!0)},Jg=e=>qg(e,c(ti())),Yg=e=>_t(()=>Xg(e)),Xg=e=>{if(e.state._tag===`Done`)return!1;jg(e.messages);let t=e.state.offers;y_(e,e.state._tag===`Open`?o_:e.state.exit);for(let e of t)h_(e);return!0},Zg=e=>u_(()=>{if(e.state._tag===`Done`)return Qa(e.state.exit,()=>li([]));let t=v_(e);return __(e),li(t)}),Qg=e=>$g(e,1,1/0),$g=o(3,(e,t,n)=>(t=_i(t),n=_i(n),u_(()=>l_(e,t,n)??Qn(f_(e,()=>d_(e,t)),$g(e,t,n))))),e_=e=>u_(()=>t_(e)??Qn(f_(e,()=>d_(e,1)),e_(e))),t_=e=>{if(e.state._tag===`Done`)return e.state.exit;if(e.messages.length>0){let t=Pg(e.messages);return __(e),ze(t)}if(e.capacity<=0&&e.state.offers.size>0){let t=g_(e.state.offers);return __(e),ze(t)}},n_=e=>e.state._tag===`Done`?0:e.messages.length,r_=ze(!1),i_=ze(!0),a_=he(ti()),o_=p(),s_=e=>{if(e.state._tag!==`Done`&&e.state.takers.size!==0){for(let t of e.state.takers)if(t.ready()&&(e.state.takers.delete(t),t.resume(be),e.messages.length===0))break}},c_=e=>{e.scheduleRunning||e.state._tag===`Done`||e.state.takers.size===0||(e.scheduleRunning=!0,e.dispatcher.scheduleTask(()=>{e.scheduleRunning=!1,s_(e)},0))},l_=(e,t,n)=>{if(e.state._tag===`Done`)return e.state.exit;if(n<=0||t<=0)return ze([]);if(!d_(e,t))return;let r=e.messages.length>0?Mg(e.messages,n):[g_(e.state.offers)];return __(e),ze(r)},u_=jt({op:`QueueTake`,[Ye](e){let t=this[et]();return pi(t)?t[Ye](e):t}}),d_=(e,t)=>e.messages.length>=(e.state._tag===`Closing`?1:Math.min(t,e.capacity||1))||e.capacity<=0&&e.state._tag!==`Done`&&e.state.offers.size>0,f_=(e,t)=>Jn(n=>{if(e.state._tag===`Done`)return n(e.state.exit);if(t())return n(be);let r={ready:t,resume:n};return e.state.takers.add(r),_t(()=>{e.state._tag!==`Done`&&e.state.takers.delete(r)})}),p_=(e,t)=>Jn(n=>Wg(e,t)?n(i_):m_(e,{_tag:`Single`,message:t,resume:n})),m_=(e,t)=>{if(e.state._tag!==`Open`)return h_(t);let n=e.state.offers;return n.add(t),_t(()=>{e.state._tag!==`Done`&&(n.delete(t),e.state._tag===`Closing`&&n.size===0&&e.messages.length===0&&y_(e,e.state.exit))})},h_=e=>e._tag===`Single`?e.resume(r_):e.resume(ze(e.remaining.slice(e.offset))),g_=e=>{let t=e.values().next().value;if(t._tag===`Single`)return e.delete(t),t.resume(i_),t.message;let n=t.remaining[t.offset++];return t.offset===t.remaining.length&&(e.delete(t),t.resume(ze([]))),n},__=e=>{if(e.state._tag===`Done`)return $a(e.state.exit.cause);if(e.state.offers.size===0)return e.state._tag===`Closing`&&e.messages.length===0&&(y_(e,e.state.exit),$a(e.state.exit.cause));for(let t of e.state.offers){let n=e.capacity-e.messages.length;if(n<=0)break;if(t._tag===`Single`)Ag(e.messages,t.message),e.state.offers.delete(t),t.resume(i_);else{for(;t.offset<t.remaining.length;t.offset++){if(n===0)return!1;Ag(e.messages,t.remaining[t.offset]),n--}e.state.offers.delete(t),t.resume(ze([]))}let r=e.state;if(r._tag===`Done`)return $a(r.exit.cause)}return!1},v_=e=>{if(e.messages.length>0){let t=Ng(e.messages);return __(e),t}if(e.state._tag!==`Done`&&e.state.offers.size>0){let t=[g_(e.state.offers)];return __(e),t}return[]},y_=(e,t)=>{if(e.state._tag===`Done`)return;let n=e.state;e.state={_tag:`Done`,exit:t};for(let e of n.takers)e.resume(t);n.takers.clear();for(let e of n.awaiters)e(t);n.awaiters.clear()},b_=wr,x_=Kt,S_=Me,C_=Rr,w_=Vt,T_=Mr,E_=hr,D_=e=>new k_(e),O_=(e,t,n)=>Jn(r=>{if(e.free>=t)return r(n);let i=()=>{e.free<t||(e.waiters.delete(i),r(n))};return e.waiters.add(i),_t(()=>{e.waiters.delete(i)})}),k_=class{waiters=new Set;taken=0;permits;constructor(e){this.permits=e}get free(){return this.permits-this.taken}take(e){let t=ii(()=>this.free<e?O_(this,e,t):(this.taken+=e,li(e)));return t}takeIfAvailable(e){return ii(()=>this.free<e?li(!1):(this.taken+=e,li(!0)))}releaseUnsafe(e,t){return this.taken-=t,this.waiters.size>0&&e.currentDispatcher.scheduleTask(()=>{for(let e of this.waiters){if(this.free<=0)break;e()}},0),this.free}resize(e){return Se(t=>(this.permits=e,this.free<0||this.releaseUnsafe(t,0),ei))}release(e){return Se(t=>li(this.releaseUnsafe(t,e)))}get releaseAll(){return Se(e=>li(this.releaseUnsafe(e,this.taken)))}withPermits(e){return t=>te(n=>{let r=ii(()=>{if(this.free<e){let t=O_(this,e,ei);return Tn(n(t),()=>r)}return this.taken+=e,_n(n(t),()=>{this.releaseUnsafe(Rr(),e)},!0)});return r})}withPermit=this.withPermits(1);withPermitsIfAvailable(e){return t=>te(n=>this.free<e?dn:(this.taken+=e,_n(n(l(t)),()=>{this.releaseUnsafe(Rr(),e)},!0)))}},A_=e=>_t(()=>new k_(e)),j_=`~effect/Channel`,M_=e=>br(e,j_),N_={[j_]:{_Env:He,_InErr:He,_InElem:He,_OutErr:He,_OutElem:He},pipe(){return Le(this,arguments)}},P_=e=>{let t=Object.create(N_);return t.transform=(t,n)=>Br(e(t,n),e=>x(Zt(e))),t},F_=(e,t)=>P_((n,r)=>T(R_(e)(n,r),e=>t(e,r))),I_=e=>P_((t,n)=>e),L_=e=>P_(mt(function*(t,n){let r=ka(n),i=e=>Aa(r,ro(e)),a=yield*_e(e(t,n,r),i);return _e(a,i)})),R_=e=>e.transform,z_=4096,B_=(e,t,n)=>Bg({capacity:n?.bufferSize,strategy:n?.strategy}).pipe(In(t=>Da(e,Yg(t))),In(n=>Ta(t(n),e).pipe(Br(e=>Kg(n,e)),Ze(e)))),V_=(e,t)=>P_((n,r)=>we(B_(r,e,t),Qg)),H_=e=>P_((t,n)=>sr(()=>R_(e())(t,n))),U_=e=>I_(y(()=>{let t=e();return sr(()=>{let e=t.next();return e.done?ta(e.value):x(e.value)})})),W_=(e,t=z_)=>{let n=vi(t);return I_(y(()=>{let t=e(),r=Cn();return sr(()=>{if(r._tag===`Some`)return ta(r.value);let e=[];for(;e.length<n;){let n=t.next();if(n.done){if(e.length===0)return ta(n.value);r=Sr(n.value);break}e.push(n.value)}return x(e)})}))},G_=(e,t=z_)=>W_(()=>e[Symbol.iterator](),t),K_=e=>X_(x(e)),q_=I_(x(ta())),J_=e=>I_(x(v(e))),Y_=e=>I_(Zt(e)),X_=e=>I_(y(()=>{let t=!1;return sr(()=>t?ta():(t=!0,e))})),Z_=e=>I_(x(Qg(e))),Q_=(e,t)=>P_(mt(function*(n,r){let i=e[Symbol.asyncIterator]();return i.return&&(yield*Da(r,qt(()=>i.return()))),T(pn({try:()=>i.next(),catch:t}),e=>e.done?ta(e.value):x(e.value))})),$_=(e,t)=>ev(Q_(e,t),Pt),ev=o(2,(e,t)=>F_(e,e=>y(()=>{let n=0;return we(e,e=>t(e,n++))}))),tv=e=>e===void 0||e!==`unbounded`&&e<=1,nv=o(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?rv(e,t):iv(e,t,n)),rv=(e,t)=>P_((n,r)=>{let i=0;return we(R_(e)(n,r),T(e=>t(e,i++)))}),iv=(e,t,n)=>L_(mt(function*(r,i,a){let o=0,s=yield*R_(e)(r,i),c=n.concurrency===`unbounded`?2**53-1:n.concurrency,l=yield*Vg(0);yield*Da(a,Yg(l));let u=kr(yield*On()),d=w_(a);if(n.unordered){let e=D_(c),n=Xn(e.release(1)),r=kt({onFailure:e=>T(Kg(l,e),n),onSuccess:e=>T(Ug(l,e),n)});yield*e.take(1).pipe(T(()=>s),T(e=>{let n=o++;return d(u(r(sr(()=>t(e,n))))),C}),bt({disableYield:!0}),Br(t=>e.withPermits(c-1)(Kg(l,t))),Ze(a))}else{let e=yield*Vg(c-2);yield*Da(a,Yg(e)),yield*e_(e).pipe(ni,T(e=>Ug(l,e)),bt({disableYield:!0}),Br(e=>Kg(l,e)),Ze(a));let n,r=e=>{e._tag!==`Success`&&(n=e.cause,qg(l,e.cause))};yield*s.pipe(T(i=>{if(n)return Zt(n);let a=o++,s=u(sr(()=>t(i,a)));return d(s),s.addObserver(r),Ug(e,x_(s))}),bt({disableYield:!0}),Br(t=>Ug(e,ia(t)).pipe(g(Kg(e,t)))),Ze(a))}return e_(l)})),av=o(e=>M_(e[0]),(e,t,n)=>tv(n?.concurrency)?ov(e,t):sv(e,t,n)),ov=(e,t)=>P_((n,r)=>we(R_(e)(n,r),e=>{let i,a,o=T(e,e=>(a??=ka(r),cn(R_(t(e))(n,a),e=>(i=s(e),i)))),s=Qa(e=>{if(i=void 0,a.state._tag===`Empty`)return o;let t=Aa(a,sa);return a=void 0,T(t,()=>o)});return sr(()=>i??o)})),sv=(e,t,n)=>e.pipe(ev(t),mv(n)),cv=e=>av(e,He),lv=e=>F_(e,e=>{let t,n=0,r=sr(function r(){if(t===void 0)return T(e,e=>{switch(e.length){case 0:return r();case 1:return x(e[0]);default:return t=e,x(e[n++])}});let i=t[n++];return n>=t.length&&(t=void 0,n=0),x(i)});return x(r)}),uv=o(2,(e,t)=>F_(e,e=>x(T(e,function n(r){let i=[];for(let e=0;e<r.length;e++)t(r[e])&&i.push(r[e]);return At(i)?x(i):T(e,n)})))),dv=o(2,(e,t)=>P_((n,r)=>{let i=ka(r);return we(R_(e)(n,i),e=>{let a=e.pipe(Br(e=>{if($a(e))return Zt(e);let o=i;return i=ka(r),Aa(o,ia(e)).pipe(g(R_(t(e))(n,i)),T(e=>(a=e,e)))}));return sr(()=>a)})})),fv=o(3,(e,t,n)=>dv(e,e=>{let r=t(e);return Ae(r)?Y_(r.failure):n(r.success,e)})),pv=o(2,(e,t)=>fv(e,Yi,e=>t(e))),mv=o(2,(e,{bufferSize:t=16,concurrency:n,switch:r=!1})=>L_(mt(function*(i,a,o){let s=n===`unbounded`?2**53-1:Math.max(1,n),c=r?void 0:D_(s),l=yield*E_(!0),u=new Set,d=yield*Vg(t);yield*Da(o,Yg(d));let f=yield*R_(e)(i,a);return yield*b(function*(){for(;;){let e;c&&(u.size<s?yield*c.take(1):(e=yield*ce(f),yield*Dn(c.take(1),g(x_(e),Nt))));let t=e===void 0?yield*f:yield*x_(e),n=ka(o),r=yield*R_(t)(i,n);for(;u.size>=s;){let e=yi(u);u.delete(e),u.size===0&&(yield*l.open),yield*S_(e)}let a=yield*r.pipe(In(()=>fe),T(e=>Ug(d,e)),bt({disableYield:!0}),_e(mt(function*(e){let t=ro(e),r=yield*Ln(Aa(n,t));if(!u.has(a))return;let i=fa([t,r]);la(i)&&(yield*Kg(d,i.cause)),u.delete(a),c&&(yield*c.release(1)),u.size===0&&(yield*l.open)})),ce);l.closeUnsafe(),u.add(a)}}).pipe(Br(e=>{let t=to(e);return Wt(t)?l.whenOpen(Kg(d,e)):Kg(d,e)}),Ze(o)),e_(d)}))),hv=o(e=>M_(e[0])&&M_(e[1]),(e,t,n)=>L_(mt(function*(r,i,a){let o=n?.haltStrategy??`both`,s=yield*Vg(0);yield*Da(a,Yg(s));let c=0;function l(e,t){if(c++,!$a(t))return Kg(s,t);switch(o){case`both`:return c===2?Kg(s,t):C;case`left`:case`right`:return e===o?Kg(s,t):C;case`either`:return Kg(s,t)}}let u=(e,t,n)=>R_(t)(r,n).pipe(T(e=>e.pipe(T(e=>Ug(s,e)),bt)),_e(t=>Cr(ro(t),e=>Aa(n,e)).pipe(kt({onFailure:t=>l(e,t),onSuccess:()=>l(e,t)}))),Ze(a));return yield*u(`left`,e,ka(a)),yield*u(`right`,t,ka(a)),e_(s)}))),gv=e=>P_((t,n)=>{let r;return x(sr(()=>r||e.pipe(Ta(n),T(e=>R_(e)(t,n)),T(e=>r=e))))}),_v=o(2,(e,t)=>hv(e,I_(x(T(t,ta))),{haltStrategy:`either`})),vv=o(2,(e,t)=>L_((n,r,i)=>Ea(i,t).pipe(g(R_(e)(n,r))))),yv=o(2,(e,t)=>vv(e,e=>t)),bv=(e,t,n)=>sr(()=>{let r=wa(),i=R_(e)(ta(),r);return Qa(T(i,t),n||x).pipe(Ne(e=>Aa(r,e)))}),xv=o(2,(e,t)=>bv(e,e=>bt(T(e,t),{disableYield:!0}))),Sv=mt(function*(e){let t=D_(1),n=yield*On(),r=Ee(n,Sa);return(yield*R_(e)(ta(),r)).pipe(st(n),t.withPermits(1))},Br(e=>x(Zt(e)))),Cv=(e,t)=>R_(e)(ta(),t),wv=`~effect/Stream`,Tv={_R:He,_E:He,_A:He},Ev=function(e){this.channel=e};Ev.prototype={[wv]:Tv,pipe(){return Le(this,arguments)}};var Dv=e=>new Ev(e),Ov=`~effect/Sink`,kv={_A:He,_In:He,_L:He,_E:He,_R:He},Av={[Ov]:kv,pipe(){return Le(this,arguments)}},jv=e=>{let t=Object.create(Av);return t.transform=e,t},Mv=((e,t,n)=>jv(r=>{let i=e(),a;return t(i)?r.pipe(T(e=>{for(let r=0;r<e.length;r++)if(i=n(i,e[r]),!t(i))return r+1<e.length&&(a=e.slice(r+1)),ta();return C}),bt({disableYield:!0}),Qa(()=>x([i,a]))):x([i])}))(Cn,on,(e,t)=>Sr(t)),Nv=()=>Mv,Pv=`~effect/Stream`,Fv=e=>br(e,Pv),Iv=Dv,Lv=e=>Iv(X_(we(e,Pt))),Rv=e=>Bv(x(T(e,()=>ta()))),zv=e=>Bv(x(we(e,Pt))),Bv=e=>Iv(I_(e)),Vv=(e,t)=>Iv(P_((n,r)=>T(Cv(e.channel,r),e=>t(e,r)))),Hv=e=>e.channel,Uv=(e,t)=>Iv(V_(e,t)),Wv=Iv(q_),Gv=e=>Iv(K_(Pt(e))),Kv=e=>Iv(H_(()=>e().channel)),qv=e=>Iv(J_(e)),Jv=e=>Iv(Y_(e)),Yv=(e,t)=>Array.isArray(e)&&t?.chunkSize===void 0?Xv(e):Iv(G_(e,t?.chunkSize)),Xv=e=>At(e)?Iv(K_(e)):Wv,Zv=e=>Iv(Z_(e)),Qv=(e,t)=>Iv($_(e,t)),$v=(e,t)=>Bv(y(()=>{let n=e,r=!1;return sr(function e(){return r?ta():T(t(n),([t,i])=>(on(i)?r=!0:n=i.value,At(t)?x(t):e()))})})),ey=e=>Iv(gv(we(e,Hv))),ty=o(2,(e,t)=>Kv(()=>{let n=0;return Iv(ev(e.channel,Et(e=>t(e,n++))))})),ny=o(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,nv(t,n),ev(Pt),Iv)),ry=e=>e.pipe(ty(n),my(e=>Gv(ve(e)))),iy=o(e=>Fv(e[0]),(e,t,n)=>e.channel.pipe(lv,av(e=>t(e).channel,n),Iv)),ay=o(2,(e,t)=>{let n=ue(t.duration);if(!ae(n))return e;if($e(n))return Kv(t.orElse);let r=Symbol();return py(Kv(()=>{let t=C_().getRef(ja),i=s(n),a,o=T_(!1);return uy(Vv(e,(e,n)=>sr(()=>(a=t.currentTimeMillisUnsafe()+i,o.openUnsafe(),e)).pipe(we(e=>(o.closeUnsafe(),a=void 0,e)),x)),Rv(b(function*(){for(;;)if(yield*o.await,a!==void 0&&(yield*jn(a-t.currentTimeMillisUnsafe()),a!==void 0&&!(a-t.currentTimeMillisUnsafe()>0)))return yield*vr(r)})),{haltStrategy:`left`})}),e=>e.reasons.find(e=>e._tag===`Die`&&e.defect===r)?t.orElse():Jv(e))}),oy=e=>iy(e,Yv),sy=o(2,(e,t)=>{let n=Iv(cv(U_(()=>ly(e,t))));return cy.set(n,[e,t]),n}),cy=new WeakMap;function*ly(e,t){let n=[t,e];for(;n.length>0;){let e=n.pop(),t=cy.get(e);t===void 0?yield e.channel:n.push(t[1],t[0])}}var uy=o(e=>Fv(e[0])&&Fv(e[1]),(e,t,n)=>Iv(hv(Hv(e),Hv(t),n))),dy=o(2,(e,t)=>Iv(uv(Hv(e),t))),fy=o(2,mt(function*(e,t){let n,r=yield*Sv(e.channel),i=Br(r,e=>(n=e,Zt(e))),[a,o]=yield*Gr(e=>t.transform(i,e)),s=n?Wv:Bv(x(r));return o&&(s=sy(Xv(o),s)),[a,s]})),py=o(2,(e,t)=>e.channel.pipe(dv(e=>t(e).channel),Iv)),my=o(2,(e,t)=>Iv(pv(e.channel,e=>t(e).channel))),hy=o(e=>Fv(e[0]),(e,t,n)=>Vv(e,(e,r)=>y(()=>{let r=0,i=!1;return T(sr(()=>i?ta():e),e=>{let a=e.findIndex(e=>t(e,r++));if(a>=0){i=!0;let t=e.slice(0,n?.excludeLast?a:a+1);return At(t)?x(t):ta()}return x(e)})}))),gy=o(2,(e,t)=>Iv(_v(e.channel,t))),_y=o(2,(e,t)=>Iv(yv(e.channel,t))),vy=o(2,(e,t)=>xv(e.channel,e=>{let n=0;return wt({while:()=>n<e.length,body:()=>t(e[n++]),step:Qe})})),yy=o(2,(e,t)=>({[Symbol.asyncIterator](){let n=sn(t),r=kr(t),i=wa(),a,o,s,c,l=e=>{if(c)return c;let t=s;return c=n(Ar(g(t?S_(t):C,Aa(i,e)),{done:!0,value:void 0})),c},u=async e=>{try{await l(e)}catch(e){await n(nt(`Suppressed error while closing Stream async iterator`,e))}};return{async next(){if(c)return c;if(o){let e=o.next();if(!e.done)return e;o=void 0}let t=r(a??T(Cv(e.channel,i),e=>(a=e,e)));s=t;let d=await n(b_(t));if(s===t&&(s=void 0),ca(d))return o=d.value[Symbol.iterator](),o.next();if($a(d.cause))return l(sa);if(c&&Ki(d.cause))return c;throw await u(d),Ji(d.cause)},return(){return l(sa)},async throw(e){throw await u(oa(e)),e}}}})),by=e=>yy(e,me()),xy=15e3,Sy=45e3,Cy=jh.check(vh(256)),wy=H.check(V(0)),Ty=P({agentId:Cy,sessionId:Cy,name:Cy}),Ey=P({by:Ty,reason:L([`escalated`,`sender_archived`,`sender_absent`]),note:k(M.check(vh(1e3)))}),Dy=P({id:Cy,kind:jh.check(vh(64)),summary:jh.check(vh(200)),since:wy,expiresAt:A(wy),inbox:A(j(!1)),waitingOn:A(Ty),escalated:A(Ey)}),Oy=Dy.mapFields(e=>({...e,extensionId:Cy})),ky=4096,Ay=F(Oy).check(vh(64)),jy=M.pipe(z(hh(1)),z(vh(256))),My=[`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Ny=P({providerId:jy,modelId:jy,reasoning:A(L(My))}),Py=O(R(Ny)),Fy=O(U(R(Ny))),Iy=L([`contract`,`extensions`,`instructions`,`model`,`runtime`,`store`,`tools`]),Ly=L([`closed`,`conflict`,`incompatible`,`invalid`,`rejected`,`unavailable`,`state_reset_required`,`storage_pressure`,`archived`]),Ry=M.pipe(z(hh(1)),z(vh(256))),zy=P({_tag:j(`ShiitakeError`),boundary:Iy,cause:Ly,message:M,requestId:k(Ry)}),W=class extends Error{boundary;requestId;_tag=`ShiitakeError`;cause;underlying;constructor(e,t,n,r,i){super(n),this.boundary=e,this.requestId=r,this.name=`ShiitakeError`,this.cause=t,this.underlying=i}},By=new TextEncoder;function Vy(e){return M.check(hh(1),vh(e),B(t=>By.encode(t).byteLength<=e))}var Hy=/\p{Cs}/u,Uy=Vy(256).check(B(e=>!Hy.test(e))),Wy=Vy(262144),Gy=P({type:j(`image`),data:M.check(hh(1),vh(1048576),Lm()),mimeType:M.check(B(e=>[`image/png`,`image/jpeg`,`image/gif`,`image/webp`].includes(e)))}),Ky=F(Gy).check(hh(1),vh(8)),qy=L([`steer`,`followUp`]),Jy=Uy,Yy=D(P({commandId:Uy,timeoutMs:H.check(V(0),Qm(3e4))}),{onExcessProperty:`error`});D(P({commandId:Uy,timeoutMs:Fh.check(th(),$m({minimum:0,maximum:3e4}))}),{onExcessProperty:`error`});var Xy=D(Vy(512)),Zy=P({requestId:Uy}),Qy=P({delivery:qy,requestId:Uy,type:j(`prompt`),text:M.check(vh(262144),B(e=>By.encode(e).byteLength<=262144)),images:k(Ky)}).check(B(e=>(e.text.length>0||(e.images?.length??0)>0)&&By.encode(e.text).byteLength+(e.images??[]).reduce((e,t)=>e+t.data.length,0)<=1048576)),$y=P({type:j(`abort`)}),eb=P({commandId:Uy,onlyIfPending:A(cm),type:j(`cancel`)}),tb=P({type:j(`operator`),requestId:Uy,author:L([`operator`,`party`]),text:Wy}),nb=P({type:j(`branch`),entryId:Uy}),rb=P({type:j(`fork`),entryId:Uy}),ib=M.check(hh(1),vh(4096)),ab=P({type:j(`compact`),requestId:Uy,instructions:k(ib)}),ob=I([Qy,ab]),sb=M.check(B(e=>e.length>0&&e.trim()===e&&!/\p{Cc}/u.test(e)&&Array.from(e).length<=120)),cb=I([Qy,$y,eb,nb,rb,tb,ab,P({type:j(`title`),title:R(sb)})]),lb=P({command:cb}),ub=P({includeSandboxFailures:A(cm),limit:A(H.check($m({minimum:1,maximum:200}))),before:A(Vy(512))}),db=P({includeSandboxFailures:A(j(`true`)),limit:A(Fh.check(th(),$m({minimum:1,maximum:200}))),before:A(Vy(512))}),fb=P({includeSandboxFailures:A(cm),after:A(M)}),pb=P({includeSandboxFailures:A(j(`true`)),mode:A(j(`subscribe`)),after:A(M),limit:A(Fh.check(th(),$m({minimum:1,maximum:200})))}),mb={onExcessProperty:`error`},hb=D(Jy,mb),gb=D(Zy,mb),_b=D(ob,mb);D(Uy);var vb=D(cb,mb);D(lb,mb);var yb=D(I([ub,sm]),mb);D(db,mb);var bb=D(fb,mb);D(pb,mb);function xb(e){let t=hb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session id is invalid`);return t.success}function Sb(e){let t=Xy(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session cursor is invalid`);return t.success}function Cb(e){let t=gb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Session creation request is invalid`);return t.success.requestId}function wb(e){let t=yb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Read options are invalid`);let n=t.success??{},r={limit:n.limit??200};return n.before!==void 0&&(r={...r,before:n.before}),n.includeSandboxFailures!==void 0&&(r={...r,includeSandboxFailures:n.includeSandboxFailures}),Object.freeze(r)}function Tb(e){let t=bb(e);if(t._tag===`Failure`)throw new W(`contract`,`invalid`,`Subscribe options are invalid`);let n={};return t.success.after!==void 0&&(n={...n,after:t.success.after}),t.success.includeSandboxFailures!==void 0&&(n={...n,includeSandboxFailures:t.success.includeSandboxFailures}),Object.freeze(n)}function Eb(e,t){if(Ae(e))throw new W(`contract`,`invalid`,t);return e.success}var Db=bn();function Ob(e){return e!==null&&!Array.isArray(e)&&typeof e==`object`}function kb(e,t){if(e===t)return 0;let n=Math.min(e.length,t.length);for(let r=0;r<n;r+=1){let n=e.charCodeAt(r)-t.charCodeAt(r);if(n!==0)return n}return e.length-t.length}function Ab(e){return e.replace(/([a-z])([A-Z])/g,`$1 $2`).replace(/([A-Z]+)([A-Z][a-z])/g,`$1 $2`).replace(/[_./:-]/g,` `).toLowerCase().trim()}function jb(e){return e.split(/[^a-zA-Z0-9]+/).filter(e=>e.length>0)}var Mb=new Set([`the`,`a`,`an`,`for`,`to`,`of`,`that`,`this`,`with`,`in`,`on`]);function Nb(e){return Mb.has(e)}function Pb(e){let t=[],n=n=>{n!==e&&n.length>=3&&!t.includes(n)&&t.push(n)};return e.endsWith(`ing`)&&e.length>4&&n(e.slice(0,-3)),e.endsWith(`ed`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`ation`)&&e.length>6&&n(`${e.slice(0,-3)}e`),e.endsWith(`ies`)&&e.length>4&&(n(e.slice(0,-3)),n(`${e.slice(0,-3)}y`)),e.endsWith(`es`)&&e.length>3&&n(e.slice(0,-2)),e.endsWith(`s`)&&!e.endsWith(`ss`)&&e.length>3&&n(e.slice(0,-1)),t}function Fb(e){let t=8997,n=33826,r=40164,i=52210;for(let a=0;a<e.length;a+=1){let o=t^e.charCodeAt(a),s=o*435,c=n*435+(s>>>16),l=r*435+(c>>>16)+(o<<8),u=i*435+(l>>>16)+(n<<8);t=s&65535,n=c&65535,r=l&65535,i=u&65535}return i.toString(16).padStart(4,`0`)+r.toString(16).padStart(4,`0`)+n.toString(16).padStart(4,`0`)+t.toString(16).padStart(4,`0`)}function Ib(e){return e.slice(e.indexOf(`.`)+1)}function Lb(e){return e.slice(0,e.indexOf(`.`))}var Rb=/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/,zb=1e3,Bb=221;function Vb(e,t){if(t>16)return t;if(Array.isArray(e)){let n=t;for(let r of e)n=Math.max(n,Vb(r,t+1));return n}if(!Ob(e))return t;let n=t;for(let r of Object.values(e))n=Math.max(n,Vb(r,t+1));return n}var Hb=_(()=>si(w(),bn()).superRefine((e,t)=>{Object.keys(e).length>100&&t.addIssue({code:`custom`,message:`Sample exceeds the entry bound`}),JSON.stringify(e).length>4e3&&t.addIssue({code:`custom`,message:`Sample exceeds the byte bound`}),Vb(e,0)>16&&t.addIssue({code:`custom`,message:`Sample exceeds the depth bound`})})),Ub=_(()=>Qt({query:w().max(200),maxResults:Mn().int().min(1).max(50).default(50)})),Wb=_(()=>Qt({path:w().max(160),detail:Jt([`index`,`full`]).default(`full`),methods:Er(w().max(80)).max(50).optional()})),Gb=Qt({cursor:w().max(400).optional(),limit:Mn().int().min(1).max(50).default(50),namespace:w().min(1).max(160).regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/).optional()}),Kb=_(()=>Qt({path:w().max(160),capabilityNotes:w().max(500).optional()})),qb=Qt({path:w().max(160),description:w().max(1e3).optional(),score:Mn().min(0).max(Bb),matchReason:w().max(500).optional(),sample:Hb.optional(),capabilityNotes:w().max(500).optional(),peers:Er(Kb).max(1e3).optional()}),Jb=_(()=>Qt({results:Er(qb).max(50),total:Mn().int().min(0).max(zb),truncated:pr(),topScore:Mn().min(0).max(Bb),margin:Mn().min(0).max(Bb),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)})),Yb=Qt({results:Er(qb).max(50),total:Mn().int().min(0).max(zb),nextCursor:w().max(400).nullable(),catalogStamp:w().length(16).regex(/^[0-9a-f]{16}$/)}),Xb=_(()=>Qt({path:w().max(160),description:w().max(1e3).optional(),types:w().max(2e4),inputSchema:bn().refine(e=>JSON.stringify(e).length<=2e4&&Vb(e,0)<=16,`Input schema exceeds the description bounds`).optional(),kind:Jt([`module`,`operation`]),usage:w().max(300).optional()}));_(()=>Qt({code:Jt([`empty_query`,`empty_catalog`,`unknown_target`,`duplicate_operation`,`invalid_input`]),message:w().max(1e3)}));var Zb=_(()=>Qt({"~standard":Qt({jsonSchema:Qt({input:t(Function),output:t(Function)})})})),Qb=_(()=>jr(e=>Zb.safeParse(e).success,`Expected a Standard JSON Schema`)),$b=_(()=>Qt({path:w().min(3).max(160).regex(Rb),description:w().max(1e3).optional(),input:Qb,output:Qb.optional(),capabilityNotes:w().max(500).optional(),instructions:w().max(1e3).optional()})),ex=_(()=>Qt({revision:w().min(1).max(160),operations:Er($b).max(zb)})),tx=class extends Error{code;failure;constructor(e,t,n){let r=t.slice(0,1e3);super(r,n),this.name=`ForageError`,this.code=e,this.failure={code:e,message:r}}},nx=Qr([ir({$ref:w().optional(),$defs:si(w(),xt()).optional(),definitions:si(w(),xt()).optional(),const:xt().optional(),enum:Er(xt()).optional(),oneOf:Er(xt()).optional(),anyOf:Er(xt()).optional(),allOf:Er(xt()).optional(),type:Qr([w(),Er(w())]).optional(),properties:si(w(),xt()).optional(),additionalProperties:xt().optional(),required:Er(w()).optional(),prefixItems:Er(xt()).optional(),items:xt().optional(),examples:Er(xt()).optional(),default:xt().optional()}),pr()]),rx=new WeakMap;function ix(e,t){let n=rx.get(e),r=n?.[t];if(r!==void 0)return r;let i;try{i=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`})}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}sx(i);let a={raw:i};return n===void 0&&(n={},rx.set(e,n)),n[t]=a,a}function ax(e,t){return ix(e,t).raw}function ox(e,t){let n=ix(e,t);try{return n.text??=JSON.stringify(n.raw),n.text}catch{throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`)}}function sx(e){let t=nx.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`);return t.data}var cx=256,lx=/^#\/(?:\$defs|definitions)\/([^/]+)$/u;function ux(e,t,n){let r=lx.exec(e)?.[1];if(r===void 0||n.expanding.has(r))return`unknown`;let i=n.definitions[r];if(i===void 0)return`unknown`;if(n.budget.expansions+=1,n.budget.expansions>cx)throw new tx(`invalid_input`,`Schema references expand more than ${String(cx)} times; flatten its shared definitions`);return fx(sx(i),t,{definitions:n.definitions,expanding:new Set([...n.expanding,r]),budget:n.budget})}function dx(e,t){if(e===!0||e===!1)return!1;if(e.$ref!==void 0){let n=lx.exec(e.$ref)?.[1],r=n===void 0||t.expanding.has(n)?void 0:t.definitions[n];return n!==void 0&&r!==void 0&&dx(sx(r),{definitions:t.definitions,expanding:new Set([...t.expanding,n]),budget:t.budget})}return e.const===void 0?e.enum!==void 0&&e.enum.length>1||e.oneOf!==void 0&&e.oneOf.length>1||e.anyOf!==void 0&&e.anyOf.length>1:!1}function fx(e,t,n){if(t>12||e===!0||e===!1)return`unknown`;let r=n??{definitions:{...e.definitions,...e.$defs},expanding:new Set,budget:{expansions:0}};if(e.$ref)return ux(e.$ref,t,r);if(e.const!==void 0)return JSON.stringify(e.const);if(e.enum)return e.enum.map(e=>JSON.stringify(e)).join(` | `);if(e.oneOf)return e.oneOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.anyOf)return e.anyOf.map(e=>fx(sx(e),t+1,r)).join(` | `);if(e.allOf)return e.allOf.map(e=>{let n=sx(e),i=fx(n,t+1,r);return dx(n,r)?`(${i})`:i}).join(` & `);if(e.type===`object`||e.properties){let n=Object.entries(e.properties??{}).sort(([e],[t])=>kb(e,t));if(n.length===0){let n=e.additionalProperties;return n===!1?`Record<string, never>`:n&&n!==!0?`Record<string, ${fx(sx(n),t+1,r)}>`:`Record<string, unknown>`}let i=new Set(e.required??[]);return`{
|
|
4
4
|
${n.map(([e,n])=>{let a=fx(sx(n),t+1,r),o=i.has(e)?``:`?`,s=/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e);return`${` `.repeat(t+1)}${s}${o}: ${a};`}).join(`
|
|
5
5
|
`)}
|
|
6
6
|
${` `.repeat(t)}}`}if(e.type===`array`){let n=e.items;if(e.prefixItems&&e.prefixItems.length>0){let i=e.prefixItems.map(e=>fx(sx(e),t+1,r));return n!==void 0&&n!==!0&&!Array.isArray(n)&&i.push(`...${fx(sx(n),t+1,r)}[]`),`[${i.join(`, `)}]`}if(n!==void 0&&Array.isArray(n))return`[${n.map(e=>fx(sx(e),t+1,r)).join(`, `)}][]`;let i=n===void 0||sx(n),a=fx(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 px(e,t=`input`){return fx(sx(ax(e,t)),0)}function mx(e){return e.replace(/[^A-Za-z0-9_$]/g,`_`)}function hx(e,t,n){let r=`(input: ${t}) => Promise<${n}>`;for(let t of e.split(`.`).reverse())r=`{ [${JSON.stringify(t)}]: ${r} }`;return r}function gx(e){return e.length===0?``:`export declare const env: ${e.map(e=>e.indexEnvironment).join(` & `)};`}function _x(e){let t=e.map(e=>e.types).join(`
|
|
7
7
|
|
|
8
8
|
`);return e.length===0?t:`${t}\nexport declare const env: ${e.map(e=>e.environment).join(` & `)};`}var vx=new WeakMap;function yx(e){let t=vx.get(e);if(t!==void 0)return t;let n=mx(e.path.replace(/\./g,`$`)),r=px(e.input,`input`),i=e.output?px(e.output,`output`):`unknown`,a=Object.freeze({indexEnvironment:hx(e.path,r,i),environment:hx(e.path,`${n}_Input`,`${n}_Output`),types:`export type ${n}_Input = ${r};\nexport type ${n}_Output = ${i};`});return vx.set(e,a),a}function bx(e){let t=sx(ax(e,`input`));if(t===!0||t===!1||!t.properties)return;let n={},r=!1,i=Object.entries(t.properties).sort(([e],[t])=>kb(e,t));for(let[e,t]of i){let i=sx(t);if(i===!0||i===!1)continue;let a=i.examples;if(a&&a.length>0){let t=Db.safeParse(a[0]);t.success&&(n[e]=t.data,r=!0)}else if(i.default!==void 0){let t=Db.safeParse(i.default);t.success&&(n[e]=t.data,r=!0)}}return r?n:void 0}function xx(e){return e&&e.length>0?e:void 0}function Sx(e){let t=Xb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Description output exceeded its bounds`);return t.data}function Cx(e,t){let n=e.find(e=>e.path===t.path);if(n){let e=`env.${n.path}`,t=Db.safeParse(ax(n.input,`input`));if(!t.success)throw new tx(`invalid_input`,`Schema cannot be projected to JSON Schema`);let r={path:n.path,description:xx(n.description),types:_x([yx(n)]),kind:`operation`,inputSchema:t.data,usage:`await ${e}({ ... })`};if(r.types.length>2e4)throw new tx(`invalid_input`,`Operation description exceeds the bounded output`);return Sx(r)}let r=`${t.path}.`,i=e.filter(e=>e.path.startsWith(r)).sort((e,t)=>kb(e.path,t.path));if(i.length===0)throw new tx(`unknown_target`,`Unknown target: ${t.path}`);let a=i[0];if(!a)throw new tx(`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?gx(i.map(yx)):_x((o.length>0?o:i).map(yx)),s.length>2e4)throw new tx(`invalid_input`,`Description types exceed the bounded output`);return Sx({path:t.path,description:xx(a.instructions),types:s,kind:`module`})}function wx(e){let t=ox(e.input,`input`),n=e.output?ox(e.output,`output`):``;return Object.freeze({...e,fingerprint:Fb(t+`
|
|
9
9
|
`+n),inputBytes:t.length,outputBytes:n.length,sample:bx(e.input)})}var Tx={exact:14,startsWith:9,phrase:6,token:4,prefix:2,substring:2,includes:1},Ex={path:12,namespace:8,method:10,description:5},Dx=25,Ox=10,kx=8,Ax=20,jx=Math.max(Dx,Ox)+kx+Ax,Mx=1+Math.max(...Object.values(Tx))*Math.max(...Object.values(Ex))+jx;function Nx(e){return Fb([...e].sort((e,t)=>kb(e.path,t.path)).map(e=>JSON.stringify([e.path,e.description??null,e.capabilityNotes??null,e.instructions??null,e.fingerprint])).join(`
|
|
10
|
-
`))}function Px(e,t){if(e===t)return`exact`;if(e.startsWith(t))return`startsWith`;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`\\b${n}\\b`).test(e))return`phrase`;let r=jb(e);return r.some(e=>e===t)?`token`:r.some(e=>e.startsWith(t))?`prefix`:r.some(e=>e.includes(t))?`substring`:e.includes(t)?`includes`:`none`}function Fx(e,t,n){let r=Ab(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...Pb(e)],s=`none`;for(let e of n){let t=Px(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=Tx[s]*Ex[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function Ix(e,t){let n=Ab(e);return[t,...Pb(t)].some(e=>n.includes(e))}function Lx(e){let t=[];for(let[n,r]of e){if(r.level===`none`)continue;let e=r.matchedTokens.slice(0,4).map(e=>e.slice(0,20));t.push(`${n}:${r.level}(${e.join(` `)})`)}return t.length>0?t.join(`; `):void 0}function Rx(e){let t=Jb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Search output exceeded its bounds`);return t.data}function zx(e){return[Ib(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Bx(e){return Rx({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Vx(e,t,n){let r=Lb(e.path),i=Ib(e.path),a=e.description??``,o=[e.path,r,i,a],s=Fx(e.path,`path`,t),c=Fx(r,`namespace`,t),l=Fx(i,`method`,t),u=Fx(a,`description`,t),d=n.filter(e=>o.some(t=>Ix(t,e))).length;if(d===0)return;let f=d/n.length,p=Math.max(s.score,c.score,l.score,u.score);if(p===0)return;let m=d===n.length?Dx:f*Ox,ee=n[0];ee&&o.some(e=>Ix(e,ee))&&(m+=kx),(s.level===`exact`||l.level===`exact`)&&(m+=Ax);let te={path:e.path,score:d+(p+m)/Mx};a&&(te.description=a);let ne=Lx([[`method`,l],[`description`,u],[`path`,s],[`namespace`,c]]);return ne&&(te.matchReason=ne),e.sample&&(te.sample=e.sample),e.capabilityNotes&&(te.capabilityNotes=e.capabilityNotes),{result:te,cluster:zx(e),pathScore:s.score}}function Hx(e){let t=new Map;for(let n of e){let e=t.get(n.cluster)??[];e.push(n),t.set(n.cluster,e)}let n=[];for(let e of t.values()){let t=[...e].sort((e,t)=>t.pathScore-e.pathScore||t.result.score-e.result.score||kb(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>kb(e.result.path,t.result.path));for(let e of a){let t={path:e.result.path};e.result.capabilityNotes&&(t.capabilityNotes=e.result.capabilityNotes),i.push(t)}let o={...r.result,score:Math.max(...t.map(e=>e.result.score))};i.length>0&&(o.peers=i),n.push(o)}return n.sort((e,t)=>t.score-e.score||kb(e.path,t.path))}function Ux(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return Rx({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function Wx(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=jb(Ab(t)),o=a.filter(e=>!Nb(e));if(o.length===0)return Bx(r);let s=[];for(let t of e){let e=Vx(t,a,o);e&&s.push(e)}return Ux(Hx(s),i,r)}var Gx=cn({catalogStamp:Yb.shape.catalogStamp,namespace:Gb.shape.namespace.unwrap().nullable(),after:qb.shape.path});function Kx(e,t,n){let r=Gb.safeParse(n);if(!r.success)throw new tx(`invalid_input`,r.error.message);let i=r.data,a=i.namespace??null,o=e.filter(e=>a===null||e.path.startsWith(`${a}.`)).sort((e,t)=>kb(Lb(e.path),Lb(t.path))||kb(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=Gx.parse(JSON.parse(i.cursor))}catch(e){throw new tx(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new tx(`invalid_input`,`Listing cursor belongs to a different catalog or namespace`);let n=o.findIndex(t=>t.path===e.after);if(n<0)throw new tx(`invalid_input`,`Listing cursor operation is absent from this view`);s=n+1}let c=o.slice(s,s+i.limit),l=c.at(-1);return Yb.parse({results:c,total:o.length,catalogStamp:t,nextCursor:s+c.length<o.length&&l!==void 0?JSON.stringify({catalogStamp:t,namespace:a,after:l.path}):null})}var qx=1e6;function Jx(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=Jx(i,a):Tn(i)&&(a=Jx(Object.values(i),a)),n=Math.max(n,a),n>16)return n}return n}function Yx(e){let t=ex.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new tx(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>kb(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new tx(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),ox(e.input,`input`).length>2e4||Jx(Object.values(ax(e.input,`input`)))>16)throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?ox(e.output,`output`).length:0)>2e4||e.output!==void 0&&Jx(Object.values(ax(e.output,`output`)))>16)throw new tx(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=wx(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||Vb(n,0)>16))throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if(i.push(t),a+=t.inputBytes+t.outputBytes+o+e.path.length,a+=e.description?.length??0,a+=e.capabilityNotes?.length??0,a+=e.instructions?.length??0,a>qx)throw new tx(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function Xx(e){let t=Yx(e),n=Object.freeze(t.operations),r=Nx(n),i=n.map(e=>{let t={path:e.path,score:0};return e.description!==void 0&&(t.description=e.description),e.sample!==void 0&&(t.sample=e.sample),e.capabilityNotes!==void 0&&(t.capabilityNotes=e.capabilityNotes),t});return Object.freeze({revision:t.revision,search:e=>{let t=Ub.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new tx(`empty_query`,`Search query must not be empty`);return Wx(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Wb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new tx(`empty_query`,`Description target must not be empty`);return Cx(n,t.data)},list:e=>Kx(i,r,e),stamp:()=>r})}var Zx=_(()=>w().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),Qx=_(()=>si(w(),yn()));_(()=>Qr([Qx,fr()]));var $x=_(()=>Zt({tool:Zx,title:w().max(120),description:w().max(1e3),input:si(w(),yn()),output:si(w(),yn()),call:si(w(),yn())}).catchall(yn()));_(()=>mn(`kind`,[cn({kind:vr(`unindexed`)}),cn({kind:vr(`ready`),tools:Tr($x).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var eS=Object.freeze({replay:`safe`,path:`forage.search`,description:`Search operation names and descriptions with short keywords, such as read or shell. If no results match, retry with one relevant keyword. Describe known operation paths directly with forage.describe.`,input:Ub,output:Jb}),tS=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Wb,output:Xb}),nS=Object.freeze({replay:`safe`,path:`forage.list`,description:`List every available operation in stable namespace then path order (UTF-16 code units). Use limit (1–50) and nextCursor to page without duplicates, optionally filtering by exact namespace. total counts all operations in that filter; summaries match search, with score 0 and no peer merging. A cursor belongs to this catalog and filter; describe paths before calling them.`,input:Gb,output:Yb});Object.freeze({createCatalog:Xx,forageSearchDefinition:eS,forageDescribeDefinition:tS,forageListDefinition:nS});var rS=`invalid_definition`,iS=`runtime_closed`,aS=`source_failure`,G=class extends Error{code=rS;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},oS=class extends Error{code=iS;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},sS=class extends Error{sourceId;phase;code=aS;constructor(e,t){super(e===void 0?`Capability source ${t} failed`:`Capability source ${t} failed: ${e}`),this.sourceId=e,this.phase=t,this.name=`MyceliumSourceError`}},cS=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},lS=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},uS=class extends zi(`SourceInvalid`){},dS=class extends zi(`GuestThrew`){},fS=class extends zi(`DeadlineExceeded`){},pS=class extends zi(`SandboxBusy`){code=`sandbox-busy`},mS=class extends zi(`Cancelled`){},hS=class extends zi(`DispatchLost`){},gS=class extends zi(`SandboxCrashed`){},_S=class extends zi(`BadResponse`){},vS=class extends zi(`ResultTooLarge`){},yS=class extends zi(`ResultNotJson`){},bS=class extends zi(`CapabilityFailed`){constructor(e){super(e),this.message=CS(this)}},xS=class extends zi(`Unknown`){};function SS(e,t){switch(e._tag){case`SourceInvalid`:return new uS({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new dS({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new fS({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new pS({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new mS({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new hS({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new gS({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new _S({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new vS({size:e.size,ref:t});case`ResultNotJson`:return new yS({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new bS({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new xS({rawCause:e.rawCause,ref:t})}}function CS(e,t=!0){let n;switch(e._tag){case`SourceInvalid`:n=`SyntaxError in submitted source line ${String(e.line)}, column ${String(e.column)}: ${e.excerpt.slice(0,160)}. Nothing ran. Fix quote/heredoc nesting: quote multi-line shell text with a JavaScript template literal or \\n escapes; escape backticks and \${ inside it. If a nested heredoc is hard to quote, write the script with Files, then execute it.`;break;case`GuestThrew`:{let t=e.name.slice(0,80),r=e.message.slice(0,512),i=e.missingVariable;n=`${t}: ${r}${i===void 0?``:`. Declare ${i} with const or let before assigning it; this sandbox does not create implicit globals. Each execute call has its own variables.`}`;break}case`DeadlineExceeded`:n=`execute hit its ${String(e.limitMs)} ms deadline after ${String(e.elapsedMs)} ms; split the work or persist progress${e.acknowledged===!1?`; sandbox did not acknowledge cancellation`:``}`;break;case`SandboxBusy`:n=`sandbox-busy: all ${String(e.capacity)} sandbox slots remained occupied after waiting ${String(e.waitedMs)} ms. Nothing ran; retry this call after capacity becomes available.`;break;case`Cancelled`:n=e.acknowledged===!1?`Sandbox did not acknowledge cancellation`:`Execution was cancelled`;break;case`DispatchLost`:n=`The sandbox lost contact after ${String(e.elapsedMs)} ms; a running command may still be running; check its effects before retrying`;break;case`SandboxCrashed`:n=`The sandbox process stopped before answering; check effects before retrying`;break;case`BadResponse`:n=`The sandbox returned an unreadable result; retry once, split the call if it recurs`;break;case`ResultTooLarge`:n=`Sandbox result exceeds 256 KiB`;break;case`ResultNotJson`:n=`Sandbox returned non-JSON data`;break;case`CapabilityFailed`:n=e.cause.message.slice(0,1e3);break;case`Unknown`:return`The sandbox failed for an unrecognized reason${t?` (ref ${e.ref??`unavailable`})`:``}`}return!t||e.ref===void 0?n:`${n} (ref ${e.ref})`}var wS=_(()=>Qr([e(uS),e(dS),e(fS),e(pS),e(mS),e(hS),e(gS),e(_S),e(vS),e(yS),e(bS),e(xS)])),TS=_(()=>bt().pipe(Qr([e(Error).transform(e=>({kind:`error`,value:e})),Cn().transform(e=>({kind:`null`,value:e})),Ir().transform(e=>({kind:`undefined`,value:e})),w().transform(e=>({kind:`string`,value:e})),fr().transform(e=>({kind:`boolean`,value:e})),Qr([Mn(),Rn(),vr(1/0),vr(-1/0)]).transform(e=>({kind:`number`,value:e})),tn().transform(e=>({kind:`bigint`,value:e})),mt().transform(e=>({kind:`symbol`,value:e})),e(Function).transform(e=>({kind:`function`,value:e})),Tr(bt()).transform(e=>({kind:`array`,value:e})),Qr([e(Object),si(w(),bt())]).transform(e=>({kind:`object`,value:e})),bt().transform(()=>({kind:`opaque`}))])));function ES(e){return wS.safeParse(e).success}function DS(e){let t=wS.safeParse(e);return t.success?t.data:new xS({rawCause:e})}function OS(e){let t=TS.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}_(()=>yn().optional());function kS(e){return AS(e,new Set)}function AS(e,t){let n=TS.parse(e);switch(n.kind){case`null`:case`undefined`:return null;case`string`:case`boolean`:return n.value;case`number`:return Number.isFinite(n.value)?n.value:String(n.value);case`bigint`:case`symbol`:return String(n.value);case`function`:return{kind:`function`,name:n.value.name};case`opaque`:return{kind:`opaque`};case`error`:case`array`:case`object`:{let r=n.value;if(t.has(e))return{kind:`circular_reference`};t.add(e);try{if(n.kind===`array`)return n.value.map(e=>AS(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,AS(n,t)]));if(n.kind===`error`){let r=n.value;e.name=r.name,e.message=r.message,r.stack!==void 0&&(e.stack=r.stack),r.cause!==void 0&&(e.cause=AS(r.cause,t)),r instanceof AggregateError&&(e.errors=AS(r.errors,t))}return e}finally{t.delete(e)}}}}var jS=_(()=>Zt({name:vr(`ReferenceError`),message:w().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));_(()=>Qr([jS,Zt({name:w(),message:w()})]).and(Zt({transportMessage:w().max(512).optional()})));var MS=_(()=>cn({v:vr(1),kind:vr(`sandbox_failure`),tag:qt([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:w().min(1).max(32),message:w().max(160)})),NS=D(U(am)),PS=_(()=>w().transform((e,t)=>{let n=NS(e);return ke(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),Or):n.success})).pipe(MS);cn({error:PS}),_(()=>bt().pipe(Qr([vr(`Execution timed out`).transform(()=>({kind:`deadline`})),bt().transform(e=>({kind:`bad_response`,rawCause:e}))])));var FS=cn({sandboxCapacity:Vr().positive().optional(),admissionWaitMs:Vr().min(1).max(9e5).optional()});function IS(e,t){let n=FS.safeParse(e??{}),r=Vr().positive().safeParse(t??2);if(!n.success||!r.success)throw new G(`Sandbox admission policy is invalid`);return Object.freeze({capacity:n.data.sandboxCapacity??Math.min(32,Math.max(2,r.data)),waitMs:n.data.admissionWaitMs??18e4})}var LS=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],RS=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],zS=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,BS=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,VS={3:`abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile`,5:`class enum extends super const export import`,6:`enum`,strict:`implements interface let package private protected public static yield`,strictBind:`eval arguments`},HS=`break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this`,US={5:HS,"5module":HS+` export import`,6:HS+` const class extends export import super`},WS=/^in(stanceof)?$/,GS=RegExp(`[`+BS+`]`),KS=RegExp(`[`+BS+zS+`]`);function qS(e,t){for(var n=65536,r=0;r<t.length;r+=2){if(n+=t[r],n>e)return!1;if(n+=t[r+1],n>=e)return!0}return!1}function JS(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&GS.test(String.fromCharCode(e)):t!==!1&&qS(e,RS)}function YS(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&KS.test(String.fromCharCode(e)):t===!1?!1:qS(e,RS)||qS(e,LS)}var K=function(e,t){t===void 0&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function XS(e,t){return new K(e,{beforeExpr:!0,binop:t})}var ZS={beforeExpr:!0},QS={startsExpr:!0},$S={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,$S[e]=new K(e,t)}var J={num:new K(`num`,QS),regexp:new K(`regexp`,QS),string:new K(`string`,QS),name:new K(`name`,QS),privateId:new K(`privateId`,QS),eof:new K(`eof`),bracketL:new K(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new K(`]`),braceL:new K(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new K(`}`),parenL:new K(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new K(`)`),comma:new K(`,`,ZS),semi:new K(`;`,ZS),colon:new K(`:`,ZS),dot:new K(`.`),question:new K(`?`,ZS),questionDot:new K(`?.`),arrow:new K(`=>`,ZS),template:new K(`template`),invalidTemplate:new K(`invalidTemplate`),ellipsis:new K(`...`,ZS),backQuote:new K("`",QS),dollarBraceL:new K("${",{beforeExpr:!0,startsExpr:!0}),eq:new K(`=`,{beforeExpr:!0,isAssign:!0}),assign:new K(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new K(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new K(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:XS(`||`,1),logicalAND:XS(`&&`,2),bitwiseOR:XS(`|`,3),bitwiseXOR:XS(`^`,4),bitwiseAND:XS(`&`,5),equality:XS(`==/!=/===/!==`,6),relational:XS(`</>/<=/>=`,7),bitShift:XS(`<</>>/>>>`,8),plusMin:new K(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:XS(`%`,10),star:XS(`*`,10),slash:XS(`/`,10),starstar:new K(`**`,{beforeExpr:!0}),coalesce:XS(`??`,1),_break:q(`break`),_case:q(`case`,ZS),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,ZS),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,ZS),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,QS),_if:q(`if`),_return:q(`return`,ZS),_switch:q(`switch`),_throw:q(`throw`,ZS),_try:q(`try`),_var:q(`var`),_const:q(`const`),_while:q(`while`,{isLoop:!0}),_with:q(`with`),_new:q(`new`,{beforeExpr:!0,startsExpr:!0}),_this:q(`this`,QS),_super:q(`super`,QS),_class:q(`class`,QS),_extends:q(`extends`,ZS),_export:q(`export`),_import:q(`import`,QS),_null:q(`null`,QS),_true:q(`true`,QS),_false:q(`false`,QS),_in:q(`in`,{beforeExpr:!0,binop:7}),_instanceof:q(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:q(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:q(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:q(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},eC=/\r\n?|\n|\u2028|\u2029/,tC=new RegExp(eC.source,`g`);function nC(e){return e===10||e===13||e===8232||e===8233}function rC(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(nC(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var iC=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,aC=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,oC=Object.prototype,sC=oC.hasOwnProperty,cC=oC.toString,lC=Object.hasOwn||(function(e,t){return sC.call(e,t)}),uC=Array.isArray||(function(e){return cC.call(e)===`[object Array]`}),dC=Object.create(null);function fC(e){return dC[e]||(dC[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function pC(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var mC=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,hC=function(e,t){this.line=e,this.column=t};hC.prototype.offset=function(e){return new hC(this.line,this.column+e)};var gC=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function _C(e,t){for(var n=1,r=0;;){var i=rC(e,r,t);if(i<0)return new hC(n,t-r);++n,r=i}}var vC={ecmaVersion:null,sourceType:`script`,strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,startLocation:null,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},yC=!1;function bC(e){var t={};for(var n in vC)t[n]=e&&lC(e,n)?e[n]:vC[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!yC&&typeof console==`object`&&console.warn&&(yC=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
10
|
+
`))}function Px(e,t){if(e===t)return`exact`;if(e.startsWith(t))return`startsWith`;let n=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`\\b${n}\\b`).test(e))return`phrase`;let r=jb(e);return r.some(e=>e===t)?`token`:r.some(e=>e.startsWith(t))?`prefix`:r.some(e=>e.includes(t))?`substring`:e.includes(t)?`includes`:`none`}function Fx(e,t,n){let r=Ab(e),i=`none`,a=0,o=[];for(let e of n){let n=[e,...Pb(e)],s=`none`;for(let e of n){let t=Px(r,e);if(t!==`none`){s=t;break}}if(s===`none`)continue;let c=Tx[s]*Ex[t];o.includes(e)||o.push(e),c>a&&(i=s,a=c)}return{level:i,score:a,matchedTokens:o}}function Ix(e,t){let n=Ab(e);return[t,...Pb(t)].some(e=>n.includes(e))}function Lx(e){let t=[];for(let[n,r]of e){if(r.level===`none`)continue;let e=r.matchedTokens.slice(0,4).map(e=>e.slice(0,20));t.push(`${n}:${r.level}(${e.join(` `)})`)}return t.length>0?t.join(`; `):void 0}function Rx(e){let t=Jb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,`Search output exceeded its bounds`);return t.data}function zx(e){return[Ib(e.path),(e.description??``).trim().toLowerCase().replace(/\s+/g,` `),e.fingerprint].join(`\0`)}function Bx(e){return Rx({results:[],total:0,truncated:!1,topScore:0,margin:0,catalogStamp:e})}function Vx(e,t,n){let r=Lb(e.path),i=Ib(e.path),a=e.description??``,o=[e.path,r,i,a],s=Fx(e.path,`path`,t),c=Fx(r,`namespace`,t),l=Fx(i,`method`,t),u=Fx(a,`description`,t),d=n.filter(e=>o.some(t=>Ix(t,e))).length;if(d===0)return;let f=d/n.length,p=Math.max(s.score,c.score,l.score,u.score);if(p===0)return;let m=d===n.length?Dx:f*Ox,ee=n[0];ee&&o.some(e=>Ix(e,ee))&&(m+=kx),(s.level===`exact`||l.level===`exact`)&&(m+=Ax);let te={path:e.path,score:d+(p+m)/Mx};a&&(te.description=a);let ne=Lx([[`method`,l],[`description`,u],[`path`,s],[`namespace`,c]]);return ne&&(te.matchReason=ne),e.sample&&(te.sample=e.sample),e.capabilityNotes&&(te.capabilityNotes=e.capabilityNotes),{result:te,cluster:zx(e),pathScore:s.score}}function Hx(e){let t=new Map;for(let n of e){let e=t.get(n.cluster)??[];e.push(n),t.set(n.cluster,e)}let n=[];for(let e of t.values()){let t=[...e].sort((e,t)=>t.pathScore-e.pathScore||t.result.score-e.result.score||kb(e.result.path,t.result.path)),r=t[0];if(!r)continue;let i=[],a=t.slice(1).sort((e,t)=>kb(e.result.path,t.result.path));for(let e of a){let t={path:e.result.path};e.result.capabilityNotes&&(t.capabilityNotes=e.result.capabilityNotes),i.push(t)}let o={...r.result,score:Math.max(...t.map(e=>e.result.score))};i.length>0&&(o.peers=i),n.push(o)}return n.sort((e,t)=>t.score-e.score||kb(e.path,t.path))}function Ux(e,t,n){let r=e.slice(0,t),i=r[0],a=r[1];return Rx({results:r,total:e.length,truncated:e.length>t,topScore:i?.score??0,margin:i&&a?i.score-a.score:0,catalogStamp:n})}function Wx(e,t,n=50,r){let i=Math.min(50,Math.max(1,Math.floor(n))),a=jb(Ab(t)),o=a.filter(e=>!Nb(e));if(o.length===0)return Bx(r);let s=[];for(let t of e){let e=Vx(t,a,o);e&&s.push(e)}return Ux(Hx(s),i,r)}var Gx=ln({catalogStamp:Yb.shape.catalogStamp,namespace:Gb.shape.namespace.unwrap().nullable(),after:qb.shape.path});function Kx(e,t,n){let r=Gb.safeParse(n);if(!r.success)throw new tx(`invalid_input`,r.error.message);let i=r.data,a=i.namespace??null,o=e.filter(e=>a===null||e.path.startsWith(`${a}.`)).sort((e,t)=>kb(Lb(e.path),Lb(t.path))||kb(e.path,t.path)),s=0;if(i.cursor!==void 0){let e;try{e=Gx.parse(JSON.parse(i.cursor))}catch(e){throw new tx(`invalid_input`,`Invalid listing cursor`,{cause:e})}if(e.catalogStamp!==t||e.namespace!==a)throw new tx(`invalid_input`,`Listing cursor belongs to a different catalog or namespace`);let n=o.findIndex(t=>t.path===e.after);if(n<0)throw new tx(`invalid_input`,`Listing cursor operation is absent from this view`);s=n+1}let c=o.slice(s,s+i.limit),l=c.at(-1);return Yb.parse({results:c,total:o.length,catalogStamp:t,nextCursor:s+c.length<o.length&&l!==void 0?JSON.stringify({catalogStamp:t,namespace:a,after:l.path}):null})}var qx=1e6;function Jx(t,n=0){if(n>=16)return t.length===0?n:n+1;let r=n;for(let i=t.length-1;i>=0;--i){let a=t[i],o=n+1;if(Array.isArray(a)?o=Jx(a,o):e(a)&&(o=Jx(Object.values(a),o)),r=Math.max(r,o),r>16)return r}return r}function Yx(e){let t=ex.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.operations.length===0)throw new tx(`empty_catalog`,`Catalog must contain an operation`);let n=[...t.data.operations].sort((e,t)=>kb(e.path,t.path)),r=new Set,i=[],a=0;for(let e of n){if(r.has(e.path))throw new tx(`duplicate_operation`,`Duplicate operation path: ${e.path}`);if(r.add(e.path),ox(e.input,`input`).length>2e4||Jx(Object.values(ax(e.input,`input`)))>16)throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if((e.output?ox(e.output,`output`).length:0)>2e4||e.output!==void 0&&Jx(Object.values(ax(e.output,`output`)))>16)throw new tx(`invalid_input`,`Schema output projection is too large: ${e.path}`);let t=wx(e),n=t.sample,o=n===void 0?0:JSON.stringify(n).length;if(n!==void 0&&(Object.keys(n).length>100||o>4e3||Vb(n,0)>16))throw new tx(`invalid_input`,`Schema projection is too large: ${e.path}`);if(i.push(t),a+=t.inputBytes+t.outputBytes+o+e.path.length,a+=e.description?.length??0,a+=e.capabilityNotes?.length??0,a+=e.instructions?.length??0,a>qx)throw new tx(`invalid_input`,`Catalog metadata exceeds the bounded projection`)}return{revision:t.data.revision,operations:i}}function Xx(e){let t=Yx(e),n=Object.freeze(t.operations),r=Nx(n),i=n.map(e=>{let t={path:e.path,score:0};return e.description!==void 0&&(t.description=e.description),e.sample!==void 0&&(t.sample=e.sample),e.capabilityNotes!==void 0&&(t.capabilityNotes=e.capabilityNotes),t});return Object.freeze({revision:t.revision,search:e=>{let t=Ub.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.query.trim().length===0)throw new tx(`empty_query`,`Search query must not be empty`);return Wx(n,t.data.query,t.data.maxResults,r)},describe:e=>{let t=Wb.safeParse(e);if(!t.success)throw new tx(`invalid_input`,t.error.message);if(t.data.path.trim().length===0)throw new tx(`empty_query`,`Description target must not be empty`);return Cx(n,t.data)},list:e=>Kx(i,r,e),stamp:()=>r})}var Zx=_(()=>w().min(1).max(75).regex(/^[A-Za-z][A-Za-z0-9_]*$/)),Qx=_(()=>si(w(),bn()));_(()=>Qr([Qx,pr()]));var $x=_(()=>Qt({tool:Zx,title:w().max(120),description:w().max(1e3),input:si(w(),bn()),output:si(w(),bn()),call:si(w(),bn())}).catchall(bn()));_(()=>hn(`kind`,[ln({kind:yr(`unindexed`)}),ln({kind:yr(`ready`),tools:Er($x).max(100).refine(e=>new Set(e.map(e=>e.tool)).size===e.length,{message:`Tool family names must be distinct`})})]));var eS=Object.freeze({replay:`safe`,path:`forage.search`,description:`Search operation names and descriptions with short keywords, such as read or shell. If no results match, retry with one relevant keyword. Describe known operation paths directly with forage.describe.`,input:Ub,output:Jb}),tS=Object.freeze({replay:`safe`,path:`forage.describe`,description:`Describe a capability`,input:Wb,output:Xb}),nS=Object.freeze({replay:`safe`,path:`forage.list`,description:`List every available operation in stable namespace then path order (UTF-16 code units). Use limit (1–50) and nextCursor to page without duplicates, optionally filtering by exact namespace. total counts all operations in that filter; summaries match search, with score 0 and no peer merging. A cursor belongs to this catalog and filter; describe paths before calling them.`,input:Gb,output:Yb});Object.freeze({createCatalog:Xx,forageSearchDefinition:eS,forageDescribeDefinition:tS,forageListDefinition:nS});var rS=`invalid_definition`,iS=`runtime_closed`,aS=`source_failure`,G=class extends Error{code=rS;constructor(e){super(e),this.name=`MyceliumDefinitionError`}},oS=class extends Error{code=iS;constructor(e=`Mycelium runtime is closed`){super(e),this.name=`MyceliumClosedError`}},sS=class extends Error{sourceId;phase;code=aS;constructor(e,t){super(e===void 0?`Capability source ${t} failed`:`Capability source ${t} failed: ${e}`),this.sourceId=e,this.phase=t,this.name=`MyceliumSourceError`}},cS=class extends Error{issues;constructor(e){super(`Invalid operation input`),this.issues=e,this.name=`InvalidOperationInput`}},lS=class extends Error{issues;constructor(e){super(`Operation output failed its declared schema`),this.issues=e,this.name=`InvalidOperationOutput`}},uS=class extends zi(`SourceInvalid`){},dS=class extends zi(`GuestThrew`){},fS=class extends zi(`DeadlineExceeded`){},pS=class extends zi(`SandboxBusy`){code=`sandbox-busy`},mS=class extends zi(`Cancelled`){},hS=class extends zi(`DispatchLost`){},gS=class extends zi(`SandboxCrashed`){},_S=class extends zi(`BadResponse`){},vS=class extends zi(`ResultTooLarge`){},yS=class extends zi(`ResultNotJson`){},bS=class extends zi(`CapabilityFailed`){constructor(e){super(e),this.message=CS(this)}},xS=class extends zi(`Unknown`){};function SS(e,t){switch(e._tag){case`SourceInvalid`:return new uS({line:e.line,column:e.column,excerpt:e.excerpt,ref:t});case`GuestThrew`:return new dS({name:e.name,message:e.message,missingVariable:e.missingVariable,transportMessage:e.transportMessage,ref:t});case`DeadlineExceeded`:return new fS({limitMs:e.limitMs,elapsedMs:e.elapsedMs,acknowledged:e.acknowledged,ref:t});case`SandboxBusy`:return new pS({capacity:e.capacity,waitedMs:e.waitedMs,ref:t});case`Cancelled`:return new mS({by:e.by,acknowledged:e.acknowledged,ref:t});case`DispatchLost`:return new hS({elapsedMs:e.elapsedMs,transport:e.transport,errno:e.errno,rawCause:e.rawCause,ref:t});case`SandboxCrashed`:return new gS({exit:e.exit,errno:e.errno,rawCause:e.rawCause,ref:t});case`BadResponse`:return new _S({reason:e.reason,rawCause:e.rawCause,ref:t});case`ResultTooLarge`:return new vS({size:e.size,ref:t});case`ResultNotJson`:return new yS({kind:e.kind,rawCause:e.rawCause,ref:t});case`CapabilityFailed`:return new bS({namespace:e.namespace,operation:e.operation,cause:e.cause,rawCause:e.rawCause,ref:t});case`Unknown`:return new xS({rawCause:e.rawCause,ref:t})}}function CS(e,t=!0){let n;switch(e._tag){case`SourceInvalid`:n=`SyntaxError in submitted source line ${String(e.line)}, column ${String(e.column)}: ${e.excerpt.slice(0,160)}. Nothing ran. Fix quote/heredoc nesting: quote multi-line shell text with a JavaScript template literal or \\n escapes; escape backticks and \${ inside it. If a nested heredoc is hard to quote, write the script with Files, then execute it.`;break;case`GuestThrew`:{let t=e.name.slice(0,80),r=e.message.slice(0,512),i=e.missingVariable;n=`${t}: ${r}${i===void 0?``:`. Declare ${i} with const or let before assigning it; this sandbox does not create implicit globals. Each execute call has its own variables.`}`;break}case`DeadlineExceeded`:n=`execute hit its ${String(e.limitMs)} ms deadline after ${String(e.elapsedMs)} ms; split the work or persist progress${e.acknowledged===!1?`; sandbox did not acknowledge cancellation`:``}`;break;case`SandboxBusy`:n=`sandbox-busy: all ${String(e.capacity)} sandbox slots remained occupied after waiting ${String(e.waitedMs)} ms. Nothing ran; retry this call after capacity becomes available.`;break;case`Cancelled`:n=e.acknowledged===!1?`Sandbox did not acknowledge cancellation`:`Execution was cancelled`;break;case`DispatchLost`:n=`The sandbox lost contact after ${String(e.elapsedMs)} ms; a running command may still be running; check its effects before retrying`;break;case`SandboxCrashed`:n=`The sandbox process stopped before answering; check effects before retrying`;break;case`BadResponse`:n=`The sandbox returned an unreadable result; retry once, split the call if it recurs`;break;case`ResultTooLarge`:n=`Sandbox result exceeds 256 KiB`;break;case`ResultNotJson`:n=`Sandbox returned non-JSON data`;break;case`CapabilityFailed`:n=e.cause.message.slice(0,1e3);break;case`Unknown`:return`The sandbox failed for an unrecognized reason${t?` (ref ${e.ref??`unavailable`})`:``}`}return!t||e.ref===void 0?n:`${n} (ref ${e.ref})`}var wS=_(()=>Qr([t(uS),t(dS),t(fS),t(pS),t(mS),t(hS),t(gS),t(_S),t(vS),t(yS),t(bS),t(xS)])),TS=_(()=>xt().pipe(Qr([t(Error).transform(e=>({kind:`error`,value:e})),wn().transform(e=>({kind:`null`,value:e})),Ir().transform(e=>({kind:`undefined`,value:e})),w().transform(e=>({kind:`string`,value:e})),pr().transform(e=>({kind:`boolean`,value:e})),Qr([Mn(),Rn(),yr(1/0),yr(-1/0)]).transform(e=>({kind:`number`,value:e})),nn().transform(e=>({kind:`bigint`,value:e})),ht().transform(e=>({kind:`symbol`,value:e})),t(Function).transform(e=>({kind:`function`,value:e})),Er(xt()).transform(e=>({kind:`array`,value:e})),Qr([t(Object),si(w(),xt())]).transform(e=>({kind:`object`,value:e})),xt().transform(()=>({kind:`opaque`}))])));function ES(e){return wS.safeParse(e).success}function DS(e){let t=wS.safeParse(e);return t.success?t.data:new xS({rawCause:e})}function OS(e){let t=TS.parse(e);switch(t.kind){case`error`:case`array`:case`null`:return`object`;default:return t.kind}}_(()=>bn().optional());function kS(e){return AS(e,new Set)}function AS(e,t){let n=TS.parse(e);switch(n.kind){case`null`:case`undefined`:return null;case`string`:case`boolean`:return n.value;case`number`:return Number.isFinite(n.value)?n.value:String(n.value);case`bigint`:case`symbol`:return String(n.value);case`function`:return{kind:`function`,name:n.value.name};case`opaque`:return{kind:`opaque`};case`error`:case`array`:case`object`:{let r=n.value;if(t.has(e))return{kind:`circular_reference`};t.add(e);try{if(n.kind===`array`)return n.value.map(e=>AS(e,t));let e=Object.fromEntries(Object.entries(r).map(([e,n])=>[e,AS(n,t)]));if(n.kind===`error`){let r=n.value;e.name=r.name,e.message=r.message,r.stack!==void 0&&(e.stack=r.stack),r.cause!==void 0&&(e.cause=AS(r.cause,t)),r instanceof AggregateError&&(e.errors=AS(r.errors,t))}return e}finally{t.delete(e)}}}}var jS=_(()=>Qt({name:yr(`ReferenceError`),message:w().regex(/^[\p{ID_Start}_$][\p{ID_Continue}$]* is not defined$/u)}).transform(e=>({...e,missingVariable:e.message.slice(0,-15)})));_(()=>Qr([jS,Qt({name:w(),message:w()})]).and(Qt({transportMessage:w().max(512).optional()})));var MS=_(()=>ln({v:yr(1),kind:yr(`sandbox_failure`),tag:Jt([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),ref:w().min(1).max(32),message:w().max(160)})),NS=D(U(am)),PS=_(()=>w().transform((e,t)=>{let n=NS(e);return Ae(n)?(t.addIssue({code:`custom`,message:`Invalid sandbox transport JSON`}),ur):n.success})).pipe(MS);ln({error:PS}),_(()=>xt().pipe(Qr([yr(`Execution timed out`).transform(()=>({kind:`deadline`})),xt().transform(e=>({kind:`bad_response`,rawCause:e}))])));var FS=ln({sandboxCapacity:Vr().positive().optional(),admissionWaitMs:Vr().min(1).max(9e5).optional()});function IS(e,t){let n=FS.safeParse(e??{}),r=Vr().positive().safeParse(t??2);if(!n.success||!r.success)throw new G(`Sandbox admission policy is invalid`);return Object.freeze({capacity:n.data.sandboxCapacity??Math.min(32,Math.max(2,r.data)),waitMs:n.data.admissionWaitMs??18e4})}var LS=[509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,7,9,32,4,318,1,78,5,71,10,50,3,123,2,54,14,32,10,3,1,11,3,46,10,8,0,46,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,3,0,158,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,68,8,2,0,3,0,2,3,2,4,2,0,15,1,83,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,7,19,58,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,199,7,137,9,54,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,55,9,266,3,10,1,2,0,49,6,4,4,14,10,5350,0,7,14,11465,27,2343,9,87,9,39,4,60,6,26,9,535,9,470,0,2,54,8,3,82,0,12,1,19628,1,4178,9,519,45,3,22,543,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,101,0,161,6,10,9,357,0,62,13,499,13,245,1,2,9,233,0,3,0,8,1,6,0,475,6,110,6,6,9,4759,9,787719,239],RS=[0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,13,10,2,14,2,6,2,1,2,10,2,14,2,6,2,1,4,51,13,310,10,21,11,7,25,5,2,41,2,8,70,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,7,25,39,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,39,27,10,22,251,41,7,1,17,5,57,28,11,0,9,21,43,17,47,20,28,22,13,52,58,1,3,0,14,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,20,1,64,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,31,9,2,0,3,0,2,37,2,0,26,0,2,0,45,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,38,6,186,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,19,72,200,32,32,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,24,43,261,18,16,0,2,12,2,33,125,0,80,921,103,110,18,195,2637,96,16,1071,18,5,26,3994,6,582,6842,29,1763,568,8,30,18,78,18,29,19,47,17,3,32,20,6,18,433,44,212,63,33,24,3,24,45,74,6,0,67,12,65,1,2,0,15,4,10,7381,42,31,98,114,8702,3,2,6,2,1,2,290,16,0,30,2,3,0,15,3,9,395,2309,106,6,12,4,8,8,9,5991,84,2,70,2,1,3,0,3,1,3,3,2,11,2,0,2,6,2,64,2,3,3,7,2,6,2,27,2,3,2,4,2,0,4,6,2,339,3,24,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,30,2,24,2,7,1845,30,7,5,262,61,147,44,11,6,17,0,322,29,19,43,485,27,229,29,3,0,208,30,2,2,2,1,2,6,3,4,10,1,225,6,2,3,2,1,2,14,2,196,60,67,8,0,1205,3,2,26,2,1,2,0,3,0,2,9,2,3,2,0,2,0,7,0,5,0,2,0,2,0,2,2,2,1,2,0,3,0,2,0,2,0,2,0,2,0,2,1,2,0,3,3,2,6,2,3,2,3,2,0,2,9,2,16,6,2,2,4,2,16,4421,42719,33,4381,3,5773,3,7472,16,621,2467,541,1507,4938,6,8489],zS=`·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߽߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛-࢟࣊-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯৾ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ૺ-૿ଁ-ଃ଼ା-ୄେୈୋ-୍୕-ୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఄ఼ా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ೳഀ-ഃ഻഼ാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ඁ-ඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ຼ່-໎໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟፩-፱ᜒ-᜕ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠏-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏᧐-᧚ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᪿ--ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭᳴᳷-᳹᷀-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯・꘠-꘩꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧ꠬ꢀꢁꢴ-ꣅ꣐-꣙꣠-꣱ꣿ-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︯︳︴﹍-﹏0-9_・`,BS=`ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙՠ-ֈא-תׯ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࡠ-ࡪࡰ-ࢇࢉ-ࢠ-ࣉऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱৼਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡૹଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘ-ౚౝౠౡಀಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽ-ೞೠೡೱೲഄ-ഌഎ-ഐഒ-ഺഽൎൔ-ൖൟ-ൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄຆ-ຊຌ-ຣລວ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏽᏸ-ᏽᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜑᜟ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡸᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭌᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᲀ-Ა-ᲺᲽ-Ჿᳩ-ᳬᳮ-ᳳᳵᳶᳺᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕ℘-ℝℤΩℨK-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞ々-〇〡-〩〱-〵〸-〼ぁ-ゖ゛-ゟァ-ヺー-ヿㄅ-ㄯㄱ-ㆎㆠ-ㆿㇰ-ㇿ㐀-䶿一-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ--ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꣽꣾꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭩꭰ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ`,VS={3:`abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile`,5:`class enum extends super const export import`,6:`enum`,strict:`implements interface let package private protected public static yield`,strictBind:`eval arguments`},HS=`break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this`,US={5:HS,"5module":HS+` export import`,6:HS+` const class extends export import super`},WS=/^in(stanceof)?$/,GS=RegExp(`[`+BS+`]`),KS=RegExp(`[`+BS+zS+`]`);function qS(e,t){for(var n=65536,r=0;r<t.length;r+=2){if(n+=t[r],n>e)return!1;if(n+=t[r+1],n>=e)return!0}return!1}function JS(e,t){return e<65?e===36:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&GS.test(String.fromCharCode(e)):t!==!1&&qS(e,RS)}function YS(e,t){return e<48?e===36:e<58?!0:e<65?!1:e<91?!0:e<97?e===95:e<123?!0:e<=65535?e>=170&&KS.test(String.fromCharCode(e)):t===!1?!1:qS(e,RS)||qS(e,LS)}var K=function(e,t){t===void 0&&(t={}),this.label=e,this.keyword=t.keyword,this.beforeExpr=!!t.beforeExpr,this.startsExpr=!!t.startsExpr,this.isLoop=!!t.isLoop,this.isAssign=!!t.isAssign,this.prefix=!!t.prefix,this.postfix=!!t.postfix,this.binop=t.binop||null,this.updateContext=null};function XS(e,t){return new K(e,{beforeExpr:!0,binop:t})}var ZS={beforeExpr:!0},QS={startsExpr:!0},$S={};function q(e,t){return t===void 0&&(t={}),t.keyword=e,$S[e]=new K(e,t)}var J={num:new K(`num`,QS),regexp:new K(`regexp`,QS),string:new K(`string`,QS),name:new K(`name`,QS),privateId:new K(`privateId`,QS),eof:new K(`eof`),bracketL:new K(`[`,{beforeExpr:!0,startsExpr:!0}),bracketR:new K(`]`),braceL:new K(`{`,{beforeExpr:!0,startsExpr:!0}),braceR:new K(`}`),parenL:new K(`(`,{beforeExpr:!0,startsExpr:!0}),parenR:new K(`)`),comma:new K(`,`,ZS),semi:new K(`;`,ZS),colon:new K(`:`,ZS),dot:new K(`.`),question:new K(`?`,ZS),questionDot:new K(`?.`),arrow:new K(`=>`,ZS),template:new K(`template`),invalidTemplate:new K(`invalidTemplate`),ellipsis:new K(`...`,ZS),backQuote:new K("`",QS),dollarBraceL:new K("${",{beforeExpr:!0,startsExpr:!0}),eq:new K(`=`,{beforeExpr:!0,isAssign:!0}),assign:new K(`_=`,{beforeExpr:!0,isAssign:!0}),incDec:new K(`++/--`,{prefix:!0,postfix:!0,startsExpr:!0}),prefix:new K(`!/~`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),logicalOR:XS(`||`,1),logicalAND:XS(`&&`,2),bitwiseOR:XS(`|`,3),bitwiseXOR:XS(`^`,4),bitwiseAND:XS(`&`,5),equality:XS(`==/!=/===/!==`,6),relational:XS(`</>/<=/>=`,7),bitShift:XS(`<</>>/>>>`,8),plusMin:new K(`+/-`,{beforeExpr:!0,binop:9,prefix:!0,startsExpr:!0}),modulo:XS(`%`,10),star:XS(`*`,10),slash:XS(`/`,10),starstar:new K(`**`,{beforeExpr:!0}),coalesce:XS(`??`,1),_break:q(`break`),_case:q(`case`,ZS),_catch:q(`catch`),_continue:q(`continue`),_debugger:q(`debugger`),_default:q(`default`,ZS),_do:q(`do`,{isLoop:!0,beforeExpr:!0}),_else:q(`else`,ZS),_finally:q(`finally`),_for:q(`for`,{isLoop:!0}),_function:q(`function`,QS),_if:q(`if`),_return:q(`return`,ZS),_switch:q(`switch`),_throw:q(`throw`,ZS),_try:q(`try`),_var:q(`var`),_const:q(`const`),_while:q(`while`,{isLoop:!0}),_with:q(`with`),_new:q(`new`,{beforeExpr:!0,startsExpr:!0}),_this:q(`this`,QS),_super:q(`super`,QS),_class:q(`class`,QS),_extends:q(`extends`,ZS),_export:q(`export`),_import:q(`import`,QS),_null:q(`null`,QS),_true:q(`true`,QS),_false:q(`false`,QS),_in:q(`in`,{beforeExpr:!0,binop:7}),_instanceof:q(`instanceof`,{beforeExpr:!0,binop:7}),_typeof:q(`typeof`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_void:q(`void`,{beforeExpr:!0,prefix:!0,startsExpr:!0}),_delete:q(`delete`,{beforeExpr:!0,prefix:!0,startsExpr:!0})},eC=/\r\n?|\n|\u2028|\u2029/,tC=new RegExp(eC.source,`g`);function nC(e){return e===10||e===13||e===8232||e===8233}function rC(e,t,n){n===void 0&&(n=e.length);for(var r=t;r<n;r++){var i=e.charCodeAt(r);if(nC(i))return r<n-1&&i===13&&e.charCodeAt(r+1)===10?r+2:r+1}return-1}var iC=/[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/,aC=/(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g,oC=Object.prototype,sC=oC.hasOwnProperty,cC=oC.toString,lC=Object.hasOwn||(function(e,t){return sC.call(e,t)}),uC=Array.isArray||(function(e){return cC.call(e)===`[object Array]`}),dC=Object.create(null);function fC(e){return dC[e]||(dC[e]=RegExp(`^(?:`+e.replace(/ /g,`|`)+`)$`))}function pC(e){return e<=65535?String.fromCharCode(e):(e-=65536,String.fromCharCode((e>>10)+55296,(e&1023)+56320))}var mC=/(?:[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])/,hC=function(e,t){this.line=e,this.column=t};hC.prototype.offset=function(e){return new hC(this.line,this.column+e)};var gC=function(e,t,n){this.start=t,this.end=n,e.sourceFile!==null&&(this.source=e.sourceFile)};function _C(e,t){for(var n=1,r=0;;){var i=rC(e,r,t);if(i<0)return new hC(n,t-r);++n,r=i}}var vC={ecmaVersion:null,sourceType:`script`,strict:!1,onInsertedSemicolon:null,onTrailingComma:null,allowReserved:null,allowReturnOutsideFunction:!1,allowImportExportEverywhere:!1,allowAwaitOutsideFunction:null,allowSuperOutsideMethod:null,allowHashBang:!1,checkPrivateFields:!0,locations:!1,startLocation:null,onToken:null,onComment:null,ranges:!1,program:null,sourceFile:null,directSourceFile:null,preserveParens:!1},yC=!1;function bC(e){var t={};for(var n in vC)t[n]=e&&lC(e,n)?e[n]:vC[n];if(t.ecmaVersion===`latest`?t.ecmaVersion=1e8:t.ecmaVersion==null?(!yC&&typeof console==`object`&&console.warn&&(yC=!0,console.warn(`Since Acorn 8.0.0, options.ecmaVersion is required.
|
|
11
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),uC(t.onToken)){var r=t.onToken;t.onToken=function(e){return r.push(e)}}if(uC(t.onComment)&&(t.onComment=xC(t,t.onComment)),t.sourceType===`commonjs`&&t.allowAwaitOutsideFunction)throw Error(`Cannot use allowAwaitOutsideFunction with sourceType: commonjs`);return t}function xC(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 gC(this,o,s)),e.ranges&&(c.range=[i,a]),t.push(c)}}var SC=1,CC=2,wC=4,TC=8,EC=16,DC=32,OC=64,kC=128,AC=256,jC=512,MC=1024,NC=SC|CC|AC;function PC(e,t){return CC|(e?wC:0)|(t?TC:0)}var FC=0,IC=1,LC=2,RC=3,zC=4,BC=5,VC=function(e,t,n){this.options=e=bC(e),this.sourceFile=e.sourceFile,this.keywords=fC(US[e.ecmaVersion>=6?6:e.sourceType===`module`?`5module`:5]);var r=``;e.allowReserved!==!0&&(r=VS[e.ecmaVersion>=6?6:e.ecmaVersion===5?5:3],e.sourceType===`module`&&(r+=` await`)),this.reservedWords=fC(r);var i=(r?r+` `:``)+VS.strict;this.reservedWordsStrict=fC(i),this.reservedWordsStrictBind=fC(i+` `+VS.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
12
|
`,n-1)+1,this.options.locations&&(this.curLine=this.input.slice(0,this.lineStart).split(eC).length)):this.lineStart=0,this.type=J.eof,this.value=null,this.start=this.end=this.pos,this.startLoc=this.endLoc=this.curPosition(),this.lastTokEndLoc=this.lastTokStartLoc=null,this.lastTokStart=this.lastTokEnd=this.pos,this.context=this.initialContext(),this.exprAllowed=!0,this.inModule=e.sourceType===`module`,this.strict=this.inModule||e.strict===!0||this.strictDirective(this.pos),this.potentialArrowAt=-1,this.potentialArrowInForAwait=!1,this.yieldPos=this.awaitPos=this.awaitIdentPos=0,this.labels=[],this.undefinedExports=Object.create(null),this.pos===0&&e.allowHashBang&&this.input.slice(0,2)===`#!`&&this.skipLineComment(2),this.scopeStack=[],this.enterScope(this.options.sourceType===`commonjs`?CC:SC),this.regexpState=null,this.privateNameStack=[]},HC={inFunction:{configurable:!0},inGenerator:{configurable:!0},inAsync:{configurable:!0},canAwait:{configurable:!0},allowReturn:{configurable:!0},allowSuper:{configurable:!0},allowDirectSuper:{configurable:!0},treatFunctionsAsVar:{configurable:!0},allowNewDotTarget:{configurable:!0},allowUsing:{configurable:!0},inClassStaticBlock:{configurable:!0}};VC.prototype.parse=function(){var e=this,t=this.options.program||this.startNode();return this.nextToken(),this.catchStackOverflow(function(){return e.parseTopLevel(t)})},HC.inFunction.get=function(){return(this.currentVarScope().flags&CC)>0},HC.inGenerator.get=function(){return(this.currentVarScope().flags&TC)>0},HC.inAsync.get=function(){return(this.currentVarScope().flags&wC)>0},HC.canAwait.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(AC|jC))return!1;if(t&CC)return(t&wC)>0}return this.inModule&&this.options.ecmaVersion>=13||this.options.allowAwaitOutsideFunction},HC.allowReturn.get=function(){return!!(this.inFunction||this.options.allowReturnOutsideFunction&&this.currentVarScope().flags&SC)},HC.allowSuper.get=function(){return(this.currentThisScope().flags&OC)>0||this.options.allowSuperOutsideMethod},HC.allowDirectSuper.get=function(){return(this.currentThisScope().flags&kC)>0},HC.treatFunctionsAsVar.get=function(){return this.treatFunctionsAsVarInScope(this.currentScope())},HC.allowNewDotTarget.get=function(){for(var e=this.scopeStack.length-1;e>=0;e--){var t=this.scopeStack[e].flags;if(t&(AC|jC)||t&CC&&!(t&EC))return!0}return!1},HC.allowUsing.get=function(){var e=this.currentScope().flags;return!(e&MC||!this.inModule&&e&SC)},HC.inClassStaticBlock.get=function(){return(this.currentVarScope().flags&AC)>0},VC.extend=function(){for(var e=[],t=arguments.length;t--;)e[t]=arguments[t];for(var n=this,r=0;r<e.length;r++)n=e[r](n);return n},VC.parse=function(e,t){return new this(t,e).parse()},VC.parseExpressionAt=function(e,t,n){var r=new this(n,e,t);return r.nextToken(),r.parseExpression()},VC.tokenizer=function(e,t){return new this(t,e)},Object.defineProperties(VC.prototype,HC);var UC=VC.prototype,WC=/^(?:'((?:\\[^]|[^'\\])*?)'|"((?:\\[^]|[^"\\])*?)")/;UC.strictDirective=function(e){if(this.options.ecmaVersion<5)return!1;for(;;){aC.lastIndex=e,e+=aC.exec(this.input)[0].length;var t=WC.exec(this.input.slice(e));if(!t)return!1;if((t[1]||t[2])===`use strict`){aC.lastIndex=e+t[0].length;var n=aC.exec(this.input),r=n.index+n[0].length,i=this.input.charAt(r);return i===`;`||i===`}`||eC.test(n[0])&&!(/[(`.[+\-/*%<>=,?^&]/.test(i)||i===`!`&&this.input.charAt(r+1)===`=`)}e+=t[0].length,aC.lastIndex=e,e+=aC.exec(this.input)[0].length,this.input[e]===`;`&&e++}},UC.eat=function(e){return this.type===e&&(this.next(),!0)},UC.isContextual=function(e){return this.type===J.name&&this.value===e&&!this.containsEsc},UC.eatContextual=function(e){return this.isContextual(e)?(this.next(),!0):!1},UC.catchStackOverflow=function(e){try{return e()}catch(e){if(e instanceof Error&&(/\bstack\b.*\b(exceeded|overflow)\b/i.test(e.message)||/\btoo much recursion\b/i.test(e.message)))this.raise(this.start,`Not enough stack space to parse input`);else throw e}},UC.expectContextual=function(e){this.eatContextual(e)||this.unexpected()},UC.canInsertSemicolon=function(){return this.type===J.eof||this.type===J.braceR||eC.test(this.input.slice(this.lastTokEnd,this.start))},UC.insertSemicolon=function(){if(this.canInsertSemicolon())return this.options.onInsertedSemicolon&&this.options.onInsertedSemicolon(this.lastTokEnd,this.lastTokEndLoc),!0},UC.semicolon=function(){!this.eat(J.semi)&&!this.insertSemicolon()&&this.unexpected()},UC.afterTrailingComma=function(e,t){if(this.type===e)return this.options.onTrailingComma&&this.options.onTrailingComma(this.lastTokStart,this.lastTokStartLoc),t||this.next(),!0},UC.expect=function(e){this.eat(e)||this.unexpected()},UC.unexpected=function(e){this.raise(e??this.start,`Unexpected token`)};var GC=function(){this.shorthandAssign=this.trailingComma=this.parenthesizedAssign=this.parenthesizedBind=this.doubleProto=-1};UC.checkPatternErrors=function(e,t){if(e){e.trailingComma>-1&&this.raiseRecoverable(e.trailingComma,`Comma is not permitted after the rest element`);var n=t?e.parenthesizedAssign:e.parenthesizedBind;n>-1&&this.raiseRecoverable(n,t?`Assigning to rvalue`:`Parenthesized pattern`)}},UC.checkExpressionErrors=function(e,t){if(!e)return!1;var n=e.shorthandAssign,r=e.doubleProto;if(!t)return n>=0||r>=0;n>=0&&this.raise(n,`Shorthand property assignments are valid only in destructuring patterns`),r>=0&&this.raiseRecoverable(r,`Redefinition of __proto__ property`)},UC.checkYieldAwaitInDefaultParams=function(){this.yieldPos&&(!this.awaitPos||this.yieldPos<this.awaitPos)&&this.raise(this.yieldPos,`Yield expression cannot be a default value`),this.awaitPos&&this.raise(this.awaitPos,`Await expression cannot be a default value`)},UC.isSimpleAssignTarget=function(e){return e.type===`ParenthesizedExpression`?this.isSimpleAssignTarget(e.expression):e.type===`Identifier`||e.type===`MemberExpression`};var Y=VC.prototype;Y.parseTopLevel=function(e){var t=Object.create(null);for(e.body||=[];this.type!==J.eof;){var n=this.parseStatement(null,!0,t);e.body.push(n)}if(this.inModule)for(var r=0,i=Object.keys(this.undefinedExports);r<i.length;r+=1){var a=i[r];this.raiseRecoverable(this.undefinedExports[a].start,`Export '`+a+`' is not defined`)}return this.adaptDirectivePrologue(e.body),this.next(),e.sourceType=this.options.sourceType===`commonjs`?`script`:this.options.sourceType,this.finishNode(e,`Program`)};var KC={kind:`loop`},qC={kind:`switch`};Y.isLet=function(e){if(this.options.ecmaVersion<6||!this.isContextual(`let`))return!1;aC.lastIndex=this.pos;var t=aC.exec(this.input),n=this.pos+t[0].length,r=this.fullCharCodeAt(n);if(r===91||r===92)return!0;if(e)return!1;if(r===123)return!0;if(JS(r)){var i=n;do n+=r<=65535?1:2;while(YS(r=this.fullCharCodeAt(n)));if(r===92)return!0;var a=this.input.slice(i,n);if(!WS.test(a))return!0}return!1},Y.isAsyncFunction=function(){if(this.options.ecmaVersion<8||!this.isContextual(`async`))return!1;aC.lastIndex=this.pos;var e=aC.exec(this.input),t=this.pos+e[0].length,n;return!eC.test(this.input.slice(this.pos,t))&&this.input.slice(t,t+8)===`function`&&(t+8===this.input.length||!(YS(n=this.fullCharCodeAt(t+8))||n===92))},Y.isUsingKeyword=function(e,t){if(this.options.ecmaVersion<17||!this.isContextual(e?`await`:`using`))return!1;aC.lastIndex=this.pos;var n=aC.exec(this.input),r=this.pos+n[0].length;if(eC.test(this.input.slice(this.pos,r)))return!1;if(e){var i=r+5,a;if(this.input.slice(r,i)!==`using`||i===this.input.length||YS(a=this.fullCharCodeAt(i))||a===92)return!1;aC.lastIndex=i;var o=aC.exec(this.input);if(r=i+o[0].length,o&&eC.test(this.input.slice(i,r)))return!1}var s=this.fullCharCodeAt(r);if(!JS(s)&&s!==92)return!1;var c=r;do r+=s<=65535?1:2;while(YS(s=this.fullCharCodeAt(r)));if(s===92)return!0;var l=this.input.slice(c,r);if(WS.test(l))return!1;if(t&&!e&&l===`of`){aC.lastIndex=r;var u=aC.exec(this.input);if(r+=u[0].length,this.input.charCodeAt(r)!==61||(s=this.input.charCodeAt(r+1))===61||s===62)return!1}return!0},Y.isAwaitUsing=function(e){return this.isUsingKeyword(!0,e)},Y.isUsing=function(e){return this.isUsingKeyword(!1,e)},Y.parseStatement=function(e,t,n){var r=this.type,i=this.startNode(),a;switch(this.isLet(e)&&(r=J._var,a=`let`),r){case J._break:case J._continue:return this.parseBreakContinueStatement(i,r.keyword);case J._debugger:return this.parseDebuggerStatement(i);case J._do:return this.parseDoStatement(i);case J._for:return this.parseForStatement(i);case J._function:return e&&(this.strict||e!==`if`&&e!==`label`)&&this.options.ecmaVersion>=6&&this.unexpected(),this.parseFunctionStatement(i,!1,!e);case J._class:return e&&this.unexpected(),this.parseClass(i,!0);case J._if:return this.parseIfStatement(i);case J._return:return this.parseReturnStatement(i);case J._switch:return this.parseSwitchStatement(i);case J._throw:return this.parseThrowStatement(i);case J._try:return this.parseTryStatement(i);case J._const:case J._var:return a||=this.value,e&&a!==`var`&&this.unexpected(),this.parseVarStatement(i,a);case J._while:return this.parseWhileStatement(i);case J._with:return this.parseWithStatement(i);case J.braceL:return this.parseBlock(!0,i);case J.semi:return this.parseEmptyStatement(i);case J._export:case J._import:if(this.options.ecmaVersion>10&&r===J._import){aC.lastIndex=this.pos;var o=aC.exec(this.input),s=this.pos+o[0].length,c=this.input.charCodeAt(s);if(c===40||c===46)return this.parseExpressionStatement(i,this.parseExpression())}return this.options.allowImportExportEverywhere||(t||this.raise(this.start,`'import' and 'export' may only appear at the top level`),this.inModule||this.raise(this.start,`'import' and 'export' may appear only with 'sourceType: module'`)),r===J._import?this.parseImport(i):this.parseExport(i,n);default:if(this.isAsyncFunction())return e&&this.unexpected(),this.next(),this.parseFunctionStatement(i,!0,!e);var l=this.isAwaitUsing(!1)?`await using`:this.isUsing(!1)?`using`:null;if(l)return this.allowUsing||this.raise(this.start,"Using declaration cannot appear in the top level when source type is `script` or in the bare case statement"),e&&this.raise(this.start,`Using declaration is not allowed in single-statement positions`),l===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.next(),this.parseVar(i,!1,l),this.semicolon(),this.finishNode(i,`VariableDeclaration`);var u=this.value,d=this.parseExpression();return r===J.name&&d.type===`Identifier`&&this.eat(J.colon)?this.parseLabeledStatement(i,u,d,e):this.parseExpressionStatement(i,d)}},Y.parseBreakContinueStatement=function(e,t){var n=t===`break`;this.next(),this.eat(J.semi)||this.insertSemicolon()?e.label=null:this.type===J.name?(e.label=this.parseIdent(),this.semicolon()):this.unexpected();for(var r=0;r<this.labels.length;++r){var i=this.labels[r];if((e.label==null||i.name===e.label.name)&&(i.kind!=null&&(n||i.kind===`loop`)||e.label&&n))break}return r===this.labels.length&&this.raise(e.start,`Unsyntactic `+t),this.finishNode(e,n?`BreakStatement`:`ContinueStatement`)},Y.parseDebuggerStatement=function(e){return this.next(),this.semicolon(),this.finishNode(e,`DebuggerStatement`)},Y.parseDoStatement=function(e){return this.next(),this.labels.push(KC),e.body=this.parseStatement(`do`),this.labels.pop(),this.expect(J._while),e.test=this.parseParenExpression(),this.options.ecmaVersion>=6?this.eat(J.semi):this.semicolon(),this.finishNode(e,`DoWhileStatement`)},Y.parseForStatement=function(e){this.next();var t=this.options.ecmaVersion>=9&&this.canAwait&&this.eatContextual(`await`)?this.lastTokStart:-1;if(this.labels.push(KC),this.enterScope(0),this.expect(J.parenL),this.type===J.semi)return t>-1&&this.unexpected(t),this.parseFor(e,null);var n=this.isLet();if(this.type===J._var||this.type===J._const||n){var r=this.startNode(),i=n?`let`:this.value;return this.next(),this.parseVar(r,!0,i),this.finishNode(r,`VariableDeclaration`),this.parseForAfterInit(e,r,t)}var a=this.isContextual(`let`),o=!1,s=this.isUsing(!0)?`using`:this.isAwaitUsing(!0)?`await using`:null;if(s){var c=this.startNode();return this.next(),s===`await using`&&(this.canAwait||this.raise(this.start,`Await using cannot appear outside of async function`),this.next()),this.parseVar(c,!0,s),this.finishNode(c,`VariableDeclaration`),this.parseForAfterInit(e,c,t)}var l=this.containsEsc,u=new GC,d=this.start,f=t>-1?this.parseExprSubscripts(u,`await`):this.parseExpression(!0,u);return this.type===J._in||(o=this.options.ecmaVersion>=6&&this.isContextual(`of`))?(t>-1?(this.type===J._in&&this.unexpected(t),e.await=!0):o&&this.options.ecmaVersion>=8&&(f.start===d&&!l&&f.type===`Identifier`&&f.name===`async`?this.unexpected():this.options.ecmaVersion>=9&&(e.await=!1)),a&&o&&this.raise(f.start,`The left-hand side of a for-of loop may not start with 'let'.`),this.toAssignable(f,!1,u),this.checkLValPattern(f),this.parseForIn(e,f)):(this.checkExpressionErrors(u,!0),t>-1&&this.unexpected(t),this.parseFor(e,f))},Y.parseForAfterInit=function(e,t,n){return(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))&&t.declarations.length===1?(this.type===J._in?((t.kind===`using`||t.kind===`await using`)&&!t.declarations[0].init&&this.raise(this.start,`Using declaration is not allowed in for-in loops`),this.options.ecmaVersion>=9&&n>-1&&this.unexpected(n)):this.options.ecmaVersion>=9&&(e.await=n>-1),this.parseForIn(e,t)):(n>-1&&this.unexpected(n),this.parseFor(e,t))},Y.parseFunctionStatement=function(e,t,n){return this.next(),this.parseFunction(e,YC|(n?0:XC),!1,t)},Y.parseIfStatement=function(e){return this.next(),e.test=this.parseParenExpression(),e.consequent=this.parseStatement(`if`),e.alternate=this.eat(J._else)?this.parseStatement(`if`):null,this.finishNode(e,`IfStatement`)},Y.parseReturnStatement=function(e){return this.allowReturn||this.raise(this.start,`'return' outside of function`),this.next(),this.eat(J.semi)||this.insertSemicolon()?e.argument=null:(e.argument=this.parseExpression(),this.semicolon()),this.finishNode(e,`ReturnStatement`)},Y.parseSwitchStatement=function(e){this.next(),e.discriminant=this.parseParenExpression(),e.cases=[],this.expect(J.braceL),this.labels.push(qC),this.enterScope(MC);for(var t,n=!1;this.type!==J.braceR;)if(this.type===J._case||this.type===J._default){var r=this.type===J._case;t&&this.finishNode(t,`SwitchCase`),e.cases.push(t=this.startNode()),t.consequent=[],this.next(),r?t.test=this.parseExpression():(n&&this.raiseRecoverable(this.lastTokStart,`Multiple default clauses`),n=!0,t.test=null),this.expect(J.colon)}else t||this.unexpected(),t.consequent.push(this.parseStatement(null));return this.exitScope(),t&&this.finishNode(t,`SwitchCase`),this.next(),this.labels.pop(),this.finishNode(e,`SwitchStatement`)},Y.parseThrowStatement=function(e){return this.next(),eC.test(this.input.slice(this.lastTokEnd,this.start))&&this.raise(this.lastTokEnd,`Illegal newline after throw`),e.argument=this.parseExpression(),this.semicolon(),this.finishNode(e,`ThrowStatement`)};var JC=[];Y.parseCatchClauseParam=function(){var e=this.parseBindingAtom(),t=e.type===`Identifier`;return this.enterScope(t?DC:0),this.checkLValPattern(e,t?zC:LC),this.expect(J.parenR),e},Y.parseTryStatement=function(e){if(this.next(),e.block=this.parseBlock(),e.handler=null,this.type===J._catch){var t=this.startNode();this.next(),this.eat(J.parenL)?t.param=this.parseCatchClauseParam():(this.options.ecmaVersion<10&&this.unexpected(),t.param=null,this.enterScope(0)),t.body=this.parseBlock(!1),this.exitScope(),e.handler=this.finishNode(t,`CatchClause`)}return e.finalizer=this.eat(J._finally)?this.parseBlock():null,!e.handler&&!e.finalizer&&this.raise(e.start,`Missing catch or finally clause`),this.finishNode(e,`TryStatement`)},Y.parseVarStatement=function(e,t,n){return this.next(),this.parseVar(e,!1,t,n),this.semicolon(),this.finishNode(e,`VariableDeclaration`)},Y.parseWhileStatement=function(e){return this.next(),e.test=this.parseParenExpression(),this.labels.push(KC),e.body=this.parseStatement(`while`),this.labels.pop(),this.finishNode(e,`WhileStatement`)},Y.parseWithStatement=function(e){return this.strict&&this.raise(this.start,`'with' in strict mode`),this.next(),e.object=this.parseParenExpression(),e.body=this.parseStatement(`with`),this.finishNode(e,`WithStatement`)},Y.parseEmptyStatement=function(e){return this.next(),this.finishNode(e,`EmptyStatement`)},Y.parseLabeledStatement=function(e,t,n,r){for(var i=0,a=this.labels;i<a.length;i+=1)a[i].name===t&&this.raise(n.start,`Label '`+t+`' is already declared`);for(var o=this.type.isLoop?`loop`:this.type===J._switch?`switch`:null,s=this.labels.length-1;s>=0;s--){var c=this.labels[s];if(c.statementStart===e.start)c.statementStart=this.start,c.kind=o;else break}return this.labels.push({name:t,kind:o,statementStart:this.start}),e.body=this.parseStatement(r?r.indexOf(`label`)===-1?r+`label`:r:`label`),this.labels.pop(),e.label=n,this.finishNode(e,`LabeledStatement`)},Y.parseExpressionStatement=function(e,t){return e.expression=t,this.semicolon(),this.finishNode(e,`ExpressionStatement`)},Y.parseBlock=function(e,t,n){for(e===void 0&&(e=!0),t===void 0&&(t=this.startNode()),t.body=[],this.expect(J.braceL),e&&this.enterScope(0);this.type!==J.braceR;){var r=this.parseStatement(null);t.body.push(r)}return n&&(this.strict=!1),this.next(),e&&this.exitScope(),this.finishNode(t,`BlockStatement`)},Y.parseFor=function(e,t){return e.init=t,this.expect(J.semi),e.test=this.type===J.semi?null:this.parseExpression(),this.expect(J.semi),e.update=this.type===J.parenR?null:this.parseExpression(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,`ForStatement`)},Y.parseForIn=function(e,t){var n=this.type===J._in;return this.next(),t.type===`VariableDeclaration`&&t.declarations[0].init!=null&&(!n||this.options.ecmaVersion<8||this.strict||t.kind!==`var`||t.declarations[0].id.type!==`Identifier`)&&this.raise(t.start,(n?`for-in`:`for-of`)+` loop variable declaration may not have an initializer`),e.left=t,e.right=n?this.parseExpression():this.parseMaybeAssign(),this.expect(J.parenR),e.body=this.parseStatement(`for`),this.exitScope(),this.labels.pop(),this.finishNode(e,n?`ForInStatement`:`ForOfStatement`)},Y.parseVar=function(e,t,n,r){for(e.declarations=[],e.kind=n;;){var i=this.startNode();if(this.parseVarId(i,n),this.eat(J.eq)?i.init=this.parseMaybeAssign(t):!r&&n===`const`&&!(this.type===J._in||this.options.ecmaVersion>=6&&this.isContextual(`of`))?this.unexpected():!r&&(n===`using`||n===`await using`)&&this.options.ecmaVersion>=17&&this.type!==J._in&&!this.isContextual(`of`)?this.raise(this.lastTokEnd,`Missing initializer in `+n+` declaration`):!r&&i.id.type!==`Identifier`&&!(t&&(this.type===J._in||this.isContextual(`of`)))?this.raise(this.lastTokEnd,`Complex binding patterns require an initialization value`):i.init=null,e.declarations.push(this.finishNode(i,`VariableDeclarator`)),!this.eat(J.comma))break}return e},Y.parseVarId=function(e,t){e.id=t===`using`||t===`await using`?this.parseIdent():this.parseBindingAtom(),this.checkLValPattern(e.id,t===`var`?IC:LC,!1)};var YC=1,XC=2,ZC=4;Y.parseFunction=function(e,t,n,r,i){this.initFunction(e),(this.options.ecmaVersion>=9||this.options.ecmaVersion>=6&&!r)&&(this.type===J.star&&t&XC&&this.unexpected(),e.generator=this.eat(J.star)),this.options.ecmaVersion>=8&&(e.async=!!r),t&YC&&(e.id=t&ZC&&this.type!==J.name?null:this.parseIdent(),e.id&&!(t&XC)&&this.checkLValSimple(e.id,this.strict||e.generator||e.async?this.treatFunctionsAsVar?IC:LC:RC));var a=this.yieldPos,o=this.awaitPos,s=this.awaitIdentPos;return this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0,this.enterScope(PC(e.async,e.generator)),t&YC||(e.id=this.type===J.name?this.parseIdent():null),this.parseFunctionParams(e),this.parseFunctionBody(e,n,!1,i),this.yieldPos=a,this.awaitPos=o,this.awaitIdentPos=s,this.finishNode(e,t&YC?`FunctionDeclaration`:`FunctionExpression`)},Y.parseFunctionParams=function(e){this.expect(J.parenL),e.params=this.parseBindingList(J.parenR,!1,this.options.ecmaVersion>=8),this.checkYieldAwaitInDefaultParams()},Y.parseClass=function(e,t){this.next();var n=this.strict;this.strict=!0,this.parseClassId(e,t),this.parseClassSuper(e);var r=this.enterClassBody(),i=this.startNode(),a=!1;for(i.body=[],this.expect(J.braceL);this.type!==J.braceR;){var o=this.parseClassElement(e.superClass!==null);o&&(i.body.push(o),o.type===`MethodDefinition`&&o.kind===`constructor`?(a&&this.raiseRecoverable(o.start,`Duplicate constructor in the same class`),a=!0):o.key&&o.key.type===`PrivateIdentifier`&&QC(r,o)&&this.raiseRecoverable(o.key.start,`Identifier '#`+o.key.name+`' has already been declared`))}return this.strict=n,this.next(),e.body=this.finishNode(i,`ClassBody`),this.exitClassBody(),this.finishNode(e,t?`ClassDeclaration`:`ClassExpression`)},Y.parseClassElement=function(e){if(this.eat(J.semi))return null;var t=this.options.ecmaVersion,n=this.startNode(),r=``,i=!1,a=!1,o=`method`,s=!1;if(this.eatContextual(`static`)){if(t>=13&&this.eat(J.braceL))return this.parseClassStaticBlock(n),n;this.isClassElementNameStart()||this.type===J.star?s=!0:r=`static`}if(n.static=s,!r&&t>=8&&this.eatContextual(`async`)&&((this.isClassElementNameStart()||this.type===J.star)&&!this.canInsertSemicolon()?a=!0:r=`async`),!r&&(t>=9||!a)&&this.eat(J.star)&&(i=!0),!r&&!a&&!i){var c=this.value;(this.eatContextual(`get`)||this.eatContextual(`set`))&&(this.isClassElementNameStart()?o=c:r=c)}if(r?(n.computed=!1,n.key=this.startNodeAt(this.lastTokStart,this.lastTokStartLoc),n.key.name=r,this.finishNode(n.key,`Identifier`)):this.parseClassElementName(n),t<13||this.type===J.parenL||o!==`method`||i||a){var l=!n.static&&$C(n,`constructor`),u=l&&e;l&&o!==`method`&&this.raise(n.key.start,`Constructor can't have get/set modifier`),n.kind=l?`constructor`:o,this.parseClassMethod(n,i,a,u)}else this.parseClassField(n);return n},Y.isClassElementNameStart=function(){return this.type===J.name||this.type===J.privateId||this.type===J.num||this.type===J.string||this.type===J.bracketL||this.type.keyword},Y.parseClassElementName=function(e){this.type===J.privateId?(this.value===`constructor`&&this.raise(this.start,`Classes can't have an element named '#constructor'`),e.computed=!1,e.key=this.parsePrivateIdent()):this.parsePropertyName(e)},Y.parseClassMethod=function(e,t,n,r){var i=e.key;e.kind===`constructor`?(t&&this.raise(i.start,`Constructor can't be a generator`),n&&this.raise(i.start,`Constructor can't be an async method`)):e.static&&$C(e,`prototype`)&&this.raise(i.start,`Classes may not have a static property named prototype`);var a=e.value=this.parseMethod(t,n,r);return e.kind===`get`&&a.params.length!==0&&this.raiseRecoverable(a.start,`getter should have no params`),e.kind===`set`&&a.params.length!==1&&this.raiseRecoverable(a.start,`setter should have exactly one param`),e.kind===`set`&&a.params[0].type===`RestElement`&&this.raiseRecoverable(a.params[0].start,`Setter cannot use rest params`),this.finishNode(e,`MethodDefinition`)},Y.parseClassField=function(e){return $C(e,`constructor`)?this.raise(e.key.start,`Classes can't have a field named 'constructor'`):e.static&&$C(e,`prototype`)&&this.raise(e.key.start,`Classes can't have a static field named 'prototype'`),this.eat(J.eq)?(this.enterScope(jC|OC),e.value=this.parseMaybeAssign(),this.exitScope()):e.value=null,this.semicolon(),this.finishNode(e,`PropertyDefinition`)},Y.parseClassStaticBlock=function(e){e.body=[];var t=this.labels;for(this.labels=[],this.enterScope(AC|OC);this.type!==J.braceR;){var n=this.parseStatement(null);e.body.push(n)}return this.next(),this.exitScope(),this.labels=t,this.finishNode(e,`StaticBlock`)},Y.parseClassId=function(e,t){this.type===J.name?(e.id=this.parseIdent(),t&&this.checkLValSimple(e.id,LC,!1)):(t===!0&&this.unexpected(),e.id=null)},Y.parseClassSuper=function(e){e.superClass=this.eat(J._extends)?this.parseExprSubscripts(null,!1):null},Y.enterClassBody=function(){var e={declared:Object.create(null),used:[]};return this.privateNameStack.push(e),e.declared},Y.exitClassBody=function(){var e=this.privateNameStack.pop(),t=e.declared,n=e.used;if(this.options.checkPrivateFields)for(var r=this.privateNameStack.length,i=r===0?null:this.privateNameStack[r-1],a=0;a<n.length;++a){var o=n[a];lC(t,o.name)||(i?i.used.push(o):this.raiseRecoverable(o.start,`Private field '#`+o.name+`' must be declared in an enclosing class`))}};function QC(e,t){var n=t.key.name,r=e[n],i=`true`;return t.type===`MethodDefinition`&&(t.kind===`get`||t.kind===`set`)&&(i=(t.static?`s`:`i`)+t.kind),r===`iget`&&i===`iset`||r===`iset`&&i===`iget`||r===`sget`&&i===`sset`||r===`sset`&&i===`sget`?(e[n]=`true`,!1):r?!0:(e[n]=i,!1)}function $C(e,t){var n=e.computed,r=e.key;return!n&&(r.type===`Identifier`&&r.name===t||r.type===`Literal`&&r.value===t)}Y.parseExportAllDeclaration=function(e,t){return this.options.ecmaVersion>=11&&(this.eatContextual(`as`)?(e.exported=this.parseModuleExportName(),this.checkExport(t,e.exported,this.lastTokStart)):e.exported=null),this.expectContextual(`from`),this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ExportAllDeclaration`)},Y.parseExport=function(e,t){if(this.next(),this.eat(J.star))return this.parseExportAllDeclaration(e,t);if(this.eat(J._default))return this.checkExport(t,`default`,this.lastTokStart),e.declaration=this.parseExportDefaultDeclaration(),this.finishNode(e,`ExportDefaultDeclaration`);if(this.shouldParseExportStatement())e.declaration=this.parseExportDeclaration(e),e.declaration.type===`VariableDeclaration`?this.checkVariableExport(t,e.declaration.declarations):this.checkExport(t,e.declaration.id,e.declaration.id.start),e.specifiers=[],e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[]);else{if(e.declaration=null,e.specifiers=this.parseExportSpecifiers(t),this.eatContextual(`from`))this.type!==J.string&&this.unexpected(),e.source=this.parseExprAtom(),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause());else{for(var n=0,r=e.specifiers;n<r.length;n+=1){var i=r[n];this.checkUnreserved(i.local),this.checkLocalExport(i.local),i.local.type===`Literal`&&this.raise(i.local.start,"A string literal cannot be used as an exported binding without `from`.")}e.source=null,this.options.ecmaVersion>=16&&(e.attributes=[])}this.semicolon()}return this.finishNode(e,`ExportNamedDeclaration`)},Y.parseExportDeclaration=function(e){return this.parseStatement(null)},Y.parseExportDefaultDeclaration=function(){var e;if(this.type===J._function||(e=this.isAsyncFunction())){var t=this.startNode();return this.next(),e&&this.next(),this.parseFunction(t,YC|ZC,!1,e)}if(this.type===J._class){var n=this.startNode();return this.parseClass(n,`nullableID`)}var r=this.parseMaybeAssign();return this.semicolon(),r},Y.checkExport=function(e,t,n){e&&(typeof t!=`string`&&(t=t.type===`Identifier`?t.name:t.value),lC(e,t)&&this.raiseRecoverable(n,`Duplicate export '`+t+`'`),e[t]=!0)},Y.checkPatternExport=function(e,t){var n=t.type;if(n===`Identifier`)this.checkExport(e,t,t.start);else if(n===`ObjectPattern`)for(var r=0,i=t.properties;r<i.length;r+=1){var a=i[r];this.checkPatternExport(e,a)}else if(n===`ArrayPattern`)for(var o=0,s=t.elements;o<s.length;o+=1){var c=s[o];c&&this.checkPatternExport(e,c)}else n===`Property`?this.checkPatternExport(e,t.value):n===`AssignmentPattern`?this.checkPatternExport(e,t.left):n===`RestElement`&&this.checkPatternExport(e,t.argument)},Y.checkVariableExport=function(e,t){if(e)for(var n=0,r=t;n<r.length;n+=1){var i=r[n];this.checkPatternExport(e,i.id)}},Y.shouldParseExportStatement=function(){return this.type.keyword===`var`||this.type.keyword===`const`||this.type.keyword===`class`||this.type.keyword===`function`||this.isLet()||this.isAsyncFunction()},Y.parseExportSpecifier=function(e){var t=this.startNode();return t.local=this.parseModuleExportName(),t.exported=this.eatContextual(`as`)?this.parseModuleExportName():t.local,this.checkExport(e,t.exported,t.exported.start),this.finishNode(t,`ExportSpecifier`)},Y.parseExportSpecifiers=function(e){var t=[],n=!0;for(this.expect(J.braceL);!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;t.push(this.parseExportSpecifier(e))}return t},Y.parseImport=function(e){return this.next(),this.type===J.string?(e.specifiers=JC,e.source=this.parseExprAtom()):(e.specifiers=this.parseImportSpecifiers(),this.expectContextual(`from`),e.source=this.type===J.string?this.parseExprAtom():this.unexpected()),this.options.ecmaVersion>=16&&(e.attributes=this.parseWithClause()),this.semicolon(),this.finishNode(e,`ImportDeclaration`)},Y.parseImportSpecifier=function(){var e=this.startNode();return e.imported=this.parseModuleExportName(),this.eatContextual(`as`)?e.local=this.parseIdent():(this.checkUnreserved(e.imported),e.local=e.imported),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportSpecifier`)},Y.parseImportDefaultSpecifier=function(){var e=this.startNode();return e.local=this.parseIdent(),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportDefaultSpecifier`)},Y.parseImportNamespaceSpecifier=function(){var e=this.startNode();return this.next(),this.expectContextual(`as`),e.local=this.parseIdent(),this.checkLValSimple(e.local,LC),this.finishNode(e,`ImportNamespaceSpecifier`)},Y.parseImportSpecifiers=function(){var e=[],t=!0;if(this.type===J.name&&(e.push(this.parseImportDefaultSpecifier()),!this.eat(J.comma)))return e;if(this.type===J.star)return e.push(this.parseImportNamespaceSpecifier()),e;for(this.expect(J.braceL);!this.eat(J.braceR);){if(t)t=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;e.push(this.parseImportSpecifier())}return e},Y.parseWithClause=function(){var e=[];if(!this.eat(J._with))return e;this.expect(J.braceL);for(var t={},n=!0;!this.eat(J.braceR);){if(n)n=!1;else if(this.expect(J.comma),this.afterTrailingComma(J.braceR))break;var r=this.parseImportAttribute(),i=r.key.type===`Identifier`?r.key.name:r.key.value;lC(t,i)&&this.raiseRecoverable(r.key.start,`Duplicate attribute key '`+i+`'`),t[i]=!0,e.push(r)}return e},Y.parseImportAttribute=function(){var e=this.startNode();return e.key=this.type===J.string?this.parseExprAtom():this.parseIdent(this.options.allowReserved!==`never`),this.expect(J.colon),this.type!==J.string&&this.unexpected(),e.value=this.parseExprAtom(),this.finishNode(e,`ImportAttribute`)},Y.parseModuleExportName=function(){if(this.options.ecmaVersion>=13&&this.type===J.string){var e=this.parseLiteral(this.value);return mC.test(e.value)&&this.raise(e.start,`An export name cannot include a lone surrogate.`),e}return this.parseIdent(!0)},Y.adaptDirectivePrologue=function(e){for(var t=0;t<e.length&&this.isDirectiveCandidate(e[t]);++t)e[t].directive=e[t].expression.raw.slice(1,-1)},Y.isDirectiveCandidate=function(e){return this.options.ecmaVersion>=5&&e.type===`ExpressionStatement`&&e.expression.type===`Literal`&&typeof e.expression.value==`string`&&(this.input[e.start]===`"`||this.input[e.start]===`'`)};var ew=VC.prototype;ew.toAssignable=function(e,t,n){if(this.options.ecmaVersion>=6&&e)switch(e.type){case`Identifier`:this.inAsync&&e.name===`await`&&this.raise(e.start,`Cannot use 'await' as identifier inside an async function`);break;case`ObjectPattern`:case`ArrayPattern`:case`AssignmentPattern`:case`RestElement`:break;case`ObjectExpression`:e.type=`ObjectPattern`,n&&this.checkPatternErrors(n,!0);for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.toAssignable(a,t),a.type===`RestElement`&&(a.argument.type===`ArrayPattern`||a.argument.type===`ObjectPattern`)&&this.raise(a.argument.start,`Unexpected token`)}break;case`Property`:e.kind!==`init`&&this.raise(e.key.start,`Object pattern can't contain getter or setter`),this.toAssignable(e.value,t);break;case`ArrayExpression`:e.type=`ArrayPattern`,n&&this.checkPatternErrors(n,!0),this.toAssignableList(e.elements,t);break;case`SpreadElement`:e.type=`RestElement`,this.toAssignable(e.argument,t),e.argument.type===`AssignmentPattern`&&this.raise(e.argument.start,`Rest elements cannot have a default value`);break;case`AssignmentExpression`:e.operator!==`=`&&this.raise(e.left.end,`Only '=' operator can be used for specifying default value.`),e.type=`AssignmentPattern`,delete e.operator,this.toAssignable(e.left,t);break;case`ParenthesizedExpression`:this.toAssignable(e.expression,t,n);break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:if(!t)break;default:this.raise(e.start,`Assigning to rvalue`)}else n&&this.checkPatternErrors(n,!0);return e},ew.toAssignableList=function(e,t){for(var n=e.length,r=0;r<n;r++){var i=e[r];i&&this.toAssignable(i,t)}if(n){var a=e[n-1];this.options.ecmaVersion===6&&t&&a&&a.type===`RestElement`&&a.argument.type!==`Identifier`&&this.unexpected(a.argument.start)}return e},ew.parseSpread=function(e){var t=this.startNode();return this.next(),t.argument=this.parseMaybeAssign(!1,e),this.finishNode(t,`SpreadElement`)},ew.parseRestBinding=function(){var e=this.startNode();return this.next(),this.options.ecmaVersion===6&&this.type!==J.name&&this.unexpected(),e.argument=this.parseBindingAtom(),this.finishNode(e,`RestElement`)},ew.parseBindingAtom=function(){if(this.options.ecmaVersion>=6)switch(this.type){case J.bracketL:var e=this.startNode();return this.next(),e.elements=this.parseBindingList(J.bracketR,!0,!0),this.finishNode(e,`ArrayPattern`);case J.braceL:return this.parseObj(!0)}return this.parseIdent()},ew.parseBindingList=function(e,t,n,r){for(var i=[],a=!0;!this.eat(e);)if(a?a=!1:this.expect(J.comma),t&&this.type===J.comma)i.push(null);else if(n&&this.afterTrailingComma(e))break;else if(this.type===J.ellipsis){var o=this.parseRestBinding();this.parseBindingListItem(o),i.push(o),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`),this.expect(e);break}else i.push(this.parseAssignableListItem(r));return i},ew.parseAssignableListItem=function(e){var t=this.parseMaybeDefault(this.start,this.startLoc);return this.parseBindingListItem(t),t},ew.parseBindingListItem=function(e){return e},ew.parseMaybeDefault=function(e,t,n){if(n||=this.parseBindingAtom(),this.options.ecmaVersion<6||!this.eat(J.eq))return n;var r=this.startNodeAt(e,t);return r.left=n,r.right=this.parseMaybeAssign(),this.finishNode(r,`AssignmentPattern`)},ew.checkLValSimple=function(e,t,n){t===void 0&&(t=FC);var r=t!==FC;switch(e.type){case`Identifier`:this.strict&&this.reservedWordsStrictBind.test(e.name)&&this.raiseRecoverable(e.start,(r?`Binding `:`Assigning to `)+e.name+` in strict mode`),r&&(t===LC&&e.name===`let`&&this.raiseRecoverable(e.start,`let is disallowed as a lexically bound name`),n&&(lC(n,e.name)&&this.raiseRecoverable(e.start,`Argument name clash`),n[e.name]=!0),t!==BC&&this.declareName(e.name,t,e.start));break;case`ChainExpression`:this.raiseRecoverable(e.start,`Optional chaining cannot appear in left-hand side`);break;case`MemberExpression`:r&&this.raiseRecoverable(e.start,`Binding member expression`);break;case`ParenthesizedExpression`:return r&&this.raiseRecoverable(e.start,`Binding parenthesized expression`),this.checkLValSimple(e.expression,t,n);default:this.raise(e.start,(r?`Binding`:`Assigning to`)+` rvalue`)}},ew.checkLValPattern=function(e,t,n){switch(t===void 0&&(t=FC),e.type){case`ObjectPattern`:for(var r=0,i=e.properties;r<i.length;r+=1){var a=i[r];this.checkLValInnerPattern(a,t,n)}break;case`ArrayPattern`:for(var o=0,s=e.elements;o<s.length;o+=1){var c=s[o];c&&this.checkLValInnerPattern(c,t,n)}break;default:this.checkLValSimple(e,t,n)}},ew.checkLValInnerPattern=function(e,t,n){switch(t===void 0&&(t=FC),e.type){case`Property`:this.checkLValInnerPattern(e.value,t,n);break;case`AssignmentPattern`:this.checkLValPattern(e.left,t,n);break;case`RestElement`:this.checkLValPattern(e.argument,t,n);break;default:this.checkLValPattern(e,t,n)}};var tw=function(e,t,n,r,i){this.token=e,this.isExpr=!!t,this.preserveSpace=!!n,this.override=r,this.generator=!!i},nw={b_stat:new tw(`{`,!1),b_expr:new tw(`{`,!0),b_tmpl:new tw("${",!1),p_stat:new tw(`(`,!1),p_expr:new tw(`(`,!0),q_tmpl:new tw("`",!0,!0,function(e){return e.tryReadTemplateToken()}),f_stat:new tw(`function`,!1),f_expr:new tw(`function`,!0),f_expr_gen:new tw(`function`,!0,!1,null,!0),f_gen:new tw(`function`,!1,!1,null,!0)},rw=VC.prototype;rw.initialContext=function(){return[nw.b_stat]},rw.curContext=function(){return this.context[this.context.length-1]},rw.braceIsBlock=function(e){var t=this.curContext();return t===nw.f_expr||t===nw.f_stat?!0:e===J.colon&&(t===nw.b_stat||t===nw.b_expr)?!t.isExpr:e===J._return||e===J.name&&this.exprAllowed?eC.test(this.input.slice(this.lastTokEnd,this.start)):e===J._else||e===J.semi||e===J.eof||e===J.parenR||e===J.arrow?!0:e===J.braceL?t===nw.b_stat:e===J._var||e===J._const||e===J.name?!1:!this.exprAllowed},rw.inGeneratorContext=function(){for(var e=this.context.length-1;e>=1;e--){var t=this.context[e];if(t.token===`function`)return t.generator}return!1},rw.updateContext=function(e){var t,n=this.type;n.keyword&&e===J.dot?this.exprAllowed=!1:(t=n.updateContext)?t.call(this,e):this.exprAllowed=n.beforeExpr},rw.overrideContext=function(e){this.curContext()!==e&&(this.context[this.context.length-1]=e)},J.parenR.updateContext=J.braceR.updateContext=function(){if(this.context.length===1){this.exprAllowed=!0;return}var e=this.context.pop();e===nw.b_stat&&this.curContext().token===`function`&&(e=this.context.pop()),this.exprAllowed=!e.isExpr},J.braceL.updateContext=function(e){this.context.push(this.braceIsBlock(e)?nw.b_stat:nw.b_expr),this.exprAllowed=!0},J.dollarBraceL.updateContext=function(){this.context.push(nw.b_tmpl),this.exprAllowed=!0},J.parenL.updateContext=function(e){var t=e===J._if||e===J._for||e===J._with||e===J._while;this.context.push(t?nw.p_stat:nw.p_expr),this.exprAllowed=!0},J.incDec.updateContext=function(){},J._function.updateContext=J._class.updateContext=function(e){e.beforeExpr&&e!==J._else&&(e!==J.semi||this.curContext()===nw.p_stat)&&!(e===J._return&&eC.test(this.input.slice(this.lastTokEnd,this.start)))&&(e!==J.colon&&e!==J.braceL||this.curContext()!==nw.b_stat)?this.context.push(nw.f_expr):this.context.push(nw.f_stat),this.exprAllowed=!1},J.colon.updateContext=function(){this.curContext().token===`function`&&this.context.pop(),this.exprAllowed=!0},J.backQuote.updateContext=function(){this.curContext()===nw.q_tmpl?this.context.pop():this.context.push(nw.q_tmpl),this.exprAllowed=!1},J.star.updateContext=function(e){if(e===J._function){var t=this.context.length-1;this.context[t]===nw.f_expr?this.context[t]=nw.f_expr_gen:this.context[t]=nw.f_gen}this.exprAllowed=!0},J.name.updateContext=function(e){var t=!1;this.options.ecmaVersion>=6&&e!==J.dot&&(this.value===`of`&&!this.exprAllowed||this.value===`yield`&&this.inGeneratorContext())&&(t=!0),this.exprAllowed=t};var X=VC.prototype;X.checkPropClash=function(e,t,n){if(!(this.options.ecmaVersion>=9&&e.type===`SpreadElement`)&&!(this.options.ecmaVersion>=6&&(e.computed||e.method||e.shorthand))){var r=e.key,i;switch(r.type){case`Identifier`:i=r.name;break;case`Literal`:i=String(r.value);break;default:return}var a=e.kind;if(this.options.ecmaVersion>=6){i===`__proto__`&&a===`init`&&(t.proto&&(n?n.doubleProto<0&&(n.doubleProto=r.start):this.raiseRecoverable(r.start,`Redefinition of __proto__ property`)),t.proto=!0);return}i=`$`+i;var o=t[i];o?(a===`init`?this.strict&&o.init||o.get||o.set:o.init||o[a])&&this.raiseRecoverable(r.start,`Redefinition of property`):o=t[i]={init:!1,get:!1,set:!1},o[a]=!0}},X.parseExpression=function(e,t){var n=this;return this.catchStackOverflow(function(){var r=n.start,i=n.startLoc,a=n.parseMaybeAssign(e,t);if(n.type===J.comma){var o=n.startNodeAt(r,i);for(o.expressions=[a];n.eat(J.comma);)o.expressions.push(n.parseMaybeAssign(e,t));return n.finishNode(o,`SequenceExpression`)}return a})},X.parseMaybeAssign=function(e,t,n){if(this.isContextual(`yield`)){if(this.inGenerator)return this.parseYield(e);this.exprAllowed=!1}var r=!1,i=-1,a=-1,o=-1;t?(i=t.parenthesizedAssign,a=t.trailingComma,o=t.doubleProto,t.parenthesizedAssign=t.trailingComma=-1):(t=new GC,r=!0);var s=this.start,c=this.startLoc;(this.type===J.parenL||this.type===J.name)&&(this.potentialArrowAt=this.start,this.potentialArrowInForAwait=e===`await`);var l=this.parseMaybeConditional(e,t);if(n&&(l=n.call(this,l,s,c)),this.type.isAssign){var u=this.startNodeAt(s,c);return u.operator=this.value,this.type===J.eq&&(l=this.toAssignable(l,!1,t)),r||(t.parenthesizedAssign=t.trailingComma=t.doubleProto=-1),t.shorthandAssign>=l.start&&(t.shorthandAssign=-1),this.type===J.eq?this.checkLValPattern(l):this.checkLValSimple(l),u.left=l,this.next(),u.right=this.parseMaybeAssign(e),o>-1&&(t.doubleProto=o),this.finishNode(u,`AssignmentExpression`)}return r&&this.checkExpressionErrors(t,!0),i>-1&&(t.parenthesizedAssign=i),a>-1&&(t.trailingComma=a),l},X.parseMaybeConditional=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprOps(e,t);if(this.checkExpressionErrors(t))return i;if((i.type!==`ArrowFunctionExpression`||i.start!==n)&&this.eat(J.question)){var a=this.startNodeAt(n,r);return a.test=i,a.consequent=this.parseMaybeAssign(),this.expect(J.colon),a.alternate=this.parseMaybeAssign(e),this.finishNode(a,`ConditionalExpression`)}return i},X.parseExprOps=function(e,t){var n=this.start,r=this.startLoc,i=this.parseMaybeUnary(t,!1,!1,e);return this.checkExpressionErrors(t)||i.start===n&&i.type===`ArrowFunctionExpression`?i:this.parseExprOp(i,n,r,-1,e)},X.parseExprOp=function(e,t,n,r,i){var a=this.type.binop;if(a!=null&&(!i||this.type!==J._in)&&a>r){var o=this.type===J.logicalOR||this.type===J.logicalAND,s=this.type===J.coalesce;s&&(a=J.logicalAND.binop);var c=this.value;this.next();var l=this.start,u=this.startLoc,d=this.parseExprOp(this.parseMaybeUnary(null,!1,!1,i),l,u,a,i),f=this.buildBinary(t,n,e,d,c,o||s);return(o&&this.type===J.coalesce||s&&(this.type===J.logicalOR||this.type===J.logicalAND))&&this.raiseRecoverable(this.start,`Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses`),this.parseExprOp(f,t,n,r,i)}return e},X.buildBinary=function(e,t,n,r,i,a){r.type===`PrivateIdentifier`&&this.raise(r.start,`Private identifier can only be left side of binary expression`);var o=this.startNodeAt(e,t);return o.left=n,o.operator=i,o.right=r,this.finishNode(o,a?`LogicalExpression`:`BinaryExpression`)},X.parseMaybeUnary=function(e,t,n,r){var i=this.start,a=this.startLoc,o;if(this.isContextual(`await`)&&this.canAwait)o=this.parseAwait(r),t=!0;else if(this.type.prefix){var s=this.startNode(),c=this.type===J.incDec;s.operator=this.value,s.prefix=!0,this.next(),s.argument=this.parseMaybeUnary(null,!0,c,r),this.checkExpressionErrors(e,!0),c?this.checkLValSimple(s.argument):this.strict&&s.operator===`delete`&&iw(s.argument)?this.raiseRecoverable(s.start,`Deleting local variable in strict mode`):s.operator===`delete`&&aw(s.argument)?this.raiseRecoverable(s.start,`Private fields can not be deleted`):t=!0,o=this.finishNode(s,c?`UpdateExpression`:`UnaryExpression`)}else if(!t&&this.type===J.privateId)(r||this.privateNameStack.length===0)&&this.options.checkPrivateFields&&this.unexpected(),o=this.parsePrivateIdent(),this.type!==J._in&&this.unexpected();else{if(o=this.parseExprSubscripts(e,r),this.checkExpressionErrors(e))return o;for(;this.type.postfix&&!this.canInsertSemicolon();){var l=this.startNodeAt(i,a);l.operator=this.value,l.prefix=!1,l.argument=o,this.checkLValSimple(o),this.next(),o=this.finishNode(l,`UpdateExpression`)}}if(!n&&(o.type!==`ArrowFunctionExpression`||o.start!==i)&&this.eat(J.starstar)){if(t)this.unexpected(this.lastTokStart);else return this.buildBinary(i,a,o,this.parseMaybeUnary(null,!1,!1,r),`**`,!1)}else return o};function iw(e){return e.type===`Identifier`||e.type===`ParenthesizedExpression`&&iw(e.expression)}function aw(e){return e.type===`MemberExpression`&&e.property.type===`PrivateIdentifier`||e.type===`ChainExpression`&&aw(e.expression)||e.type===`ParenthesizedExpression`&&aw(e.expression)}X.parseExprSubscripts=function(e,t){var n=this.start,r=this.startLoc,i=this.parseExprAtom(e,t);if(i.type===`ArrowFunctionExpression`&&this.input.slice(this.lastTokStart,this.lastTokEnd)!==`)`)return i;var a=this.parseSubscripts(i,n,r,!1,t);return e&&a.type===`MemberExpression`&&(e.parenthesizedAssign>=a.start&&(e.parenthesizedAssign=-1),e.parenthesizedBind>=a.start&&(e.parenthesizedBind=-1),e.trailingComma>=a.start&&(e.trailingComma=-1)),a},X.parseSubscripts=function(e,t,n,r,i){for(var a=this.options.ecmaVersion>=8&&e.type===`Identifier`&&e.name===`async`&&this.lastTokEnd===e.end&&!this.canInsertSemicolon()&&e.end-e.start===5&&this.potentialArrowAt===e.start,o=!1;;){var s=this.parseSubscript(e,t,n,r,a,o,i);if(s.optional&&(o=!0),s===e||s.type===`ArrowFunctionExpression`){if(o){var c=this.startNodeAt(t,n);c.expression=s,s=this.finishNode(c,`ChainExpression`)}return s}e=s}},X.shouldParseAsyncArrow=function(){return!this.canInsertSemicolon()&&this.eat(J.arrow)},X.parseSubscriptAsyncArrow=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!0,r)},X.parseSubscript=function(e,t,n,r,i,a,o){var s=this.options.ecmaVersion>=11,c=s&&this.eat(J.questionDot);r&&c&&this.raise(this.lastTokStart,`Optional chaining cannot appear in the callee of new expressions`);var l=this.eat(J.bracketL);if(l||c&&this.type!==J.parenL&&this.type!==J.backQuote||this.eat(J.dot)){var u=this.startNodeAt(t,n);u.object=e,l?(u.property=this.parseExpression(),this.expect(J.bracketR)):u.property=this.type===J.privateId&&e.type!==`Super`?this.parsePrivateIdent():this.parseIdent(this.options.allowReserved!==`never`),u.computed=!!l,s&&(u.optional=c),e=this.finishNode(u,`MemberExpression`)}else if(!r&&this.eat(J.parenL)){var d=new GC,f=this.yieldPos,p=this.awaitPos,m=this.awaitIdentPos;this.yieldPos=0,this.awaitPos=0,this.awaitIdentPos=0;var ee=this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1,d);if(i&&!c&&this.shouldParseAsyncArrow())return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.awaitIdentPos>0&&this.raise(this.awaitIdentPos,`Cannot use 'await' as identifier inside an async function`),this.yieldPos=f,this.awaitPos=p,this.awaitIdentPos=m,this.parseSubscriptAsyncArrow(t,n,ee,o);this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,this.awaitIdentPos=m||this.awaitIdentPos;var te=this.startNodeAt(t,n);te.callee=e,te.arguments=ee,s&&(te.optional=c),e=this.finishNode(te,`CallExpression`)}else if(this.type===J.backQuote){(c||a)&&this.raise(this.start,`Optional chaining cannot appear in the tag of tagged template expressions`);var ne=this.startNodeAt(t,n);ne.tag=e,ne.quasi=this.parseTemplate({isTagged:!0}),e=this.finishNode(ne,`TaggedTemplateExpression`)}return e},X.parseExprAtom=function(e,t,n){this.type===J.slash&&this.readRegexp();var r,i=this.potentialArrowAt===this.start;switch(this.type){case J._super:return this.allowSuper||this.raise(this.start,`'super' keyword outside a method`),r=this.startNode(),this.next(),this.type===J.parenL&&!this.allowDirectSuper&&this.raise(r.start,`super() call outside constructor of a subclass`),this.type!==J.dot&&this.type!==J.bracketL&&this.type!==J.parenL&&this.unexpected(),this.finishNode(r,`Super`);case J._this:return r=this.startNode(),this.next(),this.finishNode(r,`ThisExpression`);case J.name:var a=this.start,o=this.startLoc,s=this.containsEsc,c=this.parseIdent(!1);if(this.options.ecmaVersion>=8&&!s&&c.name===`async`&&!this.canInsertSemicolon()&&this.eat(J._function))return this.overrideContext(nw.f_expr),this.parseFunction(this.startNodeAt(a,o),0,!1,!0,t);if(i&&!this.canInsertSemicolon()){if(this.eat(J.arrow))return this.parseArrowExpression(this.startNodeAt(a,o),[c],!1,t);if(this.options.ecmaVersion>=8&&c.name===`async`&&this.type===J.name&&!s&&(!this.potentialArrowInForAwait||this.value!==`of`||this.containsEsc))return c=this.parseIdent(!1),(this.canInsertSemicolon()||!this.eat(J.arrow))&&this.unexpected(),this.parseArrowExpression(this.startNodeAt(a,o),[c],!0,t)}return c;case J.regexp:var l=this.value;return r=this.parseLiteral(l.value),r.regex={pattern:l.pattern,flags:l.flags},r;case J.num:case J.string:return this.parseLiteral(this.value);case J._null:case J._true:case J._false:return r=this.startNode(),r.value=this.type===J._null?null:this.type===J._true,r.raw=this.type.keyword,this.next(),this.finishNode(r,`Literal`);case J.parenL:var u=this.start,d=this.parseParenAndDistinguishExpression(i,t);return e&&(e.parenthesizedAssign<0&&!this.isSimpleAssignTarget(d)&&(e.parenthesizedAssign=u),e.parenthesizedBind<0&&(e.parenthesizedBind=u)),d;case J.bracketL:return r=this.startNode(),this.next(),r.elements=this.parseExprList(J.bracketR,!0,!0,e),this.finishNode(r,`ArrayExpression`);case J.braceL:return this.overrideContext(nw.b_expr),this.parseObj(!1,e);case J._function:return r=this.startNode(),this.next(),this.parseFunction(r,0);case J._class:return this.parseClass(this.startNode(),!1);case J._new:return this.parseNew();case J.backQuote:return this.parseTemplate();case J._import:return this.options.ecmaVersion>=11?this.parseExprImport(n):this.unexpected();default:return this.parseExprAtomDefault()}},X.parseExprAtomDefault=function(){this.unexpected()},X.parseExprImport=function(e){var t=this.startNode();if(this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword import`),this.next(),this.type===J.parenL&&!e)return this.parseDynamicImport(t);if(this.type===J.dot){var n=this.startNodeAt(t.start,t.loc&&t.loc.start);return n.name=`import`,t.meta=this.finishNode(n,`Identifier`),this.parseImportMeta(t)}this.unexpected()},X.parseDynamicImport=function(e){if(this.next(),e.source=this.parseMaybeAssign(),this.options.ecmaVersion>=16)this.eat(J.parenR)?e.options=null:(this.expect(J.comma),this.afterTrailingComma(J.parenR)?e.options=null:(e.options=this.parseMaybeAssign(),this.eat(J.parenR)||(this.expect(J.comma),this.afterTrailingComma(J.parenR)||this.unexpected())));else if(!this.eat(J.parenR)){var t=this.start;this.eat(J.comma)&&this.eat(J.parenR)?this.raiseRecoverable(t,`Trailing comma is not allowed in import()`):this.unexpected(t)}return this.finishNode(e,`ImportExpression`)},X.parseImportMeta=function(e){this.next();var t=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`meta`&&this.raiseRecoverable(e.property.start,`The only valid meta property for import is 'import.meta'`),t&&this.raiseRecoverable(e.start,`'import.meta' must not contain escaped characters`),this.options.sourceType!==`module`&&!this.options.allowImportExportEverywhere&&this.raiseRecoverable(e.start,`Cannot use 'import.meta' outside a module`),this.finishNode(e,`MetaProperty`)},X.parseLiteral=function(e){var t=this.startNode();return t.value=e,t.raw=this.input.slice(this.start,this.end),t.raw.charCodeAt(t.raw.length-1)===110&&(t.bigint=t.value==null?t.raw.slice(0,-1).replace(/_/g,``):t.value.toString()),this.next(),this.finishNode(t,`Literal`)},X.parseParenExpression=function(){this.expect(J.parenL);var e=this.parseExpression();return this.expect(J.parenR),e},X.shouldParseArrow=function(e){return!this.canInsertSemicolon()},X.parseParenAndDistinguishExpression=function(e,t){var n=this.start,r=this.startLoc,i,a=this.options.ecmaVersion>=8;if(this.options.ecmaVersion>=6){this.next();var o=this.start,s=this.startLoc,c=[],l=!0,u=!1,d=new GC,f=this.yieldPos,p=this.awaitPos,m;for(this.yieldPos=0,this.awaitPos=0;this.type!==J.parenR;){if(l?l=!1:this.expect(J.comma),a&&this.afterTrailingComma(J.parenR,!0)){u=!0;break}if(this.type===J.ellipsis){m=this.start,c.push(this.parseParenItem(this.parseRestBinding())),this.type===J.comma&&this.raiseRecoverable(this.start,`Comma is not permitted after the rest element`);break}c.push(this.parseMaybeAssign(!1,d,this.parseParenItem))}var ee=this.lastTokEnd,te=this.lastTokEndLoc;if(this.expect(J.parenR),e&&this.shouldParseArrow(c)&&this.eat(J.arrow))return this.checkPatternErrors(d,!1),this.checkYieldAwaitInDefaultParams(),this.yieldPos=f,this.awaitPos=p,this.parseParenArrowList(n,r,c,t);(!c.length||u)&&this.unexpected(this.lastTokStart),m&&this.unexpected(m),this.checkExpressionErrors(d,!0),this.yieldPos=f||this.yieldPos,this.awaitPos=p||this.awaitPos,c.length>1?(i=this.startNodeAt(o,s),i.expressions=c,this.finishNodeAt(i,`SequenceExpression`,ee,te)):i=c[0]}else i=this.parseParenExpression();if(this.options.preserveParens){var ne=this.startNodeAt(n,r);return ne.expression=i,this.finishNode(ne,`ParenthesizedExpression`)}return i},X.parseParenItem=function(e){return e},X.parseParenArrowList=function(e,t,n,r){return this.parseArrowExpression(this.startNodeAt(e,t),n,!1,r)};var ow=[];X.parseNew=function(){this.containsEsc&&this.raiseRecoverable(this.start,`Escape sequence in keyword new`);var e=this.startNode();if(this.next(),this.options.ecmaVersion>=6&&this.type===J.dot){var t=this.startNodeAt(e.start,e.loc&&e.loc.start);t.name=`new`,e.meta=this.finishNode(t,`Identifier`),this.next();var n=this.containsEsc;return e.property=this.parseIdent(!0),e.property.name!==`target`&&this.raiseRecoverable(e.property.start,`The only valid meta property for new is 'new.target'`),n&&this.raiseRecoverable(e.start,`'new.target' must not contain escaped characters`),this.allowNewDotTarget||this.raiseRecoverable(e.start,`'new.target' can only be used in functions and class static block`),this.finishNode(e,`MetaProperty`)}var r=this.start,i=this.startLoc;return e.callee=this.parseSubscripts(this.parseExprAtom(null,!1,!0),r,i,!0,!1),e.callee.type===`Super`&&this.raiseRecoverable(r,`Invalid use of 'super'`),e.arguments=this.eat(J.parenL)?this.parseExprList(J.parenR,this.options.ecmaVersion>=8,!1):ow,this.finishNode(e,`NewExpression`)},X.parseTemplateElement=function(e){var t=e.isTagged,n=this.startNode();return this.type===J.invalidTemplate?(t||this.raiseRecoverable(this.start,`Bad escape sequence in untagged template literal`),n.value={raw:this.value.replace(/\r\n?/g,`
|
|
13
13
|
`),cooked:null}):n.value={raw:this.input.slice(this.start,this.end).replace(/\r\n?/g,`
|
|
@@ -15,10 +15,10 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
|
|
|
15
15
|
`;break;default:e+=String.fromCharCode(n)}this.options.locations&&(++this.curLine,this.lineStart=this.pos),t=this.pos}else++this.pos}},Q.readInvalidTemplateToken=function(){for(;this.pos<this.input.length;this.pos++)switch(this.input[this.pos]){case`\\`:++this.pos;break;case`$`:if(this.input[this.pos+1]!==`{`)break;case"`":return this.finishToken(J.invalidTemplate,this.input.slice(this.start,this.pos));case`\r`:this.input[this.pos+1]===`
|
|
16
16
|
`&&++this.pos;case`
|
|
17
17
|
`:case`\u2028`:case`\u2029`:++this.curLine,this.lineStart=this.pos+1}this.raise(this.start,`Unterminated template`)},Q.readEscapedChar=function(e){var t=this.input.charCodeAt(++this.pos);switch(++this.pos,t){case 110:return`
|
|
18
|
-
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return pC(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),(r!==`0`||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return nC(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},Q.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},Q.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(YS(i,r))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?JS:YS)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=pC(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},Q.readWord=function(){var e=this.readWord1(),t=J.name;return this.keywords.test(e)&&(t=$S[e]),this.finishToken(t,e)},VC.acorn={Parser:VC,version:`8.18.0`,defaultOptions:vC,Position:hC,SourceLocation:gC,getLineInfo:_C,Node:uw,TokenType:K,tokTypes:J,keywordTypes:$S,TokContext:tw,tokContexts:nw,isIdentifierChar:YS,isIdentifierStart:JS,Token:tT,isNewLine:nC,lineBreak:eC,lineBreakG:tC,nonASCIIwhitespace:iC};function aT(e,t){return VC.parse(e,t)}_(()=>mn(`ok`,[cn({ok:vr(!0),value:bt()}),cn({ok:vr(!1),error:cn({kind:vr(`guest_threw`),name:w().max(80),message:w().max(512),transportMessage:w().max(512).optional()})})]));var oT=_(()=>w().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),sT=oT.refine(e=>{if(e===`env`)return!1;try{return aT(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);_(()=>si(sT,Tr(oT).min(1))),_(()=>si(sT,Tr(w().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var cT=L([`read`,`write`]),lT=cm,uT=P({access:A(cT),confirm:A(lT)}),dT=L([`none`,`read`,`write`]),fT=D(uT),pT=D(dT);function mT(e){let t=fT({access:e.access,confirm:e.confirm});if(ke(t))throw new G(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function hT(e,t){let n=`${t.module}.${t.operation}`;switch(e){case`not-granted`:return`${n} is not granted to this Agent.`;case`read-only`:return`${n} changes something, and this Agent has read-only access to ${t.module}.`;case`confirmation-unavailable`:return`${n} needs a person's approval, and no one can be asked here.`;case`declined`:return`${n} was not approved.`}}function gT(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:hT(e,t)})}function _T(e,t,n){let r=e.sessionGrants?.(t),i=r!==void 0&&Object.hasOwn(r,n)?r:e.grants;if(i===void 0||!Object.hasOwn(i,n))return e.required?.includes(n)===!0?`none`:e.defaultGrant??`write`;let a=pT(i[n]);return Ht(a)?a.success:`none`}async function vT(e,t,n,r,i){let a=await yT(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function yT(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=bT(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?gT(`confirmation-unavailable`,n):await e.confirm({module:n.module,operation:n.operation,access:n.access,sessionId:t.sessionId,input:r},i)?(await e.beforeCall?.(i),i.throwIfAborted(),bT(e,t,n)):gT(`declined`,n)}function bT(e,t,n){let r=_T(e,t,n.module);if(r===`none`)return gT(`not-granted`,n);if(r===`read`&&n.access!==`read`)return gT(`read-only`,n)}function xT(e,t,n){let r={module:e.module,operation:e.descriptor.name,...mT(e)};return{...e,prepare:i=>fn({try:e=>vT(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(T(t=>t===void 0?e.prepare(i):x({execute:()=>Gv({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var ST=Cs();async function CT(e){let t=await Kn(e);if(ca(t))return{value:t.value};let n=Yi(t.cause);if(ke(n))throw Ji(t.cause);return{issues:ST(n.success.issue).issues}}function wT(e){let t=Xh(e),n=Bp(t)[`~standard`].jsonSchema,r=Hp(t),i=qp(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>CT(r(e)),encode:e=>CT(i(e))})}function TT(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function ET(e){return em(e)?wT(e):TT(e)}var DT=Symbol(`mycelium.operation`),OT=Symbol(`mycelium.module`),kT=new WeakMap,AT=new WeakMap;function jT(e){let t=Object.freeze({[DT]:!0}),n=ET(e.input),r=e.output===void 0?void 0:ET(e.output),i={replay:e.replay??`unsafe`,...mT(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new cS(a.issues);let o=await e.execute(a.value,i);if(r===void 0)return o;let s=await r.encode(o);if(s.issues!==void 0)throw new _S({reason:`Capability output failed its declared schema`,rawCause:new lS(s.issues)});return s.value}};e.description!==void 0&&(i.description=e.description),r!==void 0&&(i.output=r.description);let a=Object.freeze(i);return kT.set(t,a),t}function MT(e){let t=Tr(oT).safeParse(e.namespace??[]);if(!t.success)throw new G(`Invalid module namespace`);let n=Object.freeze({[OT]:!0}),r={id:e.id,grantKey:e.id,name:e.name??e.id,namespace:Object.freeze(t.data),operations:Object.freeze({...e.operations})};e.description!==void 0&&(r.description=e.description);let i=Object.freeze(r);return AT.set(n,i),n}function NT(e){return AT.has(e)}function PT(e){return kT.get(e)}function FT(e){return AT.get(e)}function IT(e,t,n){let r=FT(e);if(r===void 0)throw new G(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(NT(a)){let n=FT(a);if(n===void 0)throw new G(`Unknown child module registration`);i[e]=IT(a,t,[r,...n.namespace].join(`.`));continue}let o=PT(a);if(o===void 0)throw new G(`Unknown operation registration: ${e}`);let s=Object.freeze({[DT]:!0});kT.set(s,Object.freeze({...o,invoke:async(e,n)=>{let i=await t({operation:r,context:n});return i.kind===`refuse`?i.value:await o.invoke(e,n)}})),i[e]=s}return LT(MT(r.description===void 0?{id:r.id,name:r.name,namespace:r.namespace,operations:i}:{id:r.id,name:r.name,namespace:r.namespace,description:r.description,operations:i}),r.grantKey)}function LT(e,t){let n=FT(e);if(n===void 0)throw new G(`Unknown module registration`);let r=Object.freeze({[OT]:!0});return AT.set(r,Object.freeze({...n,grantKey:t})),r}function RT(e,t){if(t.length===0||t.length>160)throw new G(`Grant key must be non-empty and bounded`);return LT(e,t)}function zT(e,t){return IT(e,t,``)}function BT(e,t){return e<t?-1:+(e>t)}function VT(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var HT=160;function UT(e){if(e.length===0||e.length>HT)throw new G(`Module id must be non-empty and bounded`)}function WT(e){if(!e.split(`.`).every(e=>oT.safeParse(e).success))throw new G(`Operation key must be a path segment or a dotted relative path`)}function GT(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function KT(e){let t=GT(e);return sT.safeParse(t).success?t:`module_${t}`}function qT(e,t){let n=new Set([`forage`,`env`]),r=new Map;for(let i of e){let e=t===`logical`?i.namespace:[],a=t===`logical`?GT(i.name):KT(i.name),o=t=>[...e,t].join(`.`),s=a,c=2;for(;n.has(o(s));)s=`${a}_${String(c)}`,c+=1;n.add(o(s)),r.set(i.id,s)}return r}var JT=14695981039346656037n,YT=1099511628211n,XT=18446744073709551615n;function ZT(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*YT&XT,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*YT&XT,n=(n^BigInt(r>>>8&255))*YT&XT}return n}function QT(e,t,n){let r=ZT(JT,e),i=[...t.entries()].sort(([e],[t])=>BT(e,t));for(let[e,t]of i)r=ZT(r,e),r=ZT(r,t);let a=[...n].sort((e,t)=>BT(e.id,t.id));for(let e of a)r=ZT(r,e.id),r=ZT(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function $T(){return[tS,eS,nS]}function eE(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(WT(t),NT(o)){let s=FT(o);if(s===void 0)throw new G(`Unknown child module registration`);return eE(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=PT(o);if(s===void 0)throw new G(`Unknown operation registration: ${[...r,t].join(`.`)}`);return[Object.freeze({grantKey:e,path:[...r,t].join(`.`),namespace:n,name:[...a,t].join(`.`),moduleDescription:i,operation:s})]})}function tE(e,t=[]){let n=e.map(e=>{let t=FT(e);if(t===void 0)throw new G(`Unknown module registration`);return UT(t.id),t}).sort((e,t)=>BT(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new G(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=qT(n,`transport`),a=qT(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new G(`Missing logical alias: ${e.id}`);return[t,Object.freeze([...e.namespace,n])]}))),s=n.flatMap(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new G(`Missing namespace path: ${e.id}`);return eE(e.grantKey,e,t,n,e.description)}).sort((e,t)=>BT(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new G(`Duplicate operation path`);for(let e of $T()){if(c.has(e.path))throw new G(`Reserved intrinsic path: ${e.path}`);c.add(e.path)}for(let e of c){let t=e.split(`.`);for(let n=1;n<t.length;n+=1)if(c.has(t.slice(0,n).join(`.`)))throw new G(`Operation conflicts with namespace: ${e}`)}let l;try{l=Xx({revision:`prepared-content-stamp`,operations:[...s.map(({path:e,moduleDescription:t,operation:n})=>{let r={path:e,input:n.input};return n.description!==void 0&&(r.description=n.description),n.output!==void 0&&(r.output=n.output),t!==void 0&&(r.instructions=t),r}),...$T()]})}catch(e){throw new G(VT(e))}let u=QT(l.stamp(),i,t),d=Object.freeze({revision:u,search:l.search,describe:l.describe,list:l.list,stamp:l.stamp}),f=Object.freeze(Object.fromEntries([...i.entries()].map(([e,t])=>[t,e])));return Object.freeze({revision:u,catalog:d,operations:Object.freeze(s),moduleAliases:f,namespacePaths:o})}function nE(){return null}var rE=yn(),iE=_(()=>Qr([Cn(),w(),fr(),Mn()])),aE=_(()=>si(w(),bt())),oE=_(()=>FS.extend({timeoutMs:Mn().int().min(1).max(9e5).optional(),abortGraceMs:Mn().int().min(1).max(3e4).optional()}).optional()),sE=64,cE=262144,lE=new TextEncoder,uE=e=>{e(x(void 0))};function dE(e){let t=oE.safeParse(e);if(!t.success)throw new G(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...IS({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function fE(e){return b(function*(){let t=yield*A_(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=$n(t=>e===0?(t(x(void 0)),y(()=>void 0)):(n.add(t),y(()=>n.delete(t))));return Object.freeze({start:r=>te(i=>y(()=>{e+=1}).pipe(g(ne(i(t.withPermits(1)(r)).pipe(rr(y(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(uE)}}))))))),awaitIdle:r})}})})}function pE(e,t=0){if(t>sE)throw Error(`JSON value exceeds the nesting bound`);let n=iE.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>pE(e,t+1));let r=aE.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,pE(n,t+1)]))}function mE(e){return rE.parse(pE(e))}function hE(e){let t=JSON.stringify(mE(e)),n=lE.encode(t).byteLength;if(n>cE)throw new vS({size:n});return Object.freeze({text:t})}function gE(e,t){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.freeze(Object.fromEntries(Object.entries(n).map(([n,r])=>[n,async i=>{t();try{return mE(await r(i))}catch(t){throw ES(t)?t:t instanceof tx?new bS({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof cS?new bS({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Kt({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function _E(e){return $n(t=>{let n=t.bind(void 0,C);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),y(e.removeEventListener.bind(e,`abort`,n))})}function vE(e,t){if(e===void 0)return()=>void 0;let n=t.bind(void 0);return e.aborted?(n(),()=>void 0):(e.addEventListener(`abort`,n,{once:!0}),e.removeEventListener.bind(e,`abort`,n))}function yE(e,t,n){return e===`deadline_exceeded`?new fS({limitMs:t,elapsedMs:n??0}):new mS({by:`caller`})}function bE(e){return Ma.pipe(Ce(t=>t-e))}function xE(e){return Ma.pipe(T(t=>sr(()=>{let n=e.executionId,r=new AbortController,i=t,a={kind:`waiting`},o,s=e=>{o===void 0&&a.kind!==`refused`&&(o=e,r.abort())},c=t=>{let n=new pS({capacity:e.policy.capacity,waitedMs:Math.max(0,t-i)});return a={kind:`refused`,failure:n},n},l=()=>{if(r.signal.aborted)throw yE(o,e.policy.timeoutMs)},u=vE(e.callerSignal,()=>{s(`cancelled`)}),d=t+e.policy.timeoutMs,f={executionId:n,deadlineAt:d,signal:r.signal,images:e.images};e.toolCallId!==void 0&&Object.assign(f,{toolCallId:e.toolCallId}),e.output!==void 0&&Object.assign(f,{output:e.output});let p=Object.freeze(f),m=sr(()=>Ma.pipe(T(u=>a.kind===`refused`?v(a.failure):(u>=d&&s(`deadline_exceeded`),r.signal.aborted?bE(t).pipe(T(t=>v(yE(o,e.policy.timeoutMs,t)))):u>=i+e.policy.waitMs?v(c(u)):(a={kind:`admitted`},e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:gE(e.createBindings(p),l),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(Br(e=>Ki(e)?Xt(e):v(DS(Ji(e)))))))))),ee=t=>S_(t).pipe(di({duration:e.policy.abortGraceMs,orElse:()=>v(o===`deadline_exceeded`?new fS({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new mS({by:`caller`,acknowledged:!1}))})),te,ne=!1,re=r=>(ne=!0,bE(t).pipe(T(t=>{let i=DS(r),a=i instanceof fS?new fS({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=SS(a,n),s=si(w(),yn()).parse(kS(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??nE(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=sr(()=>e.sandbox.onFailure?.(c)??C);return tt(`sandbox_failure`,c).pipe(dr({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),g(o._tag===`Unknown`?po(mo(fo(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(g(tt(`sandbox_health_alert`).pipe(dr({ref:n,adapter:c.adapter})))):C),g(l.pipe(Br(e=>tt(`sandbox_failure_record_failed`,e)))),Ar(o))})));return b(function*(){if(r.signal.aborted){let n=yield*bE(t);return yield*v(yE(o,e.policy.timeoutMs,n))}i=yield*Ma,te=yield*e.backingWork.start(m);let n=yield*Ma,l=jn(Math.max(0,i+e.policy.waitMs-n)).pipe(g(Ma),T(e=>a.kind===`admitted`?Mt:a.kind===`refused`?x({kind:`busy`,failure:a.failure}):r.signal.aborted?x({kind:`cancelled`}):e>=d?(s(`deadline_exceeded`),x({kind:`deadline`})):x({kind:`busy`,failure:c(e)}))),u=yield*Dn(b_(te).pipe(Ce(e=>Object.freeze({kind:`settled`,exit:e}))),Dn(jn(Math.max(0,d-n)).pipe(g(y(()=>(s(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),Dn(_E(r.signal).pipe(Ar(Object.freeze({kind:`cancelled`}))),l))),f=a.kind===`refused`?a.failure:u.kind===`busy`?u.failure:void 0;if(f!==void 0)return yield*ee(te).pipe(g(v(f)));if(u.kind===`settled`&&o===void 0)return yield*be(u.exit,{onFailure:Xt,onSuccess:e=>oi({try:()=>hE(e),catch:t=>ES(t)?t:new yS({kind:OS(e),rawCause:t})})});u.kind===`deadline`&&s(`deadline_exceeded`);let p=yield*bE(t);return yield*ee(te).pipe(g(v(yE(o,e.policy.timeoutMs,p))))}).pipe(Oe(()=>(s(`cancelled`),(te===void 0?C:S_(te).pipe(Xr(e.policy.abortGraceMs),pn)).pipe(g(sr(()=>ne?C:re(new mS({by:`operator`})).pipe(pn))))))).pipe(vn(e=>re(e).pipe(T(v))),rr(y(u)))})))}var SE=ym(()=>I([sm,om,cm,N,M,zh,Am(AbortSignal),F(SE),CE])),CE=fm(M,SE);function wE(e){return O(CE)(e)}var TE=fm(M,Zh),EE=O(P({samplingParams:k(TE),samplingParamsByThinkingLevel:k(P({off:k(TE),minimal:k(TE),low:k(TE),medium:k(TE),high:k(TE),xhigh:k(TE),max:k(TE)}))}));function DE(e){return{...e,...EE(e)}}function OE(e){if(e===void 0)return;let{onPayload:t,onProviderStreamEvent:n,onResponse:r,...i}=e,a={...i};return t!==void 0&&(a.onPayload=(e,n)=>t(wE(e),DE(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(wE(e),DE(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,DE(t))),a}var kE=async(e,t,n)=>{let{streamSimple:r}=await gi(async()=>{let{streamSimple:e}=await import(`./compat-oy1YdGOO.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,23,24]));return r(e,hi(t),OE(n))},AE=P({error:P({code:A(M),type:A(M)})});Wp(P({type:j(`response.failed`),response:AE})),Wp(U(AE)),Wp(P({type:j(`error`),status:A(N.check(th(),$m({minimum:100,maximum:599}))),code:A(M),error:A(AE.fields.error)})),O(Am(Uint8Array)),Wp(Fh.check($m({minimum:0,maximum:60}))),Wp(Fh.check(th(),$m({minimum:0,maximum:864e10}))),Wp(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Wp(j(`rejected`)),Wp(j(`0`)),Wp(Kh),Wp(P({type:j(`error`),error:P({type:j(`overloaded_error`)})}));var jE=[/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],ME=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,NE=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function PE(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!NE.some(t=>t.test(e.errorMessage))&&(jE.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&ME.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 FE(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function IE(e){return new RegExp(e.join(`|`),`i`)}var LE=IE([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`]),RE=IE(`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(`,`)),zE=6e4;function BE(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 VE=class extends Error{constructor(){super(`Aborted`)}};function HE(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new VE);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new VE)},{once:!0})})}async function UE(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||!WE(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=BE(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await HE(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof VE){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function WE(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!LE.test(t)&&RE.test(t)}var GE={assign:0,create:0,clone:0,discard:0,update:0};function KE(e){return JE(e,null)}function qE(e){return JE(typeof e,`object`)&&!KE(e)}function JE(e,t){return e===t}function YE(e){return JE(e,`__proto__`)||JE(e,`constructor`)||JE(e,`prototype`)}function XE(e,t){return YE(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function ZE(e){return Object.getOwnPropertyNames(e)}var QE={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function $E(){return QE}function eD(e){return $E().immutableTypes?Object.freeze(e):e}function tD(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 nD(e,t){return{...e,...t}}function rD(e,t,n={}){GE.create+=1;let r=nD(t,n);return eD($E().enumerableKind?nD(r,e):tD(r,e))}function iD(e){return qE(e)}function aD(e){return iD(e)&&XE(e,`~optional`)}function oD(e){return ZE(e).filter(t=>!aD(e[t]))}function sD(e,t={}){let n=oD(e);return rD({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var cD;(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`})(cD||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var lD=new Float64Array(1);new DataView(lD.buffer),new Uint8Array(lD.buffer),new TextEncoder;var uD=`-?(?:0|[1-9][0-9]*)`,dD=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function fD(e){return rD({"~kind":`String`},{type:`string`},e)}var pD=`^${uD}$`;`${dD}`;function mD(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var hD=[...mD(97,122),...mD(65,90)],gD=[`0`,...mD(49,57)];[...gD],[...hD,...gD],[...gD],new RegExp(pD);var _D={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},vD={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},yD=1e3,bD=Symbol(`Mule model limit`);function xD(e,t){return PE(e,t)}var SD=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),CD=(e,t)=>({kind:e,value:`mule_${e}_${rg()}`,parent:t}),wD=()=>C;function TD(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 ED=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function DD(e,t){return e.find(e=>e.descriptor.name===t.name)}function OD(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function kD(e,t,n,r,i){let a=CD(`tool_call`,r);return b(function*(){if(yield*i({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:a,call:t}),e===void 0){let e=ED(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*OD(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*zr(e.prepare(t));if(ke(o)){let e=ED(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*OD(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function AD(e,t,n,r){return b(function*(){let i,a;yield*vy(ry(e.tool.execute()),o=>ke(o)?(a=o.failure,C):i===void 0?o.success.type===`result`?(i=o.success.result,C):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):C);let o=a===void 0?i??ED(`Tool "${e.call.name}" returned no result`):ED(a.message),s={call:e.call,identity:e.identity,result:o};return yield*OD(s,t,n,r),s})}function jD(e,t,n,r){let i=TD(e.call,e.result),a=CD(`tool_result`,e.identity);return b(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:a,value:i}),yield*r({type:`message_end`,run:t,turn:n,message:a,value:i,data:e.result.data}),i})}function MD(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>DD(a,e)?.executionMode===`sequential`);return b(function*(){let t=e=>e.kind===`finalized`?x(e.value):AD(e,n,r,i),s=o?yield*Zr(e,e=>T(kD(DD(a,e),e,n,r,i),t)):yield*b(function*(){let o=yield*Zr(e,e=>kD(DD(a,e),e,n,r,i));return yield*Hn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*Zr(s,e=>jD(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var ND=e=>ED(`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 PD(e,t,n,r){return b(function*(){let i=yield*Zr(e,e=>b(function*(){let i=CD(`tool_call`,n),a={call:e,identity:i,result:ND(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*OD(a,t,n,r),a}));return yield*Zr(i,e=>jD(e,t,n,r))})}function FD(e,t){return fn({try:n=>{let r=()=>{t.abort(n.reason)};return n.aborted?r():n.addEventListener(`abort`,r,{once:!0}),Promise.resolve(e.next()).finally(()=>{n.removeEventListener(`abort`,r)})},catch:e=>SD(`model`,`Pi model stream failed`,e)})}function ID(e,t,n){return e.pipe(di({duration:t,orElse:()=>v(SD(`model`,n(),bD))}))}function LD(e,t,n,r,i,a){let o=CD(`message`,r),s,c={started:!1,terminal:void 0};return nr(b(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??vD.firstEventMs,vD.firstEventMs),d=Math.min(l?.attemptMs??vD.attemptMs,vD.attemptMs),f=Math.min(l?.outputBytes??vD.outputBytes,vD.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*v(SD(`model`,`Model stream limits must be positive safe integers`));let p=Date.now(),m=p,ee=0,te=0,ne=new TextEncoder,re=!1,ie=e=>SD(`model`,`Model ${e} after ${String(Date.now()-p)} ms (max provider gap ${String(Math.max(ee,Date.now()-m))} ms, streamed ${String(te)} bytes)`,bD),ae=t=>{let n=Date.now()-p,r=d-n,i=Math.min(re?vD.idleMs:u,e.modelStreamIdleTimeoutMs??vD.idleMs)-(Date.now()-m),a=r<=i?`attempt timed out`:re?`stream timed out (silence)`:`first event timed out`;return ID(t,Math.max(0,Math.min(r,i)),()=>ie(a).message)},oe=new AbortController,se={};yield*wr(()=>fn({try:()=>{if(oe.abort(`Mule model scope closed`),se.response===void 0)return Promise.resolve(!0);let e=se.response.then(async e=>{await Promise.all([se.iterator?.return?.(),e.result()])},()=>void 0);return new Promise(t=>{let n=setTimeout(()=>{t(!1)},yD);e.then(()=>{clearTimeout(n),t(!0)},()=>{clearTimeout(n),t(!1)})})},catch:e=>SD(`model`,`Pi model stream failed`,e)}).pipe(It(()=>!1),T(t=>t?C:e.onUndrained??C)));let ce=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,le={...e.streamOptions,maxRetries:0,signal:oe.signal};ce!==void 0&&(le.apiKey=ce);let ue=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*i({type:`model_prompt`,run:n,turn:r,attempt:a,systemPrompt:ue}));let de={systemPrompt:ue,messages:t},fe=(e.tools??[]).map(e=>e.descriptor);fe.length>0&&(de.tools=fe);let pe=yield*ae(fn({try:()=>{let t=e.stream??kE;return se.response=Promise.resolve(t(e.model,hi(de),le)),se.response},catch:e=>SD(`model`,`Pi model stream could not start`,e)})),me=pe[Symbol.asyncIterator]();se.iterator=me;let he=e=>{let a=Date.now();if(ee=Math.max(ee,a-m),m=a,re=!0,(e.type===`text_delta`||e.type===`thinking_delta`||e.type===`toolcall_delta`)&&(te+=ne.encode(e.delta).byteLength,te>f))return v(ie(`output limit exceeded`));switch(`partial`in e&&(s=e.partial),e.type){case`start`:return t.push(e.partial),c.started=!0,i({type:`message_start`,run:n,turn:r,message:o,value:e.partial});case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:return c.started&&(t[t.length-1]=e.partial),i({type:`message_update`,run:n,turn:r,message:o,value:e.partial,event:e});case`done`:return c.terminal=e.message,C;case`error`:return c.terminal=e.error,C}},ge=()=>ae(FD(me,oe)),_e=yield*ge();for(;!_e.done;)yield*he(_e.value),_e=yield*ge();let ve=c.terminal??(yield*ae(fn({try:()=>pe.result(),catch:e=>SD(`model`,`Pi model stream did not settle`,e)})));return c.started?t[t.length-1]=ve:(t.push(ve),yield*i({type:`message_start`,run:n,turn:r,message:o,value:ve})),{message:ve,identity:o}}).pipe(vn(l=>{if(l.cause!==bD)return v(l);let u={role:`assistant`,content:s?.content??[],api:e.model.api,provider:e.model.provider,model:e.model.id,usage:s?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,timestamp:Date.now(),errorMessage:e.retry?.enabled&&a>e.retry.maxRetries?`The model failed ${String(a)} times on this conversation: ${l.message}`:l.message};return b(function*(){return c.started?t[t.length-1]=u:(t.push(u),yield*i({type:`message_start`,run:n,turn:r,message:o,value:u})),{identity:o,message:u,limitReached:!0}})})))}function RD(e,t,n,r,i,a){return b(function*(){let o=e.retry===void 0?void 0:{...e.retry};if(o?.enabled&&[o.maxRetries,o.baseDelayMs,o.maxAgentDelayMs??6e4].some(e=>!Number.isSafeInteger(e)||e<0))return yield*v(SD(`model`,`Retry policy requires non-negative safe-integer counts and delays`));let s,c=Math.min(o?.maxRetries??0,a?.maxAttempts??1/0),l=a===void 0?0:a.attempt+ +(a.phase===`dispatched`),u=a?.attempt??0,d=!1,f=a?.message?.errorMessage,p=t=>e.onRetry===void 0?C:e.onRetry(t),m=(e,t)=>b(function*(){d=!0,yield*p(t===void 0?{type:`retry_finished`,run:n,turn:r,attempt:u,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:u,success:e,finalError:t})}),ee=e=>b(function*(){yield*jn(Math.max(0,e-Date.now())),yield*p({type:`retry_attempt_started`,run:n,turn:r,attempt:u})}),te=(e,t)=>b(function*(){if(o===void 0)return yield*v(SD(`model`,`Retry policy is unavailable`));u++,f=e;let i=Math.max(BE(o,u),t!==void 0&&Number.isSafeInteger(t)&&t>=0&&t<=6e4?t:0),a=Math.min(1e3,i/4,Math.max(0,6e4-i)),s=i+Math.floor(Math.random()*a),l=Date.now()+s;return{type:`retry_scheduled`,run:n,turn:r,attempt:u,maxAttempts:c,delayMs:s,dueAt:l,errorMessage:f}});return yield*b(function*(){if(a!==void 0){if(!Number.isSafeInteger(a.attempt)||a.attempt<0||a.maxAttempts!==void 0&&(!Number.isSafeInteger(a.maxAttempts)||a.maxAttempts<0)||a.phase===`waiting`&&(!Number.isSafeInteger(a.dueAt)||a.dueAt<0))return yield*v(SD(`model`,`Invalid model retry continuation`));if(!o?.enabled||u>c||a.phase===`dispatched`&&u>=c)return yield*m(!1,`Model retry budget exhausted after restart`),a.message===void 0?yield*v(SD(`model`,`Model retry budget exhausted after restart`)):{message:a.message};if(a.phase===`waiting`)yield*ee(a.dueAt);else{let e={...yield*te(`Model request interrupted by a restart`),delayMs:0,dueAt:Date.now()};yield*p(e),yield*ee(e.dueAt)}}for(;;){if(s!==void 0){let e=t.indexOf(s.message);e!==-1&&t.splice(e,1)}let a=yield*LD(e,t,n,r,i,++l);s=a;let f=a.message,m;if(f.stopReason===`error`&&o?.enabled&&u<c&&(yield*oi({try:()=>a.limitReached===!0||e.retryable(f),catch:e=>SD(`model`,`Typed model retry decision failed`,e)}))){let t=yield*oi({try:()=>e.retryAfterMs?.(f),catch:e=>SD(`model`,`Model retry delay observation failed`,e)});m=yield*te(f.errorMessage??`Unknown error`,t)}if(m===void 0&&(f.stopReason===`error`||u>0)){let e={type:`retry_finished`,run:n,turn:r,attempt:u,success:f.stopReason!==`error`&&f.stopReason!==`aborted`};m=f.stopReason===`error`&&f.errorMessage!==void 0?{...e,finalError:f.errorMessage}:e}if(yield*i({type:`message_end`,run:n,turn:r,message:a.identity,value:f,retry:m}),m?.type===`retry_finished`&&(d=!0),m!==void 0&&u>0&&(yield*p(m)),m?.type!==`retry_scheduled`)return s;yield*ee(m.dueAt)}}).pipe(Oe(()=>u===0||d?C:m(!1,f)))})}var zD=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function BD(e,t,n,r,i,a){return Zr(e,e=>b(function*(){let o=CD(`message`,i);t.push(e),n.push(e),yield*a({type:`message_start`,run:r,turn:i,message:o,value:e}),yield*a({type:`message_end`,run:r,turn:i,message:o,value:e})})).pipe(pn)}function VD(e,t,n,r,i,a,o,s){return b(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*BD(a,t,n,r,i,o);let c=yield*RD(e,t,r,i,o,s),l=zD(c.message)!==`completed`,u=c.message.content.filter(e=>e.type===`toolCall`),d=u.length===0||l?{messages:[],terminate:!1}:c.message.stopReason===`length`?{messages:yield*PD(u,r,i,o),terminate:!1}:yield*MD(u,e,r,i,o);t.push(...d.messages),n.push(c.message,...d.messages),yield*o({type:`turn_end`,run:r,turn:i,message:c.message,toolResults:d.messages});let f={message:c.message,toolResults:d.messages,terminate:d.terminate};return c.limitReached&&c.message.errorMessage!==void 0?{...f,modelLimitReason:c.message.errorMessage}:f})}function HD(e,t,n,r,i,a){let o=CD(`turn`,i);return b(function*(){if(zD(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*Zr(t.tools,n=>b(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=DD(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*kD(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*AD(e,i,o,a)}else s={call:n.call,identity:CD(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?ND(n.call):ED(`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*OD(s,i,o,a);return{message:yield*jD(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 UD(e,t,n,r){return b(function*(){if(e.shouldStopAfterTurn!==void 0&&(yield*e.shouldStopAfterTurn({message:t.message,toolResults:t.toolResults,context:n,newMessages:r})))return{continue:!1,pending:[]};let i=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()];if(t.message.content.some(e=>e.type===`toolCall`)&&!t.terminate||i.length>0)return{continue:!0,pending:i};let a=e.getFollowUpMessages===void 0?[]:[...yield*e.getFollowUpMessages()];return{continue:a.length>0,pending:a}})}function WD(e,t,n,r,i,a,o){return b(function*(){yield*a({type:`run_end`,run:e,terminal:t,outcome:i});let s={status:i,run:e,terminal:t,message:n,messages:r};return o===void 0?s:{...s,modelLimitReason:o}})}function GD(e,t=wD){return b(function*(){let n=yield*A_(1),r={started:!1,ended:!1},i=e=>sr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(In(()=>y(()=>{e.type===`run_start`&&(r.started=!0)}))),a=CD(`run`),o=CD(`terminal`,a);return yield*qD(e,i,a,o).pipe(Me(e=>{let t=KD(e);return!r.started||r.ended||t===void 0?C:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Be)}))})}function KD(e){if(ca(e))return;if(Ki(e.cause))return`cancelled`;let t=Xi(e.cause);if(!(Nr(t)&&t.value.phase===`listener`))return`failed`}function qD(e,t,n,r){return b(function*(){let i=[...e.messages],a=[],o=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()],s,c;yield*t({type:`run_start`,run:n});let l=e.resume?.kind===`retry`?e.resume:void 0;if(e.resume?.kind===`assistant`){let s=yield*HD(e,e.resume,i,a,n,t),c=zD(s.message),l=c===`completed`?yield*UD(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*WD(n,r,s.message,a,c,t);o.push(...l.pending)}do{let u=yield*VD(e,i,a,n,CD(`turn`,n),o,t,l);l=void 0,s=u.message;let d=zD(u.message);if(d!==`completed`)return yield*WD(n,r,u.message,a,d,t,u.modelLimitReason);if(e.prepareNextTurn!==void 0&&!u.terminate&&u.message.content.some(e=>e.type===`toolCall`)){let t=yield*e.prepareNextTurn({message:u.message,toolResults:u.toolResults,context:i,newMessages:a});t!==void 0&&i.splice(0,i.length,...t)}let f=yield*UD(e,u,i,a);o=[...f.pending],c=f.continue}while(c);return yield*WD(n,r,s,a,`completed`,t)})}var JD={run:GD},YD=class{#e=new Map;#t;constructor(e=8){this.#t=e}push(e,t){let n=this.#e.get(e)??[];if(n.length>=this.#t)throw new bS({namespace:`execute`,operation:`images`,cause:{kind:`Unavailable`,message:`Image collector cap reached for this execution (max ${String(this.#t)} images). Process images one at a time or write them to files.`}});let r=`img_${String(n.length)}`;return n.push(Object.freeze({...t})),this.#e.set(e,n),r}drain(e){let t=this.#e.get(e);return t===void 0?[]:(this.#e.delete(e),t)}dispose(e){this.#e.delete(e)}},XD=8192,ZD=XD*4,QD=new TextEncoder,$D=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),eO=class e{wake;#e={stdout:{decoder:$D(),pending:new Uint8Array},stderr:{decoder:$D(),pending:new Uint8Array}};#t=$D();#n=Array.from({length:XD},()=>void 0);#r=0;#i=0;#a=0;#o=0;#s=0;#c=0;#l=!1;#u=!1;constructor(e){this.wake=e}static make(){return Bg({capacity:1,strategy:`dropping`}).pipe(Ce(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+=ZD){let r=t.subarray(e,e+ZD),i=n.decoder.decode(r,{stream:!0}),a=new Uint8Array(n.pending.length+r.length);a.set(n.pending),a.set(r,n.pending.length);let o=this.#f(a);n.pending=a.slice(a.length-o),this.#h(i,a.length-o,a)}this.#l=!0,Wg(this.wake,void 0)}#d(e,t){let n=this.#t.decode(e.subarray(0,t),{stream:!0});return this.#t.decode(),n}#f(e){for(let t=1;t<=Math.min(3,e.length);t++){let n=e.subarray(e.length-t);if(this.#d(n,n.length).length===0)return t}return 0}#p(){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);this.#n[this.#r]=void 0,this.#r=(this.#r+1)%XD,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 QD.encode(i).length>=t&&i.split(`
|
|
18
|
+
`;case 114:return`\r`;case 120:return String.fromCharCode(this.readHexChar(2));case 117:return pC(this.readCodePoint());case 116:return` `;case 98:return`\b`;case 118:return`\v`;case 102:return`\f`;case 13:this.input.charCodeAt(this.pos)===10&&++this.pos;case 10:return this.options.locations&&(this.lineStart=this.pos,++this.curLine),``;case 56:case 57:if(this.strict&&this.invalidStringToken(this.pos-1,`Invalid escape sequence`),e){var n=this.pos-1;this.invalidStringToken(n,`Invalid escape sequence in template string`)}default:if(t>=48&&t<=55){var r=this.input.substr(this.pos-1,3).match(/^[0-7]+/)[0],i=parseInt(r,8);return i>255&&(r=r.slice(0,-1),i=parseInt(r,8)),this.pos+=r.length-1,t=this.input.charCodeAt(this.pos),(r!==`0`||t===56||t===57)&&(this.strict||e)&&this.invalidStringToken(this.pos-1-r.length,e?`Octal literal in template string`:`Octal literal in strict mode`),String.fromCharCode(i)}return nC(t)?(this.options.locations&&(this.lineStart=this.pos,++this.curLine),``):String.fromCharCode(t)}},Q.readHexChar=function(e){var t=this.pos,n=this.readInt(16,e);return n===null&&this.invalidStringToken(t,`Bad character escape sequence`),n},Q.readWord1=function(){this.containsEsc=!1;for(var e=``,t=!0,n=this.pos,r=this.options.ecmaVersion>=6;this.pos<this.input.length;){var i=this.fullCharCodeAtPos();if(YS(i,r))this.pos+=i<=65535?1:2;else if(i===92){this.containsEsc=!0,e+=this.input.slice(n,this.pos);var a=this.pos;this.input.charCodeAt(++this.pos)!==117&&this.invalidStringToken(this.pos,`Expecting Unicode escape sequence \\uXXXX`),++this.pos;var o=this.readCodePoint();(t?JS:YS)(o,r)||this.invalidStringToken(a,`Invalid Unicode escape`),e+=pC(o),n=this.pos}else break;t=!1}return e+this.input.slice(n,this.pos)},Q.readWord=function(){var e=this.readWord1(),t=J.name;return this.keywords.test(e)&&(t=$S[e]),this.finishToken(t,e)},VC.acorn={Parser:VC,version:`8.18.0`,defaultOptions:vC,Position:hC,SourceLocation:gC,getLineInfo:_C,Node:uw,TokenType:K,tokTypes:J,keywordTypes:$S,TokContext:tw,tokContexts:nw,isIdentifierChar:YS,isIdentifierStart:JS,Token:tT,isNewLine:nC,lineBreak:eC,lineBreakG:tC,nonASCIIwhitespace:iC};function aT(e,t){return VC.parse(e,t)}_(()=>hn(`ok`,[ln({ok:yr(!0),value:xt()}),ln({ok:yr(!1),error:ln({kind:yr(`guest_threw`),name:w().max(80),message:w().max(512),transportMessage:w().max(512).optional()})})]));var oT=_(()=>w().regex(/^[A-Za-z][A-Za-z0-9_]*$/u)),sT=oT.refine(e=>{if(e===`env`)return!1;try{return aT(`let ${e};`,{ecmaVersion:`latest`,sourceType:`module`}),!0}catch(e){if(!(e instanceof SyntaxError))throw e;return!1}},`Invalid sandbox transport alias`);_(()=>si(sT,Er(oT).min(1))),_(()=>si(sT,Er(w().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/u))));var cT=L([`read`,`write`]),lT=cm,uT=P({access:A(cT),confirm:A(lT)}),dT=L([`none`,`read`,`write`]),fT=D(uT),pT=D(dT);function mT(e){let t=fT({access:e.access,confirm:e.confirm});if(Ae(t))throw new G(`Access labels must be access: "read" | "write" and confirm: boolean`);return{access:t.success.access??`write`,confirm:t.success.confirm??!1}}function hT(e,t){let n=`${t.module}.${t.operation}`;switch(e){case`not-granted`:return`${n} is not granted to this Agent.`;case`read-only`:return`${n} changes something, and this Agent has read-only access to ${t.module}.`;case`confirmation-unavailable`:return`${n} needs a person's approval, and no one can be asked here.`;case`declined`:return`${n} was not approved.`}}function gT(e,t){return Object.freeze({refused:!0,module:t.module,operation:t.operation,reason:e,message:hT(e,t)})}function _T(e,t,n){let r=e.sessionGrants?.(t),i=r!==void 0&&Object.hasOwn(r,n)?r:e.grants;if(i===void 0||!Object.hasOwn(i,n))return e.required?.includes(n)===!0?`none`:e.defaultGrant??`write`;let a=pT(i[n]);return Wt(a)?a.success:`none`}async function vT(e,t,n,r,i){let a=await yT(e,t,n,r,i);return a!==void 0&&e.onRefused?.(a,t),a}async function yT(e,t,n,r,i){await e.beforeCall?.(i),i.throwIfAborted();let a=bT(e,t,n);if(a!==void 0)return a;if(!(!n.confirm&&(e.confirmWrites!==!0||n.access===`read`)))return e.confirm===void 0?gT(`confirmation-unavailable`,n):await e.confirm({module:n.module,operation:n.operation,access:n.access,sessionId:t.sessionId,input:r},i)?(await e.beforeCall?.(i),i.throwIfAborted(),bT(e,t,n)):gT(`declined`,n)}function bT(e,t,n){let r=_T(e,t,n.module);if(r===`none`)return gT(`not-granted`,n);if(r===`read`&&n.access!==`read`)return gT(`read-only`,n)}function xT(e,t,n){let r={module:e.module,operation:e.descriptor.name,...mT(e)};return{...e,prepare:i=>pn({try:e=>vT(t,n,r,i.arguments,e),catch:()=>({message:`Access check failed`})}).pipe(T(t=>t===void 0?e.prepare(i):x({execute:()=>Gv({type:`result`,result:{content:[{type:`text`,text:JSON.stringify(t)}],isError:!1}})})))}}var ST=Cs();async function CT(e){let t=await Kn(e);if(ca(t))return{value:t.value};let n=Yi(t.cause);if(Ae(n))throw Ji(t.cause);return{issues:ST(n.success.issue).issues}}function wT(e){let t=Xh(e),n=Bp(t)[`~standard`].jsonSchema,r=Hp(t),i=qp(t);return Object.freeze({description:{"~standard":{jsonSchema:{input:n.input,output:n.input}}},decode:e=>CT(r(e)),encode:e=>CT(i(e))})}function TT(e){let t=async t=>e[`~standard`].validate(t);return Object.freeze({description:e,decode:t,encode:t})}function ET(e){return em(e)?wT(e):TT(e)}var DT=Symbol(`mycelium.operation`),OT=Symbol(`mycelium.module`),kT=new WeakMap,AT=new WeakMap;function jT(e){let t=Object.freeze({[DT]:!0}),n=ET(e.input),r=e.output===void 0?void 0:ET(e.output),i={replay:e.replay??`unsafe`,...mT(e),input:n.description,invoke:async(t,i)=>{let a=await n.decode(t);if(a.issues!==void 0)throw new cS(a.issues);let o=await e.execute(a.value,i);if(r===void 0)return o;let s=await r.encode(o);if(s.issues!==void 0)throw new _S({reason:`Capability output failed its declared schema`,rawCause:new lS(s.issues)});return s.value}};e.description!==void 0&&(i.description=e.description),r!==void 0&&(i.output=r.description);let a=Object.freeze(i);return kT.set(t,a),t}function MT(e){let t=Er(oT).safeParse(e.namespace??[]);if(!t.success)throw new G(`Invalid module namespace`);let n=Object.freeze({[OT]:!0}),r={id:e.id,grantKey:e.id,name:e.name??e.id,namespace:Object.freeze(t.data),operations:Object.freeze({...e.operations})};e.description!==void 0&&(r.description=e.description);let i=Object.freeze(r);return AT.set(n,i),n}function NT(e){return AT.has(e)}function PT(e){return kT.get(e)}function FT(e){return AT.get(e)}function IT(e,t,n){let r=FT(e);if(r===void 0)throw new G(`Unknown module registration`);let i={};for(let[e,a]of Object.entries(r.operations)){let r=n===``?e:`${n}.${e}`;if(NT(a)){let n=FT(a);if(n===void 0)throw new G(`Unknown child module registration`);i[e]=IT(a,t,[r,...n.namespace].join(`.`));continue}let o=PT(a);if(o===void 0)throw new G(`Unknown operation registration: ${e}`);let s=Object.freeze({[DT]:!0});kT.set(s,Object.freeze({...o,invoke:async(e,n)=>{let i=await t({operation:r,context:n});return i.kind===`refuse`?i.value:await o.invoke(e,n)}})),i[e]=s}return LT(MT(r.description===void 0?{id:r.id,name:r.name,namespace:r.namespace,operations:i}:{id:r.id,name:r.name,namespace:r.namespace,description:r.description,operations:i}),r.grantKey)}function LT(e,t){let n=FT(e);if(n===void 0)throw new G(`Unknown module registration`);let r=Object.freeze({[OT]:!0});return AT.set(r,Object.freeze({...n,grantKey:t})),r}function RT(e,t){if(t.length===0||t.length>160)throw new G(`Grant key must be non-empty and bounded`);return LT(e,t)}function zT(e,t){return IT(e,t,``)}function BT(e,t){return e<t?-1:+(e>t)}function VT(e){return e instanceof Error?e.message:`Capability declarations could not be compiled`}var HT=160;function UT(e){if(e.length===0||e.length>HT)throw new G(`Module id must be non-empty and bounded`)}function WT(e){if(!e.split(`.`).every(e=>oT.safeParse(e).success))throw new G(`Operation key must be a path segment or a dotted relative path`)}function GT(e){let t=e.replace(/[^A-Za-z0-9_]/g,`_`);return/^[A-Za-z]/.test(t)?t:`module_${t}`}function KT(e){let t=GT(e);return sT.safeParse(t).success?t:`module_${t}`}function qT(e,t){let n=new Set([`forage`,`env`]),r=new Map;for(let i of e){let e=t===`logical`?i.namespace:[],a=t===`logical`?GT(i.name):KT(i.name),o=t=>[...e,t].join(`.`),s=a,c=2;for(;n.has(o(s));)s=`${a}_${String(c)}`,c+=1;n.add(o(s)),r.set(i.id,s)}return r}var JT=14695981039346656037n,YT=1099511628211n,XT=18446744073709551615n;function ZT(e,t){let n=e,r=BigInt(t.length);for(let e=0;e<8;e+=1)n=(n^r&255n)*YT&XT,r>>=8n;for(let e=0;e<t.length;e+=1){let r=t.charCodeAt(e);n=(n^BigInt(r&255))*YT&XT,n=(n^BigInt(r>>>8&255))*YT&XT}return n}function QT(e,t,n){let r=ZT(JT,e),i=[...t.entries()].sort(([e],[t])=>BT(e,t));for(let[e,t]of i)r=ZT(r,e),r=ZT(r,t);let a=[...n].sort((e,t)=>BT(e.id,t.id));for(let e of a)r=ZT(r,e.id),r=ZT(r,e.version);return`installed-${r.toString(16).padStart(16,`0`)}`}function $T(){return[tS,eS,nS]}function eE(e,t,n,r,i,a=[]){return Object.entries(t.operations).flatMap(([t,o])=>{if(WT(t),NT(o)){let s=FT(o);if(s===void 0)throw new G(`Unknown child module registration`);return eE(e,s,n,[...r,t,...s.namespace],s.description??i,[...a,t,...s.namespace])}let s=PT(o);if(s===void 0)throw new G(`Unknown operation registration: ${[...r,t].join(`.`)}`);return[Object.freeze({grantKey:e,path:[...r,t].join(`.`),namespace:n,name:[...a,t].join(`.`),moduleDescription:i,operation:s})]})}function tE(e,t=[]){let n=e.map(e=>{let t=FT(e);if(t===void 0)throw new G(`Unknown module registration`);return UT(t.id),t}).sort((e,t)=>BT(e.id,t.id)),r=new Set;for(let e of n){if(r.has(e.id))throw new G(`Duplicate module id: ${e.id}`);r.add(e.id)}let i=qT(n,`transport`),a=qT(n,`logical`),o=Object.freeze(Object.fromEntries(n.map(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=a.get(e.id);if(n===void 0)throw new G(`Missing logical alias: ${e.id}`);return[t,Object.freeze([...e.namespace,n])]}))),s=n.flatMap(e=>{let t=i.get(e.id);if(t===void 0)throw new G(`Missing module alias: ${e.id}`);let n=o[t];if(n===void 0)throw new G(`Missing namespace path: ${e.id}`);return eE(e.grantKey,e,t,n,e.description)}).sort((e,t)=>BT(e.path,t.path)),c=new Set(s.map(e=>e.path));if(c.size!==s.length)throw new G(`Duplicate operation path`);for(let e of $T()){if(c.has(e.path))throw new G(`Reserved intrinsic path: ${e.path}`);c.add(e.path)}for(let e of c){let t=e.split(`.`);for(let n=1;n<t.length;n+=1)if(c.has(t.slice(0,n).join(`.`)))throw new G(`Operation conflicts with namespace: ${e}`)}let l;try{l=Xx({revision:`prepared-content-stamp`,operations:[...s.map(({path:e,moduleDescription:t,operation:n})=>{let r={path:e,input:n.input};return n.description!==void 0&&(r.description=n.description),n.output!==void 0&&(r.output=n.output),t!==void 0&&(r.instructions=t),r}),...$T()]})}catch(e){throw new G(VT(e))}let u=QT(l.stamp(),i,t),d=Object.freeze({revision:u,search:l.search,describe:l.describe,list:l.list,stamp:l.stamp}),f=Object.freeze(Object.fromEntries([...i.entries()].map(([e,t])=>[t,e])));return Object.freeze({revision:u,catalog:d,operations:Object.freeze(s),moduleAliases:f,namespacePaths:o})}function nE(){return null}var rE=bn(),iE=_(()=>Qr([wn(),w(),pr(),Mn()])),aE=_(()=>si(w(),xt())),oE=_(()=>FS.extend({timeoutMs:Mn().int().min(1).max(9e5).optional(),abortGraceMs:Mn().int().min(1).max(3e4).optional()}).optional()),sE=64,cE=262144,lE=new TextEncoder,uE=e=>{e(x(void 0))};function dE(e){let t=oE.safeParse(e);if(!t.success)throw new G(`Execution policy is invalid`);let n=t.data?.timeoutMs??18e4;return Object.freeze({timeoutMs:n,abortGraceMs:t.data?.abortGraceMs??5e3,...IS({sandboxCapacity:t.data?.sandboxCapacity,admissionWaitMs:t.data?.admissionWaitMs??n},(t.data?.sandboxCapacity,void 0))})}function fE(e){return b(function*(){let t=yield*A_(e);return Object.freeze({createGroup:()=>{let e=0,n=new Set,r=$n(t=>e===0?(t(x(void 0)),y(()=>void 0)):(n.add(t),y(()=>n.delete(t))));return Object.freeze({start:r=>ne(i=>y(()=>{e+=1}).pipe(g(re(i(t.withPermits(1)(r)).pipe(rr(y(()=>{if(--e,e===0){let e=[...n];n.clear(),e.forEach(uE)}}))))))),awaitIdle:r})}})})}function pE(e,t=0){if(t>sE)throw Error(`JSON value exceeds the nesting bound`);let n=iE.safeParse(e);if(n.success)return n.data;if(Array.isArray(e))return e.map(e=>pE(e,t+1));let r=aE.safeParse(e);if(!r.success)throw r.error;return Object.fromEntries(Object.entries(r.data).filter(([,e])=>e!==void 0).map(([e,n])=>[e,pE(n,t+1)]))}function mE(e){return rE.parse(pE(e))}function hE(e){let t=JSON.stringify(mE(e)),n=lE.encode(t).byteLength;if(n>cE)throw new vS({size:n});return Object.freeze({text:t})}function gE(e,t){return Object.freeze(Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Object.freeze(Object.fromEntries(Object.entries(n).map(([n,r])=>[n,async i=>{t();try{return mE(await r(i))}catch(t){throw ES(t)?t:t instanceof tx?new bS({namespace:e,operation:n,cause:{kind:`Forage`,message:t.message},rawCause:t}):t instanceof cS?new bS({namespace:e,operation:n,cause:{kind:`InvalidInput`,message:`Invalid operation input: ${Rt({issues:t.issues})}; use forage.describe`},rawCause:t}):t}}])))])))}function _E(e){return $n(t=>{let n=t.bind(void 0,C);return e.aborted?n():e.addEventListener(`abort`,n,{once:!0}),y(e.removeEventListener.bind(e,`abort`,n))})}function vE(e,t){if(e===void 0)return()=>void 0;let n=t.bind(void 0);return e.aborted?(n(),()=>void 0):(e.addEventListener(`abort`,n,{once:!0}),e.removeEventListener.bind(e,`abort`,n))}function yE(e,t,n){return e===`deadline_exceeded`?new fS({limitMs:t,elapsedMs:n??0}):new mS({by:`caller`})}function bE(e){return Ma.pipe(we(t=>t-e))}function xE(e){return Ma.pipe(T(t=>sr(()=>{let n=e.executionId,r=new AbortController,i=t,a={kind:`waiting`},o,s=e=>{o===void 0&&a.kind!==`refused`&&(o=e,r.abort())},c=t=>{let n=new pS({capacity:e.policy.capacity,waitedMs:Math.max(0,t-i)});return a={kind:`refused`,failure:n},n},l=()=>{if(r.signal.aborted)throw yE(o,e.policy.timeoutMs)},u=vE(e.callerSignal,()=>{s(`cancelled`)}),d=t+e.policy.timeoutMs,f={executionId:n,deadlineAt:d,signal:r.signal,images:e.images};e.toolCallId!==void 0&&Object.assign(f,{toolCallId:e.toolCallId}),e.output!==void 0&&Object.assign(f,{output:e.output});let p=Object.freeze(f),m=sr(()=>Ma.pipe(T(u=>a.kind===`refused`?v(a.failure):(u>=d&&s(`deadline_exceeded`),r.signal.aborted?bE(t).pipe(T(t=>v(yE(o,e.policy.timeoutMs,t)))):u>=i+e.policy.waitMs?v(c(u)):(a={kind:`admitted`},e.sandbox.execute(Object.freeze({executionId:n,code:e.code,timeoutMs:e.policy.timeoutMs,bindings:gE(e.createBindings(p),l),modules:e.modules,namespacePaths:e.namespacePaths,sessionId:e.sessionId}),r.signal).pipe(Br(e=>Ki(e)?Zt(e):v(DS(Ji(e)))))))))),ee=t=>S_(t).pipe(di({duration:e.policy.abortGraceMs,orElse:()=>v(o===`deadline_exceeded`?new fS({limitMs:e.policy.timeoutMs,elapsedMs:e.policy.timeoutMs,acknowledged:!1}):new mS({by:`caller`,acknowledged:!1}))})),te,ne=!1,re=r=>(ne=!0,bE(t).pipe(T(t=>{let i=DS(r),a=i instanceof fS?new fS({limitMs:i.limitMs,elapsedMs:t,acknowledged:i.acknowledged}):i,o=SS(a,n),s=si(w(),bn()).parse(kS(a));s.ref=n;let c={kind:`sandbox_failure`,ref:n,executionId:n,adapter:e.sandbox.adapter??`effect`,buildSha:e.sandbox.buildSha??nE(),tag:o._tag,fields:s,healthAlert:o._tag===`Unknown`},l=sr(()=>e.sandbox.onFailure?.(c)??C);return nt(`sandbox_failure`,c).pipe(fr({executionId:n,ref:n,adapter:c.adapter,tag:c.tag,buildSha:c.buildSha}),g(o._tag===`Unknown`?po(mo(fo(`sandbox_unknown`),{adapter:c.adapter}),1).pipe(g(nt(`sandbox_health_alert`).pipe(fr({ref:n,adapter:c.adapter})))):C),g(l.pipe(Br(e=>nt(`sandbox_failure_record_failed`,e)))),Ar(o))})));return b(function*(){if(r.signal.aborted){let n=yield*bE(t);return yield*v(yE(o,e.policy.timeoutMs,n))}i=yield*Ma,te=yield*e.backingWork.start(m);let n=yield*Ma,l=jn(Math.max(0,i+e.policy.waitMs-n)).pipe(g(Ma),T(e=>a.kind===`admitted`?Nt:a.kind===`refused`?x({kind:`busy`,failure:a.failure}):r.signal.aborted?x({kind:`cancelled`}):e>=d?(s(`deadline_exceeded`),x({kind:`deadline`})):x({kind:`busy`,failure:c(e)}))),u=yield*Dn(b_(te).pipe(we(e=>Object.freeze({kind:`settled`,exit:e}))),Dn(jn(Math.max(0,d-n)).pipe(g(y(()=>(s(`deadline_exceeded`),Object.freeze({kind:`deadline`}))))),Dn(_E(r.signal).pipe(Ar(Object.freeze({kind:`cancelled`}))),l))),f=a.kind===`refused`?a.failure:u.kind===`busy`?u.failure:void 0;if(f!==void 0)return yield*ee(te).pipe(g(v(f)));if(u.kind===`settled`&&o===void 0)return yield*xe(u.exit,{onFailure:Zt,onSuccess:e=>oi({try:()=>hE(e),catch:t=>ES(t)?t:new yS({kind:OS(e),rawCause:t})})});u.kind===`deadline`&&s(`deadline_exceeded`);let p=yield*bE(t);return yield*ee(te).pipe(g(v(yE(o,e.policy.timeoutMs,p))))}).pipe(ke(()=>(s(`cancelled`),(te===void 0?C:S_(te).pipe(Xr(e.policy.abortGraceMs),mn)).pipe(g(sr(()=>ne?C:re(new mS({by:`operator`})).pipe(mn))))))).pipe(yn(e=>re(e).pipe(T(v))),rr(y(u)))})))}var SE=ym(()=>I([sm,om,cm,N,M,zh,Am(AbortSignal),F(SE),CE])),CE=fm(M,SE);function wE(e){return O(CE)(e)}var TE=fm(M,Zh),EE=O(P({samplingParams:k(TE),samplingParamsByThinkingLevel:k(P({off:k(TE),minimal:k(TE),low:k(TE),medium:k(TE),high:k(TE),xhigh:k(TE),max:k(TE)}))}));function DE(e){return{...e,...EE(e)}}function OE(e){if(e===void 0)return;let{onPayload:t,onProviderStreamEvent:n,onResponse:r,...i}=e,a={...i};return t!==void 0&&(a.onPayload=(e,n)=>t(wE(e),DE(n))),n!==void 0&&(a.onProviderStreamEvent=(e,t)=>n(wE(e),DE(t))),r!==void 0&&(a.onResponse=(e,t)=>r(e,DE(t))),a}var kE=async(e,t,n)=>{let{streamSimple:r}=await gi(async()=>{let{streamSimple:e}=await import(`./compat-bF01jZNd.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,23,24]));return r(e,hi(t),OE(n))},AE=P({error:P({code:A(M),type:A(M)})});Wp(P({type:j(`response.failed`),response:AE})),Wp(U(AE)),Wp(P({type:j(`error`),status:A(N.check(th(),$m({minimum:100,maximum:599}))),code:A(M),error:A(AE.fields.error)})),O(Am(Uint8Array)),Wp(Fh.check($m({minimum:0,maximum:60}))),Wp(Fh.check(th(),$m({minimum:0,maximum:864e10}))),Wp(L([`five_hour`,`seven_day`,`seven_day_opus`,`seven_day_sonnet`])),Wp(j(`rejected`)),Wp(j(`0`)),Wp(Kh),Wp(P({type:j(`error`),error:P({type:j(`overloaded_error`)})}));var jE=[/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],ME=/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,NE=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];function PE(e,t){return!!(e.stopReason===`error`&&e.errorMessage&&!NE.some(t=>t.test(e.errorMessage))&&(jE.some(t=>t.test(e.errorMessage))||e.provider===`cerebras`&&ME.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 FE(e,t){return e.stopReason===`length`&&t>0&&e.usage.output<t}function IE(e){return new RegExp(e.join(`|`),`i`)}var LE=IE([`GoUsageLimitError`,`FreeUsageLimitError`,`Monthly usage limit reached`,`available balance`,`insufficient_quota`,`out of budget`,`quota exceeded`,`billing`,`subscription_sharing_usage_limit_exceeded`]),RE=IE(`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(`,`)),zE=6e4;function BE(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 VE=class extends Error{constructor(){super(`Aborted`)}};function HE(e,t){return new Promise((n,r)=>{if(t?.aborted){r(new VE);return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(new VE)},{once:!0})})}async function UE(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||!WE(s))return o&&await r?.onRetryFinished?.(!1,o.attempt,s.errorMessage),s;a++,o={attempt:a,errorMessage:s.errorMessage||`Unknown error`};let c=BE(t,a);await r?.onRetryScheduled?.(a,i,c,o.errorMessage);try{await HE(c,n)}catch(e){if(await r?.onRetryFinished?.(!1,a,o.errorMessage),e instanceof VE){let{errorMessage:e,...t}=s;return{...t,stopReason:`aborted`}}throw e}await r?.onRetryAttemptStart?.()}}function WE(e){if(e.stopReason!==`error`||!e.errorMessage)return!1;let t=e.errorMessage;return!LE.test(t)&&RE.test(t)}var GE={assign:0,create:0,clone:0,discard:0,update:0};function KE(e){return JE(e,null)}function qE(e){return JE(typeof e,`object`)&&!KE(e)}function JE(e,t){return e===t}function YE(e){return JE(e,`__proto__`)||JE(e,`constructor`)||JE(e,`prototype`)}function XE(e,t){return YE(t)?Object.prototype.hasOwnProperty.call(e,t):t in e}function ZE(e){return Object.getOwnPropertyNames(e)}var QE={immutableTypes:!1,maxErrors:8,maxInstantiationCount:128,useAcceleration:!0,exactOptionalPropertyTypes:!1,enumerableKind:!1,correctiveParse:!1,unionPrioritySort:!0};function $E(){return QE}function eD(e){return $E().immutableTypes?Object.freeze(e):e}function tD(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 nD(e,t){return{...e,...t}}function rD(e,t,n={}){GE.create+=1;let r=nD(t,n);return eD($E().enumerableKind?nD(r,e):tD(r,e))}function iD(e){return qE(e)}function aD(e){return iD(e)&&XE(e,`~optional`)}function oD(e){return ZE(e).filter(t=>!aD(e[t]))}function sD(e,t={}){let n=oD(e);return rD({"~kind":`Object`},{type:`object`,...n.length>0?{required:n}:{},properties:e},t)}var cD;(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`})(cD||={}),Array.from({length:256}).map((e,t)=>BigInt(t));var lD=new Float64Array(1);new DataView(lD.buffer),new Uint8Array(lD.buffer),new TextEncoder;var uD=`-?(?:0|[1-9][0-9]*)`,dD=`-?(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?`;function fD(e){return rD({"~kind":`String`},{type:`string`},e)}var pD=`^${uD}$`;`${dD}`;function mD(e,t){return Array.from({length:t-e+1},(t,n)=>String.fromCharCode(e+n))}var hD=[...mD(97,122),...mD(65,90)],gD=[`0`,...mD(49,57)];[...gD],[...hD,...gD],[...gD],new RegExp(pD);var _D={enabled:!0,maxRetries:3,baseDelayMs:2e3,maxAgentDelayMs:6e4},vD={firstEventMs:6e4,idleMs:12e4,attemptMs:6e5,outputBytes:2097152},yD=1e3,bD=Symbol(`Mule model limit`);function xD(e,t){return PE(e,t)}var SD=(e,t,n)=>({_tag:`MuleError`,phase:e,message:t,cause:n}),CD=(e,t)=>({kind:e,value:`mule_${e}_${rg()}`,parent:t}),wD=()=>C;function TD(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 ED=(e,t)=>({content:[{type:`text`,text:e}],isError:!0,terminate:t});function DD(e,t){return e.find(e=>e.descriptor.name===t.name)}function OD(e,t,n,r){return r({type:`tool_execution_end`,run:t,turn:n,toolCall:e.identity,call:e.call,result:e.result})}function kD(e,t,n,r,i){let a=CD(`tool_call`,r);return b(function*(){if(yield*i({type:`tool_execution_start`,replay:e?.replay??`unsafe`,run:n,turn:r,toolCall:a,call:t}),e===void 0){let e=ED(`Tool "${t.name}" not found`),o={call:t,identity:a,result:e};return yield*OD(o,n,r,i),{kind:`finalized`,value:o}}let o=yield*zr(e.prepare(t));if(Ae(o)){let e=ED(o.failure.message,o.failure.terminate),s={call:t,identity:a,result:e};return yield*OD(s,n,r,i),{kind:`finalized`,value:s}}return{kind:`prepared`,call:t,identity:a,tool:o.success}})}function AD(e,t,n,r){return b(function*(){let i,a;yield*vy(ry(e.tool.execute()),o=>Ae(o)?(a=o.failure,C):i===void 0?o.success.type===`result`?(i=o.success.result,C):r({type:`tool_execution_update`,run:t,turn:n,toolCall:e.identity,call:e.call,result:o.success.result}):C);let o=a===void 0?i??ED(`Tool "${e.call.name}" returned no result`):ED(a.message),s={call:e.call,identity:e.identity,result:o};return yield*OD(s,t,n,r),s})}function jD(e,t,n,r){let i=TD(e.call,e.result),a=CD(`tool_result`,e.identity);return b(function*(){return yield*r({type:`message_start`,run:t,turn:n,message:a,value:i}),yield*r({type:`message_end`,run:t,turn:n,message:a,value:i,data:e.result.data}),i})}function MD(e,t,n,r,i){let a=t.tools??[],o=t.toolExecution===`sequential`||e.some(e=>DD(a,e)?.executionMode===`sequential`);return b(function*(){let t=e=>e.kind===`finalized`?x(e.value):AD(e,n,r,i),s=o?yield*Zr(e,e=>T(kD(DD(a,e),e,n,r,i),t)):yield*b(function*(){let o=yield*Zr(e,e=>kD(DD(a,e),e,n,r,i));return yield*Hn(o.map(t),{concurrency:`unbounded`})});return{messages:yield*Zr(s,e=>jD(e,n,r,i)),terminate:s.length>0&&s.every(e=>e.result.terminate===!0)}})}var ND=e=>ED(`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 PD(e,t,n,r){return b(function*(){let i=yield*Zr(e,e=>b(function*(){let i=CD(`tool_call`,n),a={call:e,identity:i,result:ND(e)};return yield*r({type:`tool_execution_start`,replay:`unsafe`,run:t,turn:n,toolCall:i,call:e}),yield*OD(a,t,n,r),a}));return yield*Zr(i,e=>jD(e,t,n,r))})}function FD(e,t){return pn({try:n=>{let r=()=>{t.abort(n.reason)};return n.aborted?r():n.addEventListener(`abort`,r,{once:!0}),Promise.resolve(e.next()).finally(()=>{n.removeEventListener(`abort`,r)})},catch:e=>SD(`model`,`Pi model stream failed`,e)})}function ID(e,t,n){return e.pipe(di({duration:t,orElse:()=>v(SD(`model`,n(),bD))}))}function LD(e,t,n,r,i,a){let o=CD(`message`,r),s,c={started:!1,terminal:void 0};return nr(b(function*(){let l=e.modelStreamLimits,u=Math.min(l?.firstEventMs??vD.firstEventMs,vD.firstEventMs),d=Math.min(l?.attemptMs??vD.attemptMs,vD.attemptMs),f=Math.min(l?.outputBytes??vD.outputBytes,vD.outputBytes);if([u,d,f,e.modelStreamIdleTimeoutMs??1].some(e=>!Number.isSafeInteger(e)||e<=0))return yield*v(SD(`model`,`Model stream limits must be positive safe integers`));let p=Date.now(),m=p,ee=0,te=0,ne=new TextEncoder,re=!1,ie=e=>SD(`model`,`Model ${e} after ${String(Date.now()-p)} ms (max provider gap ${String(Math.max(ee,Date.now()-m))} ms, streamed ${String(te)} bytes)`,bD),ae=t=>{let n=Date.now()-p,r=d-n,i=Math.min(re?vD.idleMs:u,e.modelStreamIdleTimeoutMs??vD.idleMs)-(Date.now()-m),a=r<=i?`attempt timed out`:re?`stream timed out (silence)`:`first event timed out`;return ID(t,Math.max(0,Math.min(r,i)),()=>ie(a).message)},oe=new AbortController,se={};yield*Tr(()=>pn({try:()=>{if(oe.abort(`Mule model scope closed`),se.response===void 0)return Promise.resolve(!0);let e=se.response.then(async e=>{await Promise.all([se.iterator?.return?.(),e.result()])},()=>void 0);return new Promise(t=>{let n=setTimeout(()=>{t(!1)},yD);e.then(()=>{clearTimeout(n),t(!0)},()=>{clearTimeout(n),t(!1)})})},catch:e=>SD(`model`,`Pi model stream failed`,e)}).pipe(Lt(()=>!1),T(t=>t?C:e.onUndrained??C)));let ce=(e.resolveApiKey===void 0?void 0:yield*e.resolveApiKey(e.model.provider))??e.streamOptions?.apiKey,le={...e.streamOptions,maxRetries:0,signal:oe.signal};ce!==void 0&&(le.apiKey=ce);let ue=e.prepareSystemPrompt===void 0?e.systemPrompt:yield*e.prepareSystemPrompt();e.prepareSystemPrompt!==void 0&&(yield*i({type:`model_prompt`,run:n,turn:r,attempt:a,systemPrompt:ue}));let de={systemPrompt:ue,messages:t},fe=(e.tools??[]).map(e=>e.descriptor);fe.length>0&&(de.tools=fe);let pe=yield*ae(pn({try:()=>{let t=e.stream??kE;return se.response=Promise.resolve(t(e.model,hi(de),le)),se.response},catch:e=>SD(`model`,`Pi model stream could not start`,e)})),me=pe[Symbol.asyncIterator]();se.iterator=me;let he=e=>{let a=Date.now();if(ee=Math.max(ee,a-m),m=a,re=!0,(e.type===`text_delta`||e.type===`thinking_delta`||e.type===`toolcall_delta`)&&(te+=ne.encode(e.delta).byteLength,te>f))return v(ie(`output limit exceeded`));switch(`partial`in e&&(s=e.partial),e.type){case`start`:return t.push(e.partial),c.started=!0,i({type:`message_start`,run:n,turn:r,message:o,value:e.partial});case`text_start`:case`text_delta`:case`text_end`:case`thinking_start`:case`thinking_delta`:case`thinking_end`:case`toolcall_start`:case`toolcall_delta`:case`toolcall_end`:return c.started&&(t[t.length-1]=e.partial),i({type:`message_update`,run:n,turn:r,message:o,value:e.partial,event:e});case`done`:return c.terminal=e.message,C;case`error`:return c.terminal=e.error,C}},ge=()=>ae(FD(me,oe)),_e=yield*ge();for(;!_e.done;)yield*he(_e.value),_e=yield*ge();let ve=c.terminal??(yield*ae(pn({try:()=>pe.result(),catch:e=>SD(`model`,`Pi model stream did not settle`,e)})));return c.started?t[t.length-1]=ve:(t.push(ve),yield*i({type:`message_start`,run:n,turn:r,message:o,value:ve})),{message:ve,identity:o}}).pipe(yn(l=>{if(l.cause!==bD)return v(l);let u={role:`assistant`,content:s?.content??[],api:e.model.api,provider:e.model.provider,model:e.model.id,usage:s?.usage??{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,timestamp:Date.now(),errorMessage:e.retry?.enabled&&a>e.retry.maxRetries?`The model failed ${String(a)} times on this conversation: ${l.message}`:l.message};return b(function*(){return c.started?t[t.length-1]=u:(t.push(u),yield*i({type:`message_start`,run:n,turn:r,message:o,value:u})),{identity:o,message:u,limitReached:!0}})})))}function RD(e,t,n,r,i,a){return b(function*(){let o=e.retry===void 0?void 0:{...e.retry};if(o?.enabled&&[o.maxRetries,o.baseDelayMs,o.maxAgentDelayMs??6e4].some(e=>!Number.isSafeInteger(e)||e<0))return yield*v(SD(`model`,`Retry policy requires non-negative safe-integer counts and delays`));let s,c=Math.min(o?.maxRetries??0,a?.maxAttempts??1/0),l=a===void 0?0:a.attempt+ +(a.phase===`dispatched`),u=a?.attempt??0,d=!1,f=a?.message?.errorMessage,p=t=>e.onRetry===void 0?C:e.onRetry(t),m=(e,t)=>b(function*(){d=!0,yield*p(t===void 0?{type:`retry_finished`,run:n,turn:r,attempt:u,success:e}:{type:`retry_finished`,run:n,turn:r,attempt:u,success:e,finalError:t})}),ee=e=>b(function*(){yield*jn(Math.max(0,e-Date.now())),yield*p({type:`retry_attempt_started`,run:n,turn:r,attempt:u})}),te=(e,t)=>b(function*(){if(o===void 0)return yield*v(SD(`model`,`Retry policy is unavailable`));u++,f=e;let i=Math.max(BE(o,u),t!==void 0&&Number.isSafeInteger(t)&&t>=0&&t<=6e4?t:0),a=Math.min(1e3,i/4,Math.max(0,6e4-i)),s=i+Math.floor(Math.random()*a),l=Date.now()+s;return{type:`retry_scheduled`,run:n,turn:r,attempt:u,maxAttempts:c,delayMs:s,dueAt:l,errorMessage:f}});return yield*b(function*(){if(a!==void 0){if(!Number.isSafeInteger(a.attempt)||a.attempt<0||a.maxAttempts!==void 0&&(!Number.isSafeInteger(a.maxAttempts)||a.maxAttempts<0)||a.phase===`waiting`&&(!Number.isSafeInteger(a.dueAt)||a.dueAt<0))return yield*v(SD(`model`,`Invalid model retry continuation`));if(!o?.enabled||u>c||a.phase===`dispatched`&&u>=c)return yield*m(!1,`Model retry budget exhausted after restart`),a.message===void 0?yield*v(SD(`model`,`Model retry budget exhausted after restart`)):{message:a.message};if(a.phase===`waiting`)yield*ee(a.dueAt);else{let e={...yield*te(`Model request interrupted by a restart`),delayMs:0,dueAt:Date.now()};yield*p(e),yield*ee(e.dueAt)}}for(;;){if(s!==void 0){let e=t.indexOf(s.message);e!==-1&&t.splice(e,1)}let a=yield*LD(e,t,n,r,i,++l);s=a;let f=a.message,m;if(f.stopReason===`error`&&o?.enabled&&u<c&&(yield*oi({try:()=>a.limitReached===!0||e.retryable(f),catch:e=>SD(`model`,`Typed model retry decision failed`,e)}))){let t=yield*oi({try:()=>e.retryAfterMs?.(f),catch:e=>SD(`model`,`Model retry delay observation failed`,e)});m=yield*te(f.errorMessage??`Unknown error`,t)}if(m===void 0&&(f.stopReason===`error`||u>0)){let e={type:`retry_finished`,run:n,turn:r,attempt:u,success:f.stopReason!==`error`&&f.stopReason!==`aborted`};m=f.stopReason===`error`&&f.errorMessage!==void 0?{...e,finalError:f.errorMessage}:e}if(yield*i({type:`message_end`,run:n,turn:r,message:a.identity,value:f,retry:m}),m?.type===`retry_finished`&&(d=!0),m!==void 0&&u>0&&(yield*p(m)),m?.type!==`retry_scheduled`)return s;yield*ee(m.dueAt)}}).pipe(ke(()=>u===0||d?C:m(!1,f)))})}var zD=e=>e.stopReason===`aborted`?`cancelled`:e.stopReason===`error`?`failed`:`completed`;function BD(e,t,n,r,i,a){return Zr(e,e=>b(function*(){let o=CD(`message`,i);t.push(e),n.push(e),yield*a({type:`message_start`,run:r,turn:i,message:o,value:e}),yield*a({type:`message_end`,run:r,turn:i,message:o,value:e})})).pipe(mn)}function VD(e,t,n,r,i,a,o,s){return b(function*(){yield*o({type:`turn_start`,run:r,turn:i}),yield*BD(a,t,n,r,i,o);let c=yield*RD(e,t,r,i,o,s),l=zD(c.message)!==`completed`,u=c.message.content.filter(e=>e.type===`toolCall`),d=u.length===0||l?{messages:[],terminate:!1}:c.message.stopReason===`length`?{messages:yield*PD(u,r,i,o),terminate:!1}:yield*MD(u,e,r,i,o);t.push(...d.messages),n.push(c.message,...d.messages),yield*o({type:`turn_end`,run:r,turn:i,message:c.message,toolResults:d.messages});let f={message:c.message,toolResults:d.messages,terminate:d.terminate};return c.limitReached&&c.message.errorMessage!==void 0?{...f,modelLimitReason:c.message.errorMessage}:f})}function HD(e,t,n,r,i,a){let o=CD(`turn`,i);return b(function*(){if(zD(t.message)!==`completed`)return{message:t.message,toolResults:[],terminate:!0};let s=yield*Zr(t.tools,n=>b(function*(){if(n.state===`completed`&&n.message!==void 0)return{message:n.message,terminate:n.result.terminate===!0,recorded:!0};let r=DD(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*kD(r,n.call,i,o,a);s=e.kind===`finalized`?e.value:yield*AD(e,i,o,a)}else s={call:n.call,identity:CD(`tool_call`,o),result:n.state===`completed`?n.result:n.state===`pending`&&t.message.stopReason===`length`?ND(n.call):ED(`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*OD(s,i,o,a);return{message:yield*jD(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 UD(e,t,n,r){return b(function*(){if(e.shouldStopAfterTurn!==void 0&&(yield*e.shouldStopAfterTurn({message:t.message,toolResults:t.toolResults,context:n,newMessages:r})))return{continue:!1,pending:[]};let i=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()];if(t.message.content.some(e=>e.type===`toolCall`)&&!t.terminate||i.length>0)return{continue:!0,pending:i};let a=e.getFollowUpMessages===void 0?[]:[...yield*e.getFollowUpMessages()];return{continue:a.length>0,pending:a}})}function WD(e,t,n,r,i,a,o){return b(function*(){yield*a({type:`run_end`,run:e,terminal:t,outcome:i});let s={status:i,run:e,terminal:t,message:n,messages:r};return o===void 0?s:{...s,modelLimitReason:o}})}function GD(e,t=wD){return b(function*(){let n=yield*A_(1),r={started:!1,ended:!1},i=e=>sr(()=>(e.type===`run_end`&&(r.ended=!0),n.withPermits(1)(t(e)))).pipe(In(()=>y(()=>{e.type===`run_start`&&(r.started=!0)}))),a=CD(`run`),o=CD(`terminal`,a);return yield*qD(e,i,a,o).pipe(Ne(e=>{let t=KD(e);return!r.started||r.ended||t===void 0?C:i({type:`run_end`,run:a,terminal:o,outcome:t}).pipe(Ve)}))})}function KD(e){if(ca(e))return;if(Ki(e.cause))return`cancelled`;let t=Xi(e.cause);if(!(Nr(t)&&t.value.phase===`listener`))return`failed`}function qD(e,t,n,r){return b(function*(){let i=[...e.messages],a=[],o=e.getSteeringMessages===void 0?[]:[...yield*e.getSteeringMessages()],s,c;yield*t({type:`run_start`,run:n});let l=e.resume?.kind===`retry`?e.resume:void 0;if(e.resume?.kind===`assistant`){let s=yield*HD(e,e.resume,i,a,n,t),c=zD(s.message),l=c===`completed`?yield*UD(e,s,i,a):{continue:!1,pending:[]};if(!l.continue&&o.length===0)return yield*WD(n,r,s.message,a,c,t);o.push(...l.pending)}do{let u=yield*VD(e,i,a,n,CD(`turn`,n),o,t,l);l=void 0,s=u.message;let d=zD(u.message);if(d!==`completed`)return yield*WD(n,r,u.message,a,d,t,u.modelLimitReason);if(e.prepareNextTurn!==void 0&&!u.terminate&&u.message.content.some(e=>e.type===`toolCall`)){let t=yield*e.prepareNextTurn({message:u.message,toolResults:u.toolResults,context:i,newMessages:a});t!==void 0&&i.splice(0,i.length,...t)}let f=yield*UD(e,u,i,a);o=[...f.pending],c=f.continue}while(c);return yield*WD(n,r,s,a,`completed`,t)})}var JD={run:GD},YD=class{#e=new Map;#t;constructor(e=8){this.#t=e}push(e,t){let n=this.#e.get(e)??[];if(n.length>=this.#t)throw new bS({namespace:`execute`,operation:`images`,cause:{kind:`Unavailable`,message:`Image collector cap reached for this execution (max ${String(this.#t)} images). Process images one at a time or write them to files.`}});let r=`img_${String(n.length)}`;return n.push(Object.freeze({...t})),this.#e.set(e,n),r}drain(e){let t=this.#e.get(e);return t===void 0?[]:(this.#e.delete(e),t)}dispose(e){this.#e.delete(e)}},XD=8192,ZD=XD*4,QD=new TextEncoder,$D=()=>new TextDecoder(`utf-8`,{ignoreBOM:!0,fatal:!1}),eO=class e{wake;#e={stdout:{decoder:$D(),pending:new Uint8Array},stderr:{decoder:$D(),pending:new Uint8Array}};#t=$D();#n=Array.from({length:XD},()=>void 0);#r=0;#i=0;#a=0;#o=0;#s=0;#c=0;#l=!1;#u=!1;constructor(e){this.wake=e}static make(){return Bg({capacity:1,strategy:`dropping`}).pipe(we(t=>new e(t)))}write(e,t){if(this.#u||t.length===0)return;let n=this.#e[e];this.#c+=t.length;for(let e=0;e<t.length;e+=ZD){let r=t.subarray(e,e+ZD),i=n.decoder.decode(r,{stream:!0}),a=new Uint8Array(n.pending.length+r.length);a.set(n.pending),a.set(r,n.pending.length);let o=this.#f(a);n.pending=a.slice(a.length-o),this.#h(i,a.length-o,a)}this.#l=!0,Wg(this.wake,void 0)}#d(e,t){let n=this.#t.decode(e.subarray(0,t),{stream:!0});return this.#t.decode(),n}#f(e){for(let t=1;t<=Math.min(3,e.length);t++){let n=e.subarray(e.length-t);if(this.#d(n,n.length).length===0)return t}return 0}#p(){let e=this.#n[this.#r];if(e===void 0)throw Error(`Missing output ring entry`);this.#n[this.#r]=void 0,this.#r=(this.#r+1)%XD,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 QD.encode(i).length>=t&&i.split(`
|
|
19
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=QD.encode(s).length,u=s.split(`
|
|
20
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:QD.encode(e).length,newlines:e.split(`
|
|
21
|
-
`).length-1};for(this.#i===XD&&this.#p(),this.#n[(this.#r+this.#i)%XD]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>XD||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-XD),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)%XD];if(n===void 0)throw Error(`Missing output ring entry`);e+=n.text}return{tail:e,droppedBytes:this.#s,totalBytes:this.#c}}#g(){if(!this.#l)return;this.#l=!1;let{tail:e,...t}=this.snapshot();return{type:`update`,result:{isError:!1,content:[{type:`text`,text:e}],data:t}}}finish(){if(!this.#u){this.#u=!0;for(let e of[this.#e.stdout,this.#e.stderr]){let t=e.decoder.decode();this.#h(t,e.pending.length,null),e.pending=new Uint8Array,t.length>0&&(this.#l=!0)}return this.#g()}}get updates(){return Zv(this.wake).pipe(ny(()=>jn(`100 millis`).pipe(Ce(()=>this.#u?void 0:this.#g()))),dy(e=>e!==void 0))}dispose(){this.#u=!0,this.#n.fill(void 0),this.#r=this.#i=this.#a=this.#o=0,this.#c=this.#s=0,this.#l=!1;for(let e of[this.#e.stdout,this.#e.stderr])e.decoder.decode(),e.pending=new Uint8Array}},tO=P({code:M}),nO='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 rO(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await vT(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function iO(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=>rO(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 aO(e,t){let n=e.safeParse(t);if(!n.success)throw new cS(n.error.issues);return n.data}function oO(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(aO(Gb,t))),describe:t=>Promise.resolve().then(()=>e.describe(aO(Wb,t))),search:t=>Promise.resolve().then(()=>e.search(aO(Ub,t)))})}function sO(e,t,n,r,i){return Object.freeze({...iO(e,n,r,i),forage:oO(t)})}function cO(e,t,n,r,i,a,o,s){let c=n.execution??dE(void 0),l=new YD,u=(u,d,f,p,m)=>xE({executionId:u,toolCallId:p,output:m,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>sO(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>sr(()=>{let n=rg();return u(n,e,t).pipe(rr(y(()=>{l.dispose(n)})))}),f=(e,t,n)=>sr(()=>{let r=rg(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(wt({onSuccess:e=>x(lO({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof vS&&t.length>0?x(lO({text:CS(e),isError:!0},t)):v(uO(e))}}),rr(y(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:nO,parameters:sD({code:fD()},{additionalProperties:!1})},prepare:e=>Hp(tO)(e.arguments).pipe(Ce(({code:t})=>({execute:()=>ey(b(function*(){let n=yield*eO.make();yield*wr(()=>y(()=>{n.dispose()}));let r=yield*Yn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return uy(n.updates,Lv(b_(r)).pipe(iy(e=>{let t=n.finish();return sy(Yv(t===void 0?[]:[t]),Lv(e))})),{haltStrategy:`right`}).pipe(hy(e=>e.type===`result`))}))})),lt(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function lO(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 uO(e){let t={_tag:`MuleError`,phase:`tool`,message:ES(e)?CS(e):e.message};return e instanceof pS?{...t,cause:e}:t}function dO(e,t){return e<t?-1:+(e>t)}var fO=128,pO=_(()=>w().min(1).max(160)),mO=_(()=>Zt({version:w().min(1).max(160),modules:Tr(bt())})),hO=1e3;function gO(e){if(e.length>fO)throw new G(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>dO(e.id,t.id)),n=new Set;for(let e of t){if(!pO.safeParse(e.id).success)throw new G(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new G(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function _O(e){if(e>hO)throw new G(`Candidate module count exceeds bound`)}function vO(e,t){let n=mO.safeParse(e);if(!n.success)throw new G(`Capability source snapshot must have a non-empty bounded version`);_O(t+n.data.modules.length)}function yO(e,t,n,r,i){return te(a=>b(function*(){let o=t=>fn({try:()=>t.release(),catch:()=>new sS(e.id,`release`)}).pipe(vn(e=>y(()=>{n.push(e)}))),s=yield*oi({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(i===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:i}).then(e=>ra(e),()=>aa(new sS(e.id,`acquire`)))}},catch:()=>new sS(e.id,`acquire`)});yield*Da(t,Gt(()=>s.outcome).pipe(T(e=>ca(e)?o(e.value):C)));let c=yield*a(Gt(()=>s.outcome)).pipe(Oe(()=>y(()=>{s.controller.abort()})));return la(c)?yield*Xt(c.cause):c.value}))}function bO(e){return b(function*(){let t=yield*oi({try:()=>gO(e.sources),catch:e=>e instanceof G?e:new G(`Capability sources are invalid`)});yield*oi({try:()=>{_O(e.modules.length)},catch:e=>e instanceof G?e:new G(`Static capability modules are invalid`)});let n=yield*Ca(),r=[],i=!1,a=[...e.modules],o=[];return yield*b(function*(){for(let s of t){let t=yield*yO(s,n,r,()=>{i=!0},e.session);yield*oi({try:()=>{vO(t.snapshot,a.length)},catch:e=>e instanceof G?e:new G(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*oi({try:()=>tE(a,o),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=cO(s.operations,s.catalog,e.sandbox,c,s.moduleAliases,s.namespacePaths,e.session?.sessionId??null,e.access),u=!1;return Object.freeze({compiled:s,executeDoor:l,isStale:()=>i,close:()=>b(function*(){u||(u=!0,yield*c.awaitIdle,yield*Aa(n,sa));let e=r[0];e!==void 0&&(yield*v(e))})})}).pipe(Me(e=>ca(e)?C:Aa(n,e)))})}var xO=2;function SO(e){return b(function*(){for(let t=0;t<xO;t+=1){let t=yield*bO(e);if(!t.isStale())return t;yield*t.close()}return yield*v(new sS(void 0,`stale`))})}function CO(e,t,n){return te(r=>r(e.take(1)).pipe(T(()=>y(t).pipe(rr(e.release(1)))),T(n)))}function wO(e,t){return vt(e.candidate.close().pipe(wt({onFailure:t=>ya(e.settled,t).pipe(g(v(t))),onSuccess:()=>ba(e.settled,void 0).pipe(g(y(()=>{t.delete(e)})))})))}function TO(e,t){return e.runCleanup?wO(e.installed,t):_a(e.installed.settled)}function EO(e,t){return Hn(e.map(e=>TO(e,t).pipe(Ln)),{concurrency:`unbounded`}).pipe(T(e=>{let t=e.find(la);return t===void 0?C:Xt(t.cause)}))}function DO(e){return b(function*(){let t=yield*A_(1),n=yield*oi({try:()=>dE(e.execution),catch:e=>e instanceof G?e:new G(`Execution policy is invalid`)}),r=yield*fE(n.capacity),i=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:n}),a=e.modules.length===0&&e.sources.length>0?void 0:yield*oi({try:()=>tE(e.modules),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)}),o=yield*oi({try:()=>Object.freeze(e.tools.map(t=>xT(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof G?e:new G(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*SO({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*ga(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>CO(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=>EO(e,c));return yield*wr(()=>u().pipe(Bt)),Object.freeze({acquire:()=>t.withPermits(1)(b(function*(){if(l)return yield*v(new oS);if(s===void 0||s.candidate.isStale()){let t=yield*SO({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*ga(),leases:0,retired:!1,closing:!1};s=a,c.add(a),n!==void 0&&(n.retired=!0,n.leases===0&&!n.closing&&(n.closing=!0,yield*wO(n,c)))}let n=s;n.leases+=1;let a,u=()=>CO(t,()=>{if(a!==void 0)return a?{installed:n,runCleanup:!1}:void 0;if(--n.leases,a=n.retired&&n.leases===0&&!n.closing,a)return n.closing=!0,{installed:n,runCleanup:!0}},e=>e===void 0?C:TO(e,c));return yield*wr(()=>u().pipe(Bt)),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 OO(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>vt(fn({try:()=>e.execute(t,n),catch:DS}))})}function kO(e){return DO({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(Ce(e=>Object.freeze({acquire:()=>e.acquire().pipe(Ce(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function AO(e,t){let n=await Kn(e,t);if(ca(n))return n.value;let r=Xi(n.cause);if(Nr(r))throw r.value;if(Ki(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Ji(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function jO(e){let t=await AO(Ca()),n=e.onSandboxFailure;try{let r=await AO(DO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:OO(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>Gt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(Ta(t))),i=async e=>{let t=await AO(Ca());try{let n=await AO(r.acquire().pipe(Ta(t)),e?.signal===void 0?void 0:{signal:e.signal}),i;return Object.freeze({revision:n.revision,catalog:n.catalog,executeTool:n.effectExecuteTool,tools:n.tools,release:()=>(i??=AO(n.release().pipe(rr(Aa(t,sa)))),i)})}catch(e){throw await AO(Aa(t,sa)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=AO(r.close().pipe(rr(Aa(t,sa)))),a)})}catch(e){throw await AO(Aa(t,sa)),e}}var MO=ym(()=>I([om,cm,Hm,M,gm(F(MO)),tm(fm(M,MO))])),NO=M.check(hh(1),vh(256)),PO=M.check(hh(1),vh(128)),FO=P({kind:j(`sandbox_failure`),ref:NO,executionId:NO,adapter:PO,buildSha:R(PO),tag:L([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:fm(M,MO),healthAlert:cm});function IO(e){return jT(e)}function LO(e){return MT(e)}var RO=Object.freeze({module:LO,operation:IO,make:jO,gate:zT,grantAs:RT}),zO=Zh,BO=4096,VO=new TextEncoder,HO=zO.check(B(e=>VO.encode(JSON.stringify(e)).byteLength<=BO)),UO=D(HO);function WO(e,t){if(em(e))return Ht(D(e)(t));let n=e[`~standard`].validate(t);if(yr(n,`then`))throw new W(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function GO(e,t){let n=UO(t);if(ke(n))throw new W(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!WO(e.schema,n.success))throw new W(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function KO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qO(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function JO(e){return qO({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function YO(e,t){ur(tt(`shiitake_operation_failed`,Lo(t)).pipe(dr({operation:e,errorKind:t instanceof Error?`error`:`non-error`})))}var XO=64,ZO=256,QO=new WeakMap,$O=new TextEncoder;function ek(e){let t=QO.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:$O.encode(n).byteLength});return QO.set(e,r),r}function tk(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 nk(e){let t=new Set,n=!1,r,i=e=>{gr(Zg(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:gr(Hg(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=sr(()=>o.closed?x(`closed`):r===void 0?o.lagged?x(`reset`):n?x(`closed`):e_(o.frames).pipe(Qa(()=>x(`closed`)),T(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=ek(e).bytes),x(e)):v(r))):v(r));return Object.freeze({take:s,checkpoint:(e=-1)=>{i(o),o.lagged=!1,o.observed=e},close:()=>{o.closed||(o.closed=!0,i(o),t.delete(o),Jg(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=tk(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=ek(t);n.bytes+o>1048576||!Wg(n.frames,t)?(i(n),n.lagged=!0,Wg(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Jg(e.frames)}}}}var rk=new WeakMap;function ik(e,t){for(let n of rk.get(e)??[])if(n.observes(t))return!0;return!1}function ak(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 ok(e,t){if(e.pendingCount>=ZO){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 sk(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){ok(e,t);return}e.wake=void 0;try{n(t)}catch(t){YO(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function ck(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&sk(n,`activity`)}function lk(e,t,n=`durable`){let r=rk.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){YO(`owner-observation-publish`,e);continue}}function uk(e){let t=rk.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){YO(`owner-execution-change-publish`,e)}}function dk(e){let t=new Map,n=new Set,r=rk.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){YO(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){ck(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&ck(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`||sk(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),rk.set(e,r),Object.freeze({register:(e,r)=>sr(()=>{if(i)return v(new W(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=XO)return v(new W(`runtime`,`rejected`,`Observation capacity is exhausted`));let s={revision:0,sessionId:e,settlementOnly:r===`settlement`,closed:!1,pendingCount:0,pendingReason:void 0,queued:!0,reset:!1,wake:void 0},c=t.get(e)??new Set;c.add(s),t.set(e,c),n.add(s);let l=y(()=>a(s)),u=$n(e=>{let t=a(s);if(t!==void 0){e(x(t));return}let n=t=>{e(x(t))};return s.wake=n,y(()=>{s.wake===n&&(s.wake=void 0)})});return x(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:y(()=>{if(!i){i=!0,r.delete(s),r.size===0&&rk.delete(e);for(let e of n)o(e)}})})}var fk=200,pk={onExcessProperty:`error`},mk=new TextEncoder,hk=H.pipe(z(V(0))),gk=M.pipe(z(hh(1)),z(B(e=>mk.encode(e).byteLength<=256)));D(P({limit:k(H.pipe(z($m({minimum:1,maximum:fk})))),after:k(M)}),pk);var _k=U(mm([hk,gk]));D(_k),Qp(_k),D(P({session_id:gk,last_activity_at:hk,state:L([`needs_you`,`running`,`errored`,`done`]),bytes:H.pipe(z(V(0)))}),pk);var vk=O(P({extension_id:M,value_json:M})),yk=O(U(Dy)),bk=O(Oy),xk=Qp(U(Dy));function Sk(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
21
|
+
`).length-1};for(this.#i===XD&&this.#p(),this.#n[(this.#r+this.#i)%XD]=r,this.#i++,this.#a+=r.textBytes,this.#o+=r.newlines;this.#a>XD||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-XD),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)%XD];if(n===void 0)throw Error(`Missing output ring entry`);e+=n.text}return{tail:e,droppedBytes:this.#s,totalBytes:this.#c}}#g(){if(!this.#l)return;this.#l=!1;let{tail:e,...t}=this.snapshot();return{type:`update`,result:{isError:!1,content:[{type:`text`,text:e}],data:t}}}finish(){if(!this.#u){this.#u=!0;for(let e of[this.#e.stdout,this.#e.stderr]){let t=e.decoder.decode();this.#h(t,e.pending.length,null),e.pending=new Uint8Array,t.length>0&&(this.#l=!0)}return this.#g()}}get updates(){return Zv(this.wake).pipe(ny(()=>jn(`100 millis`).pipe(we(()=>this.#u?void 0:this.#g()))),dy(e=>e!==void 0))}dispose(){this.#u=!0,this.#n.fill(void 0),this.#r=this.#i=this.#a=this.#o=0,this.#c=this.#s=0,this.#l=!1;for(let e of[this.#e.stdout,this.#e.stderr])e.decoder.decode(),e.pending=new Uint8Array}},tO=P({code:M}),nO='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 rO(e,t,n,r){let i={module:e.grantKey,operation:e.name,access:e.operation.access,confirm:e.operation.confirm};return async a=>await vT(n,{sessionId:r},i,a,t.signal)??await e.operation.invoke(a,t)}function iO(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=>rO(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 aO(e,t){let n=e.safeParse(t);if(!n.success)throw new cS(n.error.issues);return n.data}function oO(e){return Object.freeze({list:t=>Promise.resolve().then(()=>e.list(aO(Gb,t))),describe:t=>Promise.resolve().then(()=>e.describe(aO(Wb,t))),search:t=>Promise.resolve().then(()=>e.search(aO(Ub,t)))})}function sO(e,t,n,r,i){return Object.freeze({...iO(e,n,r,i),forage:oO(t)})}function cO(e,t,n,r,i,a,o,s){let c=n.execution??dE(void 0),l=new YD,u=(u,d,f,p,m)=>xE({executionId:u,toolCallId:p,output:m,images:Object.freeze({push:e=>l.push(u,e)}),code:d,callerSignal:f,policy:c,sandbox:n,backingWork:r,createBindings:n=>sO(e,t,Object.freeze({...n,toolCallCode:d}),s,o),modules:i,namespacePaths:a,sessionId:o}),d=(e,t)=>sr(()=>{let n=rg();return u(n,e,t).pipe(rr(y(()=>{l.dispose(n)})))}),f=(e,t,n)=>sr(()=>{let r=rg(),i=()=>l.drain(r);return u(r,e,void 0,t,n).pipe(Tt({onSuccess:e=>x(lO({text:e.text,isError:!1},i())),onFailure:e=>{let t=i();return e instanceof vS&&t.length>0?x(lO({text:CS(e),isError:!0},t)):v(uO(e))}}),rr(y(()=>{l.dispose(r)})))}),p={replay:`unsafe`,descriptor:{name:`execute`,description:nO,parameters:sD({code:fD()},{additionalProperties:!1})},prepare:e=>Hp(tO)(e.arguments).pipe(we(({code:t})=>({execute:()=>ey(b(function*(){let n=yield*eO.make();yield*Tr(()=>y(()=>{n.dispose()}));let r=yield*Yn(f(t,e.id,{write:(e,t)=>{n.write(e,t)}}),{startImmediately:!0});return uy(n.updates,Lv(b_(r)).pipe(iy(e=>{let t=n.finish();return sy(Yv(t===void 0?[]:[t]),Lv(e))})),{haltStrategy:`right`}).pipe(hy(e=>e.type===`result`))}))})),ut(()=>({message:`Invalid execute arguments`})))};return Object.freeze({effectTool:p,execute:d})}function lO(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 uO(e){let t={_tag:`MuleError`,phase:`tool`,message:ES(e)?CS(e):e.message};return e instanceof pS?{...t,cause:e}:t}function dO(e,t){return e<t?-1:+(e>t)}var fO=128,pO=_(()=>w().min(1).max(160)),mO=_(()=>Qt({version:w().min(1).max(160),modules:Er(xt())})),hO=1e3;function gO(e){if(e.length>fO)throw new G(`Capability source count exceeds bound`);let t=[...e].sort((e,t)=>dO(e.id,t.id)),n=new Set;for(let e of t){if(!pO.safeParse(e.id).success)throw new G(`Capability source id must be non-empty and bounded`);if(n.has(e.id))throw new G(`Duplicate capability source id: ${e.id}`);n.add(e.id)}return t}function _O(e){if(e>hO)throw new G(`Candidate module count exceeds bound`)}function vO(e,t){let n=mO.safeParse(e);if(!n.success)throw new G(`Capability source snapshot must have a non-empty bounded version`);_O(t+n.data.modules.length)}function yO(e,t,n,r,i){return ne(a=>b(function*(){let o=t=>pn({try:()=>t.release(),catch:()=>new sS(e.id,`release`)}).pipe(yn(e=>y(()=>{n.push(e)}))),s=yield*oi({try:()=>{let t=new AbortController;return{controller:t,outcome:e.acquire(i===void 0?{signal:t.signal,invalidate:r}:{signal:t.signal,invalidate:r,session:i}).then(e=>ra(e),()=>aa(new sS(e.id,`acquire`)))}},catch:()=>new sS(e.id,`acquire`)});yield*Da(t,qt(()=>s.outcome).pipe(T(e=>ca(e)?o(e.value):C)));let c=yield*a(qt(()=>s.outcome)).pipe(ke(()=>y(()=>{s.controller.abort()})));return la(c)?yield*Zt(c.cause):c.value}))}function bO(e){return b(function*(){let t=yield*oi({try:()=>gO(e.sources),catch:e=>e instanceof G?e:new G(`Capability sources are invalid`)});yield*oi({try:()=>{_O(e.modules.length)},catch:e=>e instanceof G?e:new G(`Static capability modules are invalid`)});let n=yield*Ca(),r=[],i=!1,a=[...e.modules],o=[];return yield*b(function*(){for(let s of t){let t=yield*yO(s,n,r,()=>{i=!0},e.session);yield*oi({try:()=>{vO(t.snapshot,a.length)},catch:e=>e instanceof G?e:new G(`Capability source snapshot is invalid`)}),a.push(...t.snapshot.modules),o.push({id:s.id,version:t.snapshot.version})}let s=e.precompiled??(yield*oi({try:()=>tE(a,o),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)})),c=e.backingWork.createGroup(),l=cO(s.operations,s.catalog,e.sandbox,c,s.moduleAliases,s.namespacePaths,e.session?.sessionId??null,e.access),u=!1;return Object.freeze({compiled:s,executeDoor:l,isStale:()=>i,close:()=>b(function*(){u||(u=!0,yield*c.awaitIdle,yield*Aa(n,sa));let e=r[0];e!==void 0&&(yield*v(e))})})}).pipe(Ne(e=>ca(e)?C:Aa(n,e)))})}var xO=2;function SO(e){return b(function*(){for(let t=0;t<xO;t+=1){let t=yield*bO(e);if(!t.isStale())return t;yield*t.close()}return yield*v(new sS(void 0,`stale`))})}function CO(e,t,n){return ne(r=>r(e.take(1)).pipe(T(()=>y(t).pipe(rr(e.release(1)))),T(n)))}function wO(e,t){return yt(e.candidate.close().pipe(Tt({onFailure:t=>ya(e.settled,t).pipe(g(v(t))),onSuccess:()=>ba(e.settled,void 0).pipe(g(y(()=>{t.delete(e)})))})))}function TO(e,t){return e.runCleanup?wO(e.installed,t):_a(e.installed.settled)}function EO(e,t){return Hn(e.map(e=>TO(e,t).pipe(Ln)),{concurrency:`unbounded`}).pipe(T(e=>{let t=e.find(la);return t===void 0?C:Zt(t.cause)}))}function DO(e){return b(function*(){let t=yield*A_(1),n=yield*oi({try:()=>dE(e.execution),catch:e=>e instanceof G?e:new G(`Execution policy is invalid`)}),r=yield*fE(n.capacity),i=Object.freeze({execute:e.sandbox.execute,adapter:e.sandbox.adapter,buildSha:e.sandbox.buildSha,onFailure:e.onSandboxFailure,execution:n}),a=e.modules.length===0&&e.sources.length>0?void 0:yield*oi({try:()=>tE(e.modules),catch:e=>e instanceof G?e:new G(`Capability compilation failed`)}),o=yield*oi({try:()=>Object.freeze(e.tools.map(t=>xT(t,e.access,{sessionId:e.session?.sessionId??null}))),catch:e=>e instanceof G?e:new G(`Direct tool labels are invalid`)}),s,c=new Set,l=!1;if(e.sources.length===0&&a!==void 0){let t={candidate:yield*SO({...e,sandbox:i,backingWork:r,precompiled:a}),settled:yield*ga(),leases:0,retired:!1,closing:!1};s=t,c.add(t)}let u=()=>CO(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=>EO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({acquire:()=>t.withPermits(1)(b(function*(){if(l)return yield*v(new oS);if(s===void 0||s.candidate.isStale()){let t=yield*SO({...e,sandbox:i,backingWork:r}),n=s,a={candidate:t,settled:yield*ga(),leases:0,retired:!1,closing:!1};s=a,c.add(a),n!==void 0&&(n.retired=!0,n.leases===0&&!n.closing&&(n.closing=!0,yield*wO(n,c)))}let n=s;n.leases+=1;let a,u=()=>CO(t,()=>{if(a!==void 0)return a?{installed:n,runCleanup:!1}:void 0;if(--n.leases,a=n.retired&&n.leases===0&&!n.closing,a)return n.closing=!0,{installed:n,runCleanup:!0}},e=>e===void 0?C:TO(e,c));return yield*Tr(()=>u().pipe(Ht)),Object.freeze({revision:n.candidate.compiled.revision,catalog:n.candidate.compiled.catalog,executeDoor:n.candidate.executeDoor,effectExecuteTool:n.candidate.executeDoor.effectTool,tools:o,release:u})})),close:u})})}function OO(e){return Object.freeze({adapter:e.adapter??`promise`,buildSha:e.buildSha,execute:(t,n)=>yt(pn({try:()=>e.execute(t,n),catch:DS}))})}function kO(e){return DO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:e.sandbox,onSandboxFailure:e.onSandboxFailure,tools:e.tools??[],access:e.access??{}}).pipe(we(e=>Object.freeze({acquire:()=>e.acquire().pipe(we(e=>Object.freeze({revision:e.revision,catalog:e.catalog,executeTool:e.effectExecuteTool,tools:e.tools,release:e.release}))),close:e.close})))}async function AO(e,t){let n=await Kn(e,t);if(ca(n))return n.value;let r=Xi(n.cause);if(Nr(r))throw r.value;if(Ki(n.cause))throw t?.signal?.reason instanceof Error?t.signal.reason:new DOMException(`The operation was aborted`,`AbortError`);let i=Ji(n.cause);throw i instanceof Error?i:Error(`Effect failed without an Error cause`)}async function jO(e){let t=await AO(Ca()),n=e.onSandboxFailure;try{let r=await AO(DO({modules:e.modules??[],sources:e.sources??[],session:e.session,execution:e.execution,sandbox:OO(e.sandbox),onSandboxFailure:n===void 0?void 0:e=>qt(()=>n(e)),tools:e.tools??[],access:e.access??{}}).pipe(Ta(t))),i=async e=>{let t=await AO(Ca());try{let n=await AO(r.acquire().pipe(Ta(t)),e?.signal===void 0?void 0:{signal:e.signal}),i;return Object.freeze({revision:n.revision,catalog:n.catalog,executeTool:n.effectExecuteTool,tools:n.tools,release:()=>(i??=AO(n.release().pipe(rr(Aa(t,sa)))),i)})}catch(e){throw await AO(Aa(t,sa)),e}},a;return Object.freeze({acquire:i,close:()=>(a??=AO(r.close().pipe(rr(Aa(t,sa)))),a)})}catch(e){throw await AO(Aa(t,sa)),e}}var MO=ym(()=>I([om,cm,Hm,M,gm(F(MO)),tm(fm(M,MO))])),NO=M.check(hh(1),vh(256)),PO=M.check(hh(1),vh(128)),FO=P({kind:j(`sandbox_failure`),ref:NO,executionId:NO,adapter:PO,buildSha:R(PO),tag:L([`SourceInvalid`,`GuestThrew`,`DeadlineExceeded`,`SandboxBusy`,`Cancelled`,`DispatchLost`,`SandboxCrashed`,`BadResponse`,`ResultTooLarge`,`ResultNotJson`,`CapabilityFailed`,`Unknown`]),fields:fm(M,MO),healthAlert:cm});function IO(e){return jT(e)}function LO(e){return MT(e)}var RO=Object.freeze({module:LO,operation:IO,make:jO,gate:zT,grantAs:RT}),zO=Zh,BO=4096,VO=new TextEncoder,HO=zO.check(B(e=>VO.encode(JSON.stringify(e)).byteLength<=BO)),UO=D(HO);function WO(e,t){if(em(e))return Wt(D(e)(t));let n=e[`~standard`].validate(t);if(br(n,`then`))throw new W(`contract`,`invalid`,`Host metadata schema must validate synchronously`);return n.issues===void 0}function GO(e,t){let n=UO(t);if(Ae(n))throw new W(`contract`,`invalid`,`Host metadata is not JSON within 4096 bytes`);if(e!==void 0&&!WO(e.schema,n.success))throw new W(`contract`,`invalid`,`Host metadata does not match the host's schema`);return n.success}function KO(e,t){return JSON.stringify(e)===JSON.stringify(t)}function qO(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function JO(e){return qO({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function YO(e,t){dr(nt(`shiitake_operation_failed`,Lo(t)).pipe(fr({operation:e,errorKind:t instanceof Error?`error`:`non-error`})))}var XO=64,ZO=256,QO=new WeakMap,$O=new TextEncoder;function ek(e){let t=QO.get(e);if(t!==void 0)return t;let n=JSON.stringify(e),r=Object.freeze({data:n,bytes:$O.encode(n).byteLength});return QO.set(e,r),r}function tk(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 nk(e){let t=new Set,n=!1,r,i=e=>{_r(Zg(e.frames)),e.bytes=0};return{register(a=!1){let o={frames:_r(Hg(256)),bytes:0,lagged:!1,closed:!1,observed:-1,includeSandboxFailures:a};t.add(o);let s=sr(()=>o.closed?x(`closed`):r===void 0?o.lagged?x(`reset`):n?x(`closed`):e_(o.frames).pipe(Qa(()=>x(`closed`)),T(e=>r===void 0?(e!==`reset`&&e!==`closed`&&(o.bytes-=ek(e).bytes),x(e)):v(r))):v(r));return Object.freeze({take:s,checkpoint:(e=-1)=>{i(o),o.lagged=!1,o.observed=e},close:()=>{o.closed||(o.closed=!0,i(o),t.delete(o),Jg(o.frames),t.size===0&&e())}})},publish(e,r=1/0){if(n)return;let a=tk(e);for(let n of t){if(n.closed||n.lagged||r<=n.observed)continue;let t=n.includeSandboxFailures?e:a,{bytes:o}=ek(t);n.bytes+o>1048576||!Wg(n.frames,t)?(i(n),n.lagged=!0,Wg(n.frames,`reset`)):n.bytes+=o}},end(e){if(!n){n=!0,r=e;for(let e of t)i(e),e.lagged=!1,Jg(e.frames)}}}}var rk=new WeakMap;function ik(e,t){for(let n of rk.get(e)??[])if(n.observes(t))return!0;return!1}function ak(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 ok(e,t){if(e.pendingCount>=ZO){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 sk(e,t){if(e.closed||(e.revision+=1,e.reset))return;let n=e.wake;if(n===void 0){ok(e,t);return}e.wake=void 0;try{n(t)}catch(t){YO(`observation-delivery`,t),e.pendingCount=0,e.pendingReason=void 0,e.reset=!0}}function ck(e,t){for(let n of e)n.queued&&!n.settlementOnly&&n.sessionId!==t&&sk(n,`activity`)}function lk(e,t,n=`durable`){let r=rk.get(e);if(r!==void 0)for(let e of r)try{e.publish({kind:`session`,sessionId:t,reason:n})}catch(e){YO(`owner-observation-publish`,e);continue}}function uk(e){let t=rk.get(e);if(t!==void 0)for(let e of t)try{e.publish({kind:`agent-execution`})}catch(e){YO(`owner-execution-change-publish`,e)}}function dk(e){let t=new Map,n=new Set,r=rk.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){YO(`observation-listener-close`,e)}},s={publish:e=>{if(e.kind===`agent-execution`){ck(n,null);return}e.sessionId!==null&&e.reason!==`settlement`&&ck(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`||sk(t,e.reason===`settlement`?`durable`:e.reason)},observes:e=>[...t.get(e)??[]].some(e=>!e.closed&&!e.settlementOnly)};return r.add(s),rk.set(e,r),Object.freeze({register:(e,r)=>sr(()=>{if(i)return v(new W(`runtime`,`closed`,`Shiitake is closed`));if(n.size>=XO)return v(new W(`runtime`,`rejected`,`Observation capacity is exhausted`));let s={revision:0,sessionId:e,settlementOnly:r===`settlement`,closed:!1,pendingCount:0,pendingReason:void 0,queued:!0,reset:!1,wake:void 0},c=t.get(e)??new Set;c.add(s),t.set(e,c),n.add(s);let l=y(()=>a(s)),u=$n(e=>{let t=a(s);if(t!==void 0){e(x(t));return}let n=t=>{e(x(t))};return s.wake=n,y(()=>{s.wake===n&&(s.wake=void 0)})});return x(Object.freeze({get revision(){return s.revision},pollSignal:l,awaitSignal:u,close:()=>{o(s)},setQueued:e=>{s.closed||(s.queued=e)}}))}),close:y(()=>{if(!i){i=!0,r.delete(s),r.size===0&&rk.delete(e);for(let e of n)o(e)}})})}var fk=200,pk={onExcessProperty:`error`},mk=new TextEncoder,hk=H.pipe(z(V(0))),gk=M.pipe(z(hh(1)),z(B(e=>mk.encode(e).byteLength<=256)));D(P({limit:k(H.pipe(z($m({minimum:1,maximum:fk})))),after:k(M)}),pk);var _k=U(mm([hk,gk]));D(_k),Qp(_k),D(P({session_id:gk,last_activity_at:hk,state:L([`needs_you`,`running`,`errored`,`done`]),bytes:H.pipe(z(V(0)))}),pk);var vk=O(P({extension_id:M,value_json:M})),yk=O(U(Dy)),bk=O(Oy),xk=Qp(U(Dy));function Sk(e){e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention_grants (
|
|
22
22
|
extension_id TEXT PRIMARY KEY
|
|
23
23
|
)`),e.sql.exec(`CREATE TABLE IF NOT EXISTS session_attention (
|
|
24
24
|
session_id TEXT NOT NULL REFERENCES sessions(id),
|
|
@@ -41,7 +41,7 @@ Defaulting to 2020, but this will stop working in the future.`)),t.ecmaVersion=1
|
|
|
41
41
|
PRIMARY KEY (session_id, work_id)
|
|
42
42
|
)`)}function fA(e,t,n,r){e.sql.exec(`INSERT OR IGNORE INTO session_work_senders
|
|
43
43
|
(session_id, work_id, agent_id, sender_session_id, name)
|
|
44
|
-
VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function pA(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=cA(r);return lA({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function mA(e,t,n){let r=pA(e,t,n);return r===void 0?[]:hA(e,t,[r])}function hA(e,t,n){return Ck(e,t).filter(e=>n.some(t=>e.waitingOn?.agentId===t.agentId&&e.waitingOn.sessionId===t.sessionId)).slice(0,sA).map(e=>({itemId:e.id,kind:e.kind,summary:e.summary}))}var gA=new TextEncoder,_A=new TextDecoder,vA=/^[A-Za-z0-9_-]+$/u,yA=P({v:j(1),generation:M.pipe(z(hh(1)),z(vh(128)),z(B(e=>gA.encode(e).byteLength<=128))),sequence:H.pipe(z(Xm(0)),z(Qm(2**53-1)))}),bA={onExcessProperty:`error`},xA=D(yA,bA),SA=D(U(yA),bA);function CA(e){let t=xA({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(gA.encode(n).byteLength>384)return;let r=Fs(n);return gA.encode(r).byteLength<=512?r:void 0}function wA(e){if(gA.encode(e).byteLength>512||!vA.test(e))return;let t=Is(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=_A.decode(t.success),r=SA(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&Fs(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var TA=M.check(hh(1),vh(256)),EA=I([P({agentId:TA,sessionId:TA,...Lk.fields}),P({agentId:TA,sessionId:k(TA),...zk.fields})]),DA=`fungi_agent_reply`,OA=RegExp(`<(?=\\s*/?\\s*${DA})`,`giu`);function kA(e){return e.replace(OA,`<`)}function AA(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function jA(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]),`<${DA} ${t.map(([e,t])=>`${e}="${AA(t)}"`).join(` `)}>`}function MA(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:kA(e.text)}:e):kA(e.content);if(t===void 0)return{...e,content:n};let r=jA(t),i=`</${DA}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var NA={onExcessProperty:`error`},PA=new TextEncoder,FA=e=>M.pipe(z(hh(1)),z(B(t=>PA.encode(t).byteLength<=e))),IA=FA(256),LA=FA(4096),RA=M.pipe(z(Pm(/^[0-9a-f]{64}$/u))),zA=ym(()=>I([M,N,cm,om,F(zA),fm(M,zA)])),BA=P({type:j(`text`),text:M,textSignature:k(M)}),VA=P({type:j(`thinking`),thinking:M,thinkingSignature:k(M),redacted:k(cm)}),HA=P({type:j(`image`),data:M,mimeType:M}),UA=P({type:j(`toolCall`),id:M,name:M,arguments:fm(M,zA),thoughtSignature:k(M),namespace:k(M),argumentsError:k(M)}),WA=P({input:N,output:N,cacheRead:N,cacheWrite:N,cacheWrite1h:k(N),reasoning:k(N),totalTokens:N,cost:P({input:N,output:N,cacheRead:N,cacheWrite:N,total:N})}),GA=P({role:j(`user`),content:I([M,gm(F(I([BA,HA])))]),timestamp:N}),KA=P({role:j(`user`),content:M,timestamp:N}),qA=P({name:M,description:M,parameters:fm(M,zA),constrainedSampling:k(I([j(!1),P({type:j(`json_schema`),strict:L([`prefer`,`require`])}),P({type:j(`grammar`),variants:P({openai_lark:k(M),openai_regex:k(M)})})]))}),JA=I([P({role:j(`system`),content:I([M,gm(F(BA))]),sections:k(fm(M,I([M,om]))),toolsAdded:k(gm(F(qA))),toolsRemoved:k(gm(F(P({name:M})))),timestamp:N}),GA,P({role:j(`assistant`),content:gm(F(I([BA,VA,UA]))),api:M,provider:M,model:M,responseModel:k(M),responseId:k(M),diagnostics:k(gm(F(P({type:M,timestamp:N,error:k(P({name:k(M),message:M,stack:k(M),code:k(I([M,N]))})),details:k(fm(M,zA))})))),usage:WA,stopReason:L([`pending`,`stop`,`length`,`toolUse`,`error`,`aborted`,`deferred`]),deferred:k(P({provider:M,modelId:M,api:M,id:M,expiresAt:k(N),pollAfterMs:k(N),data:k(zA)})),errorMessage:k(M),providerError:k(M),rawStopReason:k(M),providerThinkingLevel:k(M),endTurn:k(cm),timestamp:N,durationMs:k(N)}),P({role:j(`toolResult`),toolCallId:M,toolName:M,content:gm(F(I([BA,HA]))),usage:k(WA),isError:cm,timestamp:N,durationMs:k(N)})]),YA=L([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),XA=ym(()=>P({kind:YA,value:IA,parent:A(XA)})),ZA=I([P({type:j(`auto_retry_start`),run:XA,attempt:N,maxAttempts:N,delayMs:N,dueAt:H.check(V(0)),errorMessage:M}),P({type:j(`auto_retry_attempt`),run:XA,attempt:N}),P({type:j(`auto_retry_end`),run:XA,attempt:N,success:cm,finalError:k(M)})]),QA=P({core:RA,extensions:F(mm([IA,M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)))])).pipe(z(vh(128)))}),$A=P({content:gm(F(I([BA,HA]))),usage:A(WA),isError:cm,terminate:A(cm)}),ej={workId:IA},tj=98304,nj=L([`manual`,`threshold`,`overflow`]),rj=I([P({...ej,kind:j(`sandbox_failure`),event:FO}),P({kind:j(`document`),workId:om,extensionId:IA,name:IA,valueJson:M}),P({kind:j(`model_preference`),workId:om,preference:R(Ny)}),P({...ej,kind:j(`command`),meta:k(HO),reply:k(EA),delivery:k(L([`steer`,`followUp`])),requestId:IA,targetWorkId:k(IA),receiptId:IA,message:GA,contract:QA}),P({...ej,kind:j(`command`),work:j(`compact`),instructions:k(ib),meta:k(HO),requestId:IA,receiptId:IA,timestamp:H.check(V(0)),contract:QA}),P({kind:j(`operator`),workId:om,requestId:IA,author:L([`operator`,`party`]),meta:k(HO),message:KA}),P({...ej,kind:j(`cancellation`),requestId:IA,receiptId:IA,targetWorkId:IA,meta:k(HO)}),P({...ej,kind:j(`model_selection`),provider:IA,model:IA,catalogRevision:IA,definitionRevision:IA,selectionPolicyRevision:IA}),P({...ej,kind:j(`run_started`),run:XA,contract:QA}),P({...ej,kind:j(`turn_started`),run:XA,turn:XA}),P({...ej,kind:j(`model_prompt`),run:XA,turn:XA,attempt:N.pipe(z(th()),z(Xm(0))),contract:QA,systemPrompt:M.pipe(z(B(e=>PA.encode(e).byteLength<=1048576)))}),P({...ej,kind:j(`message_start`),run:XA,turn:XA,message:XA,role:L([`assistant`,`system`,`toolResult`,`user`]),partial:k(P({text:M.pipe(z(B(e=>PA.encode(e).byteLength<=tj))),offset:N.pipe(z(th()),z(V(0)))}))}),P({...ej,kind:j(`message`),data:k(zA),run:XA,turn:XA,message:XA,value:JA}),P({...ej,kind:j(`tool_intent`),replay:L([`safe`,`unsafe`]).pipe(Om(x(`unsafe`))),contract:QA,run:XA,turn:XA,toolCall:XA,call:UA}),P({...ej,kind:j(`tool_outcome`),data:k(zA),run:XA,turn:XA,toolCall:XA,call:UA,result:$A}),P({...ej,kind:j(`live_retry`),event:ZA}),P({...ej,kind:j(`compaction`),head:IA,model:mm([GA]),data:P({reason:k(nj),resumesRun:cm,tokensBefore:N,tokensAfter:k(N),usage:WA,contextRevision:IA,receipt:k(LA),details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})}),P({...ej,kind:j(`compaction_checkpoint`),trigger:nj,resumesRun:cm,head:IA,contextRevision:IA,summary:M,tokensBefore:N,usage:WA,details:P({readFiles:F(M),modifiedFiles:F(M)})}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`nothing_to_compact`),diagnostic:k(M.check(vh(200)))}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`failed`),usage:k(WA),diagnostic:k(M.check(vh(200)))}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`stale`),usage:k(WA)}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`insufficient`),usage:k(WA)}),P({...ej,kind:j(`run_terminal`),run:XA,terminal:XA,diagnostic:k(M.check(vh(200))),outcome:L([`completed`,`cancelled`,`failed`])}),P({...ej,kind:j(`work_terminal`),diagnostic:k(M),outcome:L([`completed`,`interrupted`,`cancelled`,`failed`])})]),ij=qh(rj);function aj(e){return{kind:e.kind,workId:e.workId,run:e.run,turn:e.turn,message:e.message,role:e.role}}function oj(e,t){return ij(dj(uj(e)),dj(uj(t)))}var sj=U(rj),cj=U(am),lj=D(sj,NA),uj=Qp(cj),dj=O(sj,NA);function fj(e){return`work`in e}function pj(e){return e.kind===`command`&&!fj(e)?e:void 0}function mj(e){return fj(e)?e.timestamp:e.message.timestamp}function hj(e){return MA(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 gj(e){return MA(e.message,e.reply)}function _j(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 vj(e){return
|
|
44
|
+
VALUES (?, ?, ?, ?, ?)`,t,n,r.agentId,r.sessionId,r.name)}function pA(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=cA(r);return lA({agentId:i.agent_id,sessionId:i.sender_session_id,name:i.name})}function mA(e,t,n){let r=pA(e,t,n);return r===void 0?[]:hA(e,t,[r])}function hA(e,t,n){return Ck(e,t).filter(e=>n.some(t=>e.waitingOn?.agentId===t.agentId&&e.waitingOn.sessionId===t.sessionId)).slice(0,sA).map(e=>({itemId:e.id,kind:e.kind,summary:e.summary}))}var gA=new TextEncoder,_A=new TextDecoder,vA=/^[A-Za-z0-9_-]+$/u,yA=P({v:j(1),generation:M.pipe(z(hh(1)),z(vh(128)),z(B(e=>gA.encode(e).byteLength<=128))),sequence:H.pipe(z(Xm(0)),z(Qm(2**53-1)))}),bA={onExcessProperty:`error`},xA=D(yA,bA),SA=D(U(yA),bA);function CA(e){let t=xA({v:1,...e});if(t._tag===`Failure`)return;let n=JSON.stringify(t.success);if(gA.encode(n).byteLength>384)return;let r=Fs(n);return gA.encode(r).byteLength<=512?r:void 0}function wA(e){if(gA.encode(e).byteLength>512||!vA.test(e))return;let t=Is(e);if(t._tag===`Failure`||t.success.byteLength>384)return;let n=_A.decode(t.success),r=SA(n);if(r._tag===`Failure`)return;let i=JSON.stringify(r.success);if(i===n&&Fs(i)===e)return Object.freeze({generation:r.success.generation,sequence:r.success.sequence})}var TA=M.check(hh(1),vh(256)),EA=I([P({agentId:TA,sessionId:TA,...Lk.fields}),P({agentId:TA,sessionId:k(TA),...zk.fields})]),DA=`fungi_agent_reply`,OA=RegExp(`<(?=\\s*/?\\s*${DA})`,`giu`);function kA(e){return e.replace(OA,`<`)}function AA(e){return e.replaceAll(`&`,`&`).replaceAll(`"`,`"`).replaceAll(`<`,`<`).replaceAll(`>`,`>`)}function jA(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]),`<${DA} ${t.map(([e,t])=>`${e}="${AA(t)}"`).join(` `)}>`}function MA(e,t){let n=Array.isArray(e.content)?e.content.map(e=>e.type===`text`?{...e,text:kA(e.text)}:e):kA(e.content);if(t===void 0)return{...e,content:n};let r=jA(t),i=`</${DA}>`;return{...e,content:Array.isArray(n)?[{type:`text`,text:r},...n,{type:`text`,text:i}]:`${r}\n${n}\n${i}`}}var NA={onExcessProperty:`error`},PA=new TextEncoder,FA=e=>M.pipe(z(hh(1)),z(B(t=>PA.encode(t).byteLength<=e))),IA=FA(256),LA=FA(4096),RA=M.pipe(z(Pm(/^[0-9a-f]{64}$/u))),zA=ym(()=>I([M,N,cm,om,F(zA),fm(M,zA)])),BA=P({type:j(`text`),text:M,textSignature:k(M)}),VA=P({type:j(`thinking`),thinking:M,thinkingSignature:k(M),redacted:k(cm)}),HA=P({type:j(`image`),data:M,mimeType:M}),UA=P({type:j(`toolCall`),id:M,name:M,arguments:fm(M,zA),thoughtSignature:k(M),namespace:k(M),argumentsError:k(M)}),WA=P({input:N,output:N,cacheRead:N,cacheWrite:N,cacheWrite1h:k(N),reasoning:k(N),totalTokens:N,cost:P({input:N,output:N,cacheRead:N,cacheWrite:N,total:N})}),GA=P({role:j(`user`),content:I([M,gm(F(I([BA,HA])))]),timestamp:N}),KA=P({role:j(`user`),content:M,timestamp:N}),qA=P({name:M,description:M,parameters:fm(M,zA),constrainedSampling:k(I([j(!1),P({type:j(`json_schema`),strict:L([`prefer`,`require`])}),P({type:j(`grammar`),variants:P({openai_lark:k(M),openai_regex:k(M)})})]))}),JA=I([P({role:j(`system`),content:I([M,gm(F(BA))]),sections:k(fm(M,I([M,om]))),toolsAdded:k(gm(F(qA))),toolsRemoved:k(gm(F(P({name:M})))),timestamp:N}),GA,P({role:j(`assistant`),content:gm(F(I([BA,VA,UA]))),api:M,provider:M,model:M,responseModel:k(M),responseId:k(M),diagnostics:k(gm(F(P({type:M,timestamp:N,error:k(P({name:k(M),message:M,stack:k(M),code:k(I([M,N]))})),details:k(fm(M,zA))})))),usage:WA,stopReason:L([`pending`,`stop`,`length`,`toolUse`,`error`,`aborted`,`deferred`]),deferred:k(P({provider:M,modelId:M,api:M,id:M,expiresAt:k(N),pollAfterMs:k(N),data:k(zA)})),errorMessage:k(M),providerError:k(M),rawStopReason:k(M),providerThinkingLevel:k(M),endTurn:k(cm),timestamp:N,durationMs:k(N)}),P({role:j(`toolResult`),toolCallId:M,toolName:M,content:gm(F(I([BA,HA]))),usage:k(WA),isError:cm,timestamp:N,durationMs:k(N)})]),YA=L([`run`,`turn`,`message`,`tool_call`,`tool_result`,`terminal`]),XA=ym(()=>P({kind:YA,value:IA,parent:A(XA)})),ZA=I([P({type:j(`auto_retry_start`),run:XA,attempt:N,maxAttempts:N,delayMs:N,dueAt:H.check(V(0)),errorMessage:M}),P({type:j(`auto_retry_attempt`),run:XA,attempt:N}),P({type:j(`auto_retry_end`),run:XA,attempt:N,success:cm,finalError:k(M)})]),QA=P({core:RA,extensions:F(mm([IA,M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)))])).pipe(z(vh(128)))}),$A=P({content:gm(F(I([BA,HA]))),usage:A(WA),isError:cm,terminate:A(cm)}),ej={workId:IA},tj=98304,nj=L([`manual`,`threshold`,`overflow`]),rj=I([P({...ej,kind:j(`sandbox_failure`),event:FO}),P({kind:j(`document`),workId:om,extensionId:IA,name:IA,valueJson:M}),P({kind:j(`model_preference`),workId:om,preference:R(Ny)}),P({...ej,kind:j(`command`),meta:k(HO),reply:k(EA),delivery:k(L([`steer`,`followUp`])),requestId:IA,targetWorkId:k(IA),receiptId:IA,message:GA,contract:QA}),P({...ej,kind:j(`command`),work:j(`compact`),instructions:k(ib),meta:k(HO),requestId:IA,receiptId:IA,timestamp:H.check(V(0)),contract:QA}),P({kind:j(`operator`),workId:om,requestId:IA,author:L([`operator`,`party`]),meta:k(HO),message:KA}),P({...ej,kind:j(`cancellation`),requestId:IA,receiptId:IA,targetWorkId:IA,meta:k(HO)}),P({...ej,kind:j(`model_selection`),provider:IA,model:IA,catalogRevision:IA,definitionRevision:IA,selectionPolicyRevision:IA}),P({...ej,kind:j(`run_started`),run:XA,contract:QA}),P({...ej,kind:j(`turn_started`),run:XA,turn:XA}),P({...ej,kind:j(`model_prompt`),run:XA,turn:XA,attempt:N.pipe(z(th()),z(Xm(0))),contract:QA,systemPrompt:M.pipe(z(B(e=>PA.encode(e).byteLength<=1048576)))}),P({...ej,kind:j(`message_start`),run:XA,turn:XA,message:XA,role:L([`assistant`,`system`,`toolResult`,`user`]),partial:k(P({text:M.pipe(z(B(e=>PA.encode(e).byteLength<=tj))),offset:N.pipe(z(th()),z(V(0)))}))}),P({...ej,kind:j(`message`),data:k(zA),run:XA,turn:XA,message:XA,value:JA}),P({...ej,kind:j(`tool_intent`),replay:L([`safe`,`unsafe`]).pipe(Om(x(`unsafe`))),contract:QA,run:XA,turn:XA,toolCall:XA,call:UA}),P({...ej,kind:j(`tool_outcome`),data:k(zA),run:XA,turn:XA,toolCall:XA,call:UA,result:$A}),P({...ej,kind:j(`live_retry`),event:ZA}),P({...ej,kind:j(`compaction`),head:IA,model:mm([GA]),data:P({reason:k(nj),resumesRun:cm,tokensBefore:N,tokensAfter:k(N),usage:WA,contextRevision:IA,receipt:k(LA),details:k(P({readFiles:F(M),modifiedFiles:F(M)}))})}),P({...ej,kind:j(`compaction_checkpoint`),trigger:nj,resumesRun:cm,head:IA,contextRevision:IA,summary:M,tokensBefore:N,usage:WA,details:P({readFiles:F(M),modifiedFiles:F(M)})}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`nothing_to_compact`),diagnostic:k(M.check(vh(200)))}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`failed`),usage:k(WA),diagnostic:k(M.check(vh(200)))}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`stale`),usage:k(WA)}),P({...ej,kind:j(`compaction_notice`),trigger:nj,result:j(`insufficient`),usage:k(WA)}),P({...ej,kind:j(`run_terminal`),run:XA,terminal:XA,diagnostic:k(M.check(vh(200))),outcome:L([`completed`,`cancelled`,`failed`])}),P({...ej,kind:j(`work_terminal`),diagnostic:k(M),outcome:L([`completed`,`interrupted`,`cancelled`,`failed`])})]),ij=qh(rj);function aj(e){return{kind:e.kind,workId:e.workId,run:e.run,turn:e.turn,message:e.message,role:e.role}}function oj(e,t){return ij(dj(uj(e)),dj(uj(t)))}var sj=U(rj),cj=U(am),lj=D(sj,NA),uj=Qp(cj),dj=O(sj,NA);function fj(e){return`work`in e}function pj(e){return e.kind===`command`&&!fj(e)?e:void 0}function mj(e){return fj(e)?e.timestamp:e.message.timestamp}function hj(e){return MA(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 gj(e){return MA(e.message,e.reply)}function _j(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 vj(e){return zt(lj(e),e=>e.kind===`command`&&!fj(e)&&e.delivery===void 0?{...e,delivery:`followUp`}:e)}function yj(e){let t=uj(e);return dj(t),t}var bj=bg({family:`session`,version:1,kinds:{session:{prefix:`session`},work:{prefix:`session_work`},fact:{prefix:`session_fact`},receipt:{prefix:`session_receipt`}}}),xj=M.pipe(z(hh(1))),Sj=H.pipe(z(V(0))),Cj={onExcessProperty:`error`},wj=P({value_json:M}),Tj=P({state_version:H.pipe(z(V(1))),revision:xj}),Ej=P({status:L([`running`,`stopped`]),reason:R(M),stopped_at:R(Sj),revision:xj}),Dj=P({extension_id:xj,key:xj,job_id:xj}),Oj=P({collection:xj,key:xj,value_json:M}),kj=P({sequence:Sj});function Aj(e){return new W(`store`,`unavailable`,e)}function jj(e,t,n){let r=D(e,Cj);return t.map(e=>{let t=r(e);if(t._tag===`Failure`)throw Aj(n);return t.success})}function Mj(e){e.transactionSync(()=>{e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_extension_records (
|
|
45
45
|
extension_id TEXT NOT NULL,
|
|
46
46
|
collection TEXT NOT NULL,
|
|
47
47
|
key TEXT NOT NULL,
|
|
@@ -196,10 +196,10 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
196
196
|
session_id TEXT PRIMARY KEY,
|
|
197
197
|
version INTEGER NOT NULL,
|
|
198
198
|
grants_json TEXT NOT NULL
|
|
199
|
-
)`)}function PM(e,t,n){let r=kM(n);if(
|
|
199
|
+
)`)}function PM(e,t,n){let r=kM(n);if(Ae(r))throw new W(`contract`,`invalid`,`Session grants delivery is invalid`);let i=jM(r.success.grants),a=FM(e,t);if(a!==void 0){if(r.success.version<a.version)throw new W(`contract`,`conflict`,`Session grants delivery is older than the stored delivery`);if(r.success.version===a.version&&a.grantsJson===i)return`unchanged`}return e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
|
|
200
200
|
VALUES (?, ?, ?)
|
|
201
201
|
ON CONFLICT(session_id) DO UPDATE SET
|
|
202
|
-
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function FM(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=MM(n);if(
|
|
202
|
+
version = excluded.version, grants_json = excluded.grants_json`,t,r.success.version,i),`applied`}function FM(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=MM(n);if(Ae(r))throw new W(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:r.success.version,grantsJson:r.success.grants_json}}function IM(e,t){let n=FM(e,t);if(n===void 0)return null;let r=AM(n.grantsJson);if(Ae(r))throw new W(`store`,`unavailable`,`Stored Session grants are invalid`);return{version:n.version,grants:r.success}}function LM(e,t,n){e.sql.exec(`INSERT INTO session_tool_grants (session_id, version, grants_json)
|
|
203
203
|
SELECT ?, version, grants_json FROM session_tool_grants WHERE session_id = ?`,n,t)}var RM=200,zM={onExcessProperty:`error`},BM=new TextEncoder,VM=M.pipe(z(hh(1)),z(B(e=>BM.encode(e).byteLength<=256))),HM=H.pipe(z(V(0))),UM=L([0,1,2]),WM=L([`needs_you`,`running`,`errored`,`done`]),GM=L([`completed`,`failed`,`cancelled`,`outcome_unknown`,`interrupted`]),KM=P({session_id:VM,title:R(M),created_at:HM,last_activity_at:HM,settled_at:R(HM),state:WM,tier:UM}),qM=D(KM,zM);D(KM.mapFields(Ep({revision:HM})),zM),D(P({revision:HM}),zM);var JM=D(P({outcome:R(GM)}),zM),YM=U(mm([UM,HM,VM])),XM=D(YM),ZM=Qp(YM),QM=`session_id, title, created_at, last_activity_at, settled_at, state, tier`;function $M(e){return new W(`store`,`unavailable`,e)}function eN(e){switch(e){case`needs_you`:return 0;case`running`:return 1;case`errored`:case`done`:return 2}}function tN(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 nN(e){e.sql.exec(`
|
|
204
204
|
CREATE TABLE IF NOT EXISTS session_inbox (
|
|
205
205
|
session_id TEXT PRIMARY KEY REFERENCES sessions(id),
|
|
@@ -804,6 +804,6 @@ Only summarize information explicitly present above. Do not infer or recreate la
|
|
|
804
804
|
VALUES (?, '/', ?, NULL, ?, ?, NULL)`,r,t.sessionId,i,i),LM(e,t.sessionId,r);let a=null,o=null,s=1,c=new Map,l=0;for(;;){let t=FF(e,n,{after:l,from:`oldest`,rows:pF});for(let n of t.rows){let t=bj.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
|
|
805
805
|
(id, session_id, parent_id, sequence, type, role, state,
|
|
806
806
|
request_id, work_id, data_json, timestamp, completed_at)
|
|
807
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,sP(i),n.state,oP(i),i.workId,yj(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=jF(e,{sessionId:t.sessionId});for(let t of rM(e,(t,n)=>BF(e,u,t,n)))dF(e,{sessionId:r,id:bj.fact.generate(),entry:t});return aN(e,{sessionId:r,activityAt:i,title:iP(e,r)}),r})}function jI(e,t,n,r){if(pP(e,t)===void 0)throw $(`Session document owner is unavailable`);return BF(e,jF(e,{sessionId:t}),n,r)}function MI(e,t,n,r,i){if(pP(e,t)===void 0)throw $(`Session document owner is unavailable`);dF(e,{sessionId:t,id:bj.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var NI=2097152,PI=200,FI=200,II=new TextEncoder;function LI(e){return new W(`store`,`unavailable`,e)}function RI(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)AP(e,t,n)!==void 0&&r.set(n,n);return r}function zI(e,t){return n=>{let r=AP(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function BI(e,t,n){return{commandIds:RI(e,t,n),diagnostics:UI(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:zI(e,t)}}function VI(e,t,n,r){let i=HF(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)&&AP(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:zI(e,t)}}function HI(e,t){let n=pj(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:_j(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 UI(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 GI=new WeakMap;function KI(e){let t=GI.get(e);if(t===void 0)throw LI(`Session compaction entry position is unavailable`);return t}function qI(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??LF(e,t,a.head);if(o===void 0)throw LI(`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});GI.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function JI(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 YI(e){return II.encode(JSON.stringify(e)).byteLength}function XI(e,t){let n=CA({generation:e,sequence:t});if(n===void 0)throw LI(`Session cursor is unavailable`);return n}function ZI(e,t,n,r,i=!1){let a=HI(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:YI(a))+(o===void 0?0:YI(o))+(s===void 0?0:YI(s));if(c>NI)throw LI(`Session projection entry exceeds the read bound`);return e.bytes+c>NI?!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 QI(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==FI;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!ZI(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw LI(`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 $I(e){return Array.isArray(e)}function eL(e,t){let{commands:n,total:r}=TP(e,t,FI+1,`prompts`),i=[],a=II.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=nL(e),n=II.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===FI||a+n>NI)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function tL(e,t,n){let r=CP(e,t,n);return r===void 0?null:nL(r)}function nL(e){let t=pj(e.entry);if(t===void 0)throw LI(`Pending Session prompt is unavailable`);let n=t.message.content,r=$I(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 rL(e,t,n){let r=wA(n);if(r?.generation===t.rootId)return IF(e,t,r.sequence)?r.sequence:void 0}function iL(e,t,n,r,i=()=>({})){return bF(e,t,()=>{let a=eL(e,t),o=jF(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:Ck(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:rL(e,o,n.before);if(c===void 0)throw LI(`Session read cursor is unavailable`);let l=FF(e,o,{before:c,from:`newest`,rows:FI}),u=QI(l.rows,l.more,n.limit,VI(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:XI(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?XI(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:qI(e,o,d),compactionNotices:JI(d),pending:a,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:Ck(e,t)},ee=uA(e,t);return ee!==void 0&&Object.assign(m,{parent:ee}),Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var aL=Object.freeze({kind:`reset`});function oL(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return IF(e,t,n.sequence)?n.sequence:void 0}function sL(e,t,n,r,i,a,o,s,c){let l=FF(e,t,{after:n,from:`oldest`,rows:FI}),u=QI(l.rows,l.more,PI,VI(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:XI(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:qI(e,t,d),compactionNotices:JI(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 cL(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:wA(n);return n!==void 0&&s===void 0?aL:bF(e,t,()=>{let c=eL(e,t),l=jF(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:Ck(e,t),pending:c}],hasMore:!1}:aL;let u=oL(e,l,s);return u===void 0?aL:sL(e,l,u,r,i,a(),Ck(e,t),c,o)})}function lL(e,t,n){let r=AP(e,t,n);if(r===void 0)throw LI(`Accepted Session command is unavailable`);if(!NP(e,t,r.entry.workId))return;let i=PP(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=Tg(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:oA(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:mA(e,t,r.entry.workId)}}var uL=65536,dL=250,fL=2048,pL=new TextEncoder,mL=()=>({chunks:[],length:0,bytes:0});function hL(e,t){for(let n=0;n<t.length;){let r=Math.min(n+fL,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=pL.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=fL?(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>uL&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function gL(e){return e.chunks[0]?.offset??0}function _L(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function vL(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:_L(e.text,gL(e.text)),thinking:_L(e.thinking,gL(e.thinking)),textOffset:gL(e.text),thinkingOffset:gL(e.thinking),textTruncated:gL(e.text)>0,thinkingTruncated:gL(e.thinking)>0}}function yL(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function bL(e,t,n,r){let i=xL.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<gL(a.text)||c<gL(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:_L(a.text,s)},thinking:{offset:c,append:_L(a.thinking,c)}}}var xL=new WeakMap;function SL(e,t,n){let r=xL.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var CL=D(P({droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))}),{onExcessProperty:`error`});function wL(e,t){return b(function*(){let n=yield*EL(e,t),r=()=>{lk(e,t.sessionId,`progress`)};return{started:e=>y(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>y(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=CL(e.result.data);if(ke(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(`
|
|
808
|
-
`).length>200||i.success.droppedBytes>i.success.totalBytes||(n.slots.set(e.toolCall.value,{toolCallId:e.call.id,revision:(t?.revision??0)+1,tail:a,...i.success}),r())}),terminal:e=>y(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function TL(e){let t=xL.get(e);if(t!==void 0)return t;let n=new Map;return xL.set(e,n),n}function EL(e,t){return b(function*(){let n=TL(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*wr(()=>y(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&lk(e,t.sessionId,`progress`))})),i})}function DL(e){return new W(`runtime`,`rejected`,e)}function OL(e,t,n){let r=TL(e).get(t);return vL(r?.workId===n?r.value:null)}function kL(e,t,n){let r=xL.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function AL(e,t,n,r){return b(function*(){let i=yield*EL(e,t);if(r!==void 0&&i.value===null){let n=mL();n.length=r.offset,hL(n,r.text),i.value={recovered:!0,messageId:r.messageId,revision:1,text:n,thinking:mL()},lk(e,t.sessionId,`progress`)}let a,o=0,s=0,c,l=()=>{c!==void 0&&clearTimeout(c),c=void 0},u=()=>{l();let n=i.value;n!==null&&(s=n.text.length+n.thinking.length,lk(e,t.sessionId,`progress`))},d=y(()=>{l();let n=i.value!==null;i.value=null,n&&lk(e,t.sessionId,`progress`),a=void 0});return yield*wr(()=>d),Object.freeze({started:e=>y(()=>{l(),a=e,o=0,i.value?.recovered!==!0&&(i.value=null),s=0}),update:n=>sr(()=>{let r=a;if(r===void 0)return v(DL(`Mule progress arrived before its message start`));if(r.run.value!==n.run.value||r.turn.value!==n.turn.value||r.message.value!==n.message.value)return v(DL(`Mule progress identity conflicts`));let l=n.event;if(l.type!==`text_delta`&&l.type!==`thinking_delta`||l.delta.length===0)return C;let d=i.value===null||i.value.recovered===!0,f=(d?null:i.value)??{messageId:n.message.value,revision:0,text:mL(),thinking:mL()};hL(l.type===`text_delta`?f.text:f.thinking,l.delta),f.revision++,i.value=f;let p=f.text.length+f.thinking.length;d||p-s>=4096?u():c??=setTimeout(u,100);let m=Date.now();return l.type!==`text_delta`||m-o<dL?C:(o=m,oi({try:()=>{oI(e,{sessionId:t.sessionId,entry:{kind:`message_start`,workId:t.commandId,run:r.run,turn:r.turn,message:r.message,role:`assistant`},text:_L(f.text,gL(f.text)),offset:gL(f.text)})},catch:e=>new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)}))}),terminal:e=>d.pipe(g(n(e)))})})}var jL=new WeakMap;function ML(e){let t=jL.get(e);if(t!==void 0)return t;let n=new Map;return jL.set(e,n),n}function NL(e,t){return ML(e).get(t)??null}function PL(e,t,n){ML(e).set(t,Object.freeze({trigger:n})),lk(e,t,`progress`)}function FL(e,t){ML(e).delete(t)&&lk(e,t,`progress`)}var IL=Object.freeze({admitNew:()=>{}});function LL(e){return e===void 0?IL:Object.freeze({admitNew:()=>{if(e.underPressure())throw new W(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function RL(e,t){let n=cI(e,t);return lk(e,t.sessionId),n}function zL(e,t){let n=dI(e,t);return lk(e,t.sessionId),n}function BL(e,t){let n=fI(e,t);return n!==`stale`&&lk(e,t.sessionId),n}function VL(e){return new W(`store`,`rejected`,e)}function HL(e){return new W(`store`,`conflict`,e)}function UL(e){return oi({try:e,catch:e=>e instanceof W?e:new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function WL(e){return UL(()=>{oF(e)})}function GL(e,t,n,r,i,a,o){return UL(()=>{let s=EI(e,t,n,i,a,r,o);return s?.delivery===`new`&&lk(e,t,`settlement`),s})}function KL(e,t){return UL(()=>{let n=OP(e,t.sessionId,t.delivery,t.workId);return n.length>0&&lk(e,t.sessionId),n})}function qL(e,t){return UL(()=>{kP(e,t),lk(e,t.sessionId,`settlement`)})}function JL(e,t,n,r,i){return UL(()=>{let a=TI(e,t,n,r,i);return lk(e,t,`settlement`),a?.accepted})}function YL(e,t){return UL(()=>{OI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),lk(e,t.sessionId)})}function XL(e,t){return UL(()=>{kI(e,t)&&lk(e,t.sessionId)})}function ZL(e,t){return UL(()=>{let n=AI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return lk(e,n),Object.freeze({sessionId:n})})}function QL(e,t){return UL(()=>{let n=iI(e,{sessionId:xb(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&lk(e,t.sessionId),n})}function $L(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function eR(e,t){return UL(()=>{let n=AP(e,t.sessionId,t.commandFactId);if(n===void 0)throw VL(`Accepted Session command is unavailable`);let r=PP(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=$L(t.value);if(e!==``)return e}}return``})}function tR(e,t){return b(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*eR(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*UL(()=>{let n=AP(e,t.sessionId,i);if(n===void 0)throw VL(`Accepted Session command is unavailable`);if(hR(e,t.sessionId,i,n.entry.workId)===null)return;let r=gP(e,i);if(r===void 0)throw VL(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=gP(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw VL(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function nR(e,t,n){return UL(()=>{let r=AP(e,t.sessionId,t.commandFactId);if(r===void 0)throw VL(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=PP(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function rR(e,t){return UL(()=>{let n=AP(e,t.sessionId,t.commandFactId);if(n===void 0)throw VL(`Accepted Session command is unavailable`);return UI(PP(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function iR(e,t,n,r,i,a){return UL(()=>{let o=xb(t),s=wb(r);return yF(e,o,()=>a(iL(e,o,s,n(),i)),s.before===void 0?void 0:wA(s.before)?.sequence)})}function aR(e,t,n){return UL(()=>VP(e,Cb({requestId:t}),n))}function oR(e,t,n){return HP(e,Cb({requestId:t}),n)}function sR(e,t){return UL(()=>UP(e,{sessionId:xb(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{oN(e,t)}}))}function cR(e,t){return UL(()=>dN(e,t))}function lR(e,t,n,r,i,a,o,s){return UL(()=>{let c=xb(t);return yF(e,c,()=>s(cL(e,c,n,r,i,a,o)))})}function uR(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function dR(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 fR(e,t,n,r,i){i?.();let a=PP(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||oj(a.entry,n))return`replay`;throw HL(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=bj.fact.generate();if(gP(e,r)===void 0&&AP(e,t.sessionId,r)===void 0)return dF(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw VL(`Session fact identity allocation failed`)}function pR(e,t,n,r,i){e.transactionSync(()=>fR(e,t,n,r,i))===`new`&&lk(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`)}function mR(e,t,n){return UL(()=>{pR(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function hR(e,t,n,r){let i=AP(e,t,n);if(i?.entry.workId!==r)throw VL(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function gR(e,t,n,r){let i=hR(e,t,n,r),a=PP(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 _R(e,t){return UL(()=>{if(AP(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw VL(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};pR(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 vR(e,t,n,r,i){return UL(()=>{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}),pR(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?uR(e.run,a.run)&&dR(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?uR(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&uR(e.terminal,a.terminal):!1)})}function yR(e,t,n){return UL(()=>{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=PP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&uR(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!uR(i.entry.run,r.run)||!uR(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw HL(`Mule message-start identity conflicts`);return`replay`}if(i.entry.kind!==`message_start`||!oj(aj(i.entry),r))throw HL(`Mule message-start identity conflicts`);return`replay`}return dF(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&lk(e,t.sessionId)})}function bR(e,t,n,r){return UL(()=>{pR(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`&&uR(e.turn,r.turn)&&e.attempt===r.attempt&&dR(e.contract,n))})}function xR(e,t,n,r){return UL(()=>{let i={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value},a=n.data===void 0?i:{...i,data:n.data};e.transactionSync(()=>{let i=PP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&uR(e.message,n.message));if(i?.entry.kind===`message`){if(!oj(i.entry,a))throw HL(`Mule completed-message identity conflicts`)}else fF(e,{sessionId:t.sessionId,id:n.message.value,entry:a});let o=n.retry===void 0||n.value.role!==`assistant`?`replay`:TR(e,t,wR(n.retry,r),n.turn);return i?.entry.kind===`message`&&o===`replay`?`replay`:`new`})===`new`&&lk(e,t.sessionId)})}function SR(e,t,n,r){return UL(()=>{pR(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`&&uR(e.toolCall,r.toolCall)&&dR(e.contract,n))})}function CR(e,t,n){return UL(()=>{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};pR(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&uR(e.toolCall,n.toolCall))})}function wR(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+qO({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,dueAt:e.dueAt,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function TR(e,t,n,r){let i=PP(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&uR(e.turn,r));if(i===void 0)throw HL(`Retry has no recorded turn`);return fR(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&&uR(e.event.run,n.run))}function ER(e,t,n,r){return UL(()=>{e.transactionSync(()=>TR(e,t,n,r))===`new`&&lk(e,t.sessionId)}).pipe(lt(DR))}var DR=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function OR(e,t,n,r,i){return b(function*(){let a=yield*AL(e,t,n=>xR(e,t,n,r),i),o=yield*wL(e,t),s=(i,s)=>{switch(i.type){case`model_prompt`:return bR(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return vR(e,t,n,i,s);case`message_start`:return i.value.role===`user`?C:yR(e,t,i).pipe(g(i.value.role===`assistant`?a.started(i):C));case`message_update`:return a.update(i);case`message_end`:return i.value.role===`user`?C:i.value.role===`assistant`?a.terminal(i):xR(e,t,i,r);case`tool_execution_start`:return SR(e,t,n,i).pipe(g(o.started(i)));case`tool_execution_end`:return CR(e,t,i).pipe(g(o.terminal(i)));case`tool_execution_update`:return o.update(i);case`turn_end`:return C}};return(e,t)=>s(e,t).pipe(lt(DR))})}function kR(e,t,n){return UL(()=>lL(e,xb(t),xb(n)))}var AR=NN.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),jR=P({requestId:k(M),meta:k(HO),data:k(zO),origin:k(AR),id:M,sequence:H.check(Xm(0)),commandId:R(M),value:JA}),MR=L([`manual`,`threshold`,`overflow`]),NR=P({queue:I([P({state:j(`idle`)}),P({state:j(`queued`),commandId:jh,runningWork:R(P({phase:L([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),P({state:j(`running`),commandId:jh})]),cancellationRequested:cm,retry:R(P({attempt:H.check(Xm(0)),maxAttempts:H.check(Xm(0)),delayMs:H.check(V(0)),errorMessage:M,scheduledAt:H.check(V(0))})),activeTool:R(M),lastModelChoiceSequence:R(H.check(Xm(0))),compaction:R(P({trigger:MR}))}),PR=M,FR=fm(M,I([P({status:j(`running`),revision:PR,value:zO,catalog:k(zO)}),P({status:j(`stopped`),revision:PR,reason:M})])),IR=P({id:M,version:M,revision:PR,status:L([`running`,`stopped`]),reason:R(M),stoppedAt:R(N)}),LR=P({commandId:M,outcome:L([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:H.check(Xm(0)),diagnostic:R(M),meta:k(HO)}),RR=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),tokensBefore:N,tokensAfter:R(N),trigger:R(MR)}),zR=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),trigger:MR,result:L([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:R(M)}),BR=M.check(B(e=>new TextEncoder().encode(e).byteLength<=65536)),VR=P({messageId:M,revision:H.check(V(0)),text:BR,thinking:BR,textOffset:H.check(V(0)),thinkingOffset:H.check(V(0)),textTruncated:cm,thinkingTruncated:cm}),HR=P({commandId:M,requestId:M,meta:k(HO),origin:k(AR),text:M,images:k(F(Gy)),delivery:L([`steer`,`followUp`])}),UR=F(P({toolCallId:M,revision:H.check(V(0)),tail:M.check(B(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
|
|
809
|
-
`).length<=200)),droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))})).check(vh(4)),WR=P({total:H.check(V(0)),prompts:F(HR),hasMore:cm}),GR=P({tokens:H.check(V(0)),window:R(H.check(Xm(0)))}),KR=P({parent:k(Ty),sessionId:M,cursor:R(M),hasMore:cm,oldestCursor:k(R(M)),messages:F(jR),terminals:F(LR),sandboxFailures:k(F(FO)),compactions:k(F(RR)),compactionNotices:k(F(zR)),pending:WR,activity:NR,progress:R(VR),toolOutput:UR,extensions:FR,attention:Ay,context:k(GR)}),qR=I([P({kind:j(`heartbeat`)}),P({kind:j(`activity`),activity:NR}),P({kind:j(`tool_output`),toolOutput:UR,activity:NR}),P({kind:j(`update`),delivery:L([`replay`,`live`]),cursor:R(M),messages:F(jR),terminals:F(LR),sandboxFailures:k(F(FO)),compactions:k(F(RR)),compactionNotices:k(F(zR)),pending:WR,activity:NR,extensions:FR,attention:Ay,context:k(GR)}),P({kind:j(`progress`),progress:P({messageId:M,revision:H.check(V(0)),text:P({offset:H.check(V(0)),append:BR}),thinking:P({offset:H.check(V(0)),append:BR})}),activity:NR}),P({kind:j(`reset`),reason:j(`history_unavailable`),cursor:R(M),baseline:KR})]),JR=P({status:j(`accepted`),commandId:M,sessionId:k(M)});O(U(I([JR,P({status:j(`held`),reason:j(`recipient_offline`),message:j(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var YR=P({status:j(`unknown`)}),XR=O(U(I([JR,YR])));function ZR(e){return XR(e)}var QR=I([JR,YR,P({status:j(`too_late`),commandId:M})]),$R=P({sessionId:M}),ez=O(U(KR),{onExcessProperty:`error`}),tz=O(U(qR),{onExcessProperty:`error`}),nz=O(U(JR)),rz=O(U(QR)),iz=O(U($R)),az=O(U(zy)),oz=O(U(IR)),sz=O(U(F(IR))),cz=O(U(zO));function lz(e){return oz(e)}function uz(e){return sz(e)}function dz(e){return cz(e)}function fz(e){return nz(e)}function pz(e){return rz(e)}function mz(e){return O(U(R(HR)))(e)}function hz(e){return iz(e)}var gz=P({acceptedSender:R(M),delegator:R(M),terminal:LR,content:M,usage:F(P({provider:M,model:M,usage:WA})),toolCalls:H.check(V(0)),waitingOnYou:F(P({itemId:M,kind:M,summary:M})).check(vh(8))});function _z(e){return O(U(R(gz)))(e)??void 0}function vz(e){return ez(e)}function yz(e){return tz(e)}function bz(e){let t=az(e);return new W(t.boundary,t.cause,t.message,t.requestId)}var xz=O(U(P({sessions:F(I([P({sessionId:jh,createdAt:N,lastActivityAt:N,settledAt:k(N),title:M,state:L([`needs_you`,`running`,`errored`,`done`])}),P({sessionId:jh,state:j(`unavailable`)})])),next:A(jh)})));function Sz(e){let t=xz(e);return{sessions:t.sessions,next:t.next}}var Cz=O(U(P({sessionId:jh}))),wz=O(U(P({deleted:cm})));function Tz(e){return wz(e).deleted}function Ez(e){return Cz(e).sessionId}function Dz(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:OO(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function Oz(e,t){return Kn(e,t).then(e=>{if(ca(e))return e.value;let t=Gn(Xi(e.cause))??Ji(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function kz(e){let t=Pr(e);if(ca(t))return t.value;let n=Gn(Xi(t.cause))??Ji(t.cause);throw n instanceof Error?n:Error(String(n))}function Az(e){let t=by(e);return Object.freeze({[Symbol.asyncIterator]:()=>{let e=t[Symbol.asyncIterator]();return{next:()=>e.next(),return:()=>e.return?.()??Promise.resolve({done:!0,value:void 0})}}})}function jz(e,t){function n(e){return Oz(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>Oz(t.withdraw(e)),abort:()=>Oz(t.abort),send:(e,n)=>Oz(t.send(e,n)),cancel:e=>Oz(t.cancel(e)),latestPending:()=>Oz(t.latestPending),modelPreference:Object.freeze({read:()=>Oz(t.modelPreference.read),set:e=>Oz(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>Oz(n.call(e,t,r))})},read:e=>Oz(t.read(e)),readSettlement:(e,n)=>Oz(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>Az(t.subscribe(e)),watch:e=>Oz(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:Az(e.changes),close:()=>Oz(e.close)}))})}function Mz(e,t){let n=t??`local:${rg()}`;return Object.freeze({createSession:t=>Oz(e.createSession(t)),deleteSession:t=>Oz(e.deleteSession(t)),listSessions:t=>Oz(e.listSessions(t)),extensions:Object.freeze({list:()=>Oz(e.extensions.list),resume:t=>Oz(e.extensions.resume(t)),call:(t,n,r)=>Oz(e.extensions.call(t,n,r))}),session:t=>jz(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>Oz(e.close)})}function Nz(e){let t=`local:${rg()}`;return Object.freeze({...Mz(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:Dz(t.tools)});let r=await Oz(e.prepareConfiguration(n));return{commit:()=>{kz(r.commit)},discard:()=>Oz(r.discard)}},grants:Object.freeze({deliver:(t,n)=>kz(e.grants.deliver(t,n)),read:t=>kz(e.grants.read(t))}),withMeta:n=>Mz(e.withMeta(n),t)})}function Pz(e=`Remote Shiitake operation is unavailable`){return new W(`runtime`,`unavailable`,e)}function Fz(e){return new W(`runtime`,`invalid`,e)}function Iz(){return new W(`runtime`,`closed`,`Shiitake client is closed`)}var Lz=2,Rz=O(M);function zz(e){if(!(e instanceof MessageEvent))throw Fz(`Session stream event is invalid`);return Rz(e.data)}function Bz(e){return e.kind===`source-error`?v(Pz(`Session stream is unavailable`)):e.kind===`snapshot`?oi({try:()=>({kind:`snapshot`,value:vz(zz(e.event))}),catch:()=>Fz(`Session snapshot is invalid`)}):e.kind===`frame`?oi({try:()=>({kind:`frame`,value:yz(zz(e.event))}),catch:()=>Fz(`Session frame is invalid`)}):oi({try:()=>bz(zz(e.event)),catch:()=>Fz(`Session runtime error is invalid`)}).pipe(T(v))}function Vz(e,t){return y(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function Hz(e,t,n,r){return Uv(t=>Fr(oi({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Wg(t,{kind:e,event:r})||(qg(t,Wi(Pz(`Session stream client fell behind`))),gr(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===Lz&&a(`source-error`,e)}),n.add(i),i},catch:()=>Pz(`Session stream could not open`)}),e=>Vz(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(ny(Bz),ay({duration:Sy,orElse:()=>qv(Pz(`Session feed is connected but silent; the service may be busy`))}),gy(t.await))}function Uz(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function Wz(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 Gz(e,t,n,r){return Hz(e,t,n,r).pipe(ny(e=>e.kind===`frame`?x(e.value):v(Fz(`Session subscription received a snapshot`))))}function Kz(e,t,n,r,i,a){return b(function*(){yield*n;let o=yield*E_(!1),s=yield*Ca();yield*y(()=>t.add(s)),yield*Da(s,y(()=>{t.delete(s)}));let c=yield*Ln(Hz(e,r,i,a).pipe(fy(Nv()),Ta(s)));if(la(c))return yield*Aa(s,c),yield*Xt(c.cause);let[l,u]=c.value;if(an(l)||l.value.kind!==`snapshot`){let e=Fz(`Session stream did not begin with a snapshot`);return yield*Aa(s,aa(e)),yield*v(e)}let d=u.pipe(ny(e=>e.kind===`frame`?x(e.value):x({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),gy(o.await),py(e=>o.isOpen()&&Ki(e)?Wv:Jv(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(g(Aa(s,sa)))})})}function qz(e,t,n){return fn({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>Pz(`${n} request failed`)}).pipe(T(({response:e,body:r})=>e.ok?oi({try:()=>t(r),catch:()=>Fz(`${n} response is invalid`)}):oi({try:()=>bz(r),catch:()=>Fz(`${n} error response is invalid`)}).pipe(T(v))))}function Jz(e){let t=e.baseUrl.replace(/\/+$/u,``),n=e.fetch??globalThis.fetch,r=new Set,i=new Set,a=T_(!1),o=!1,s=sr(()=>o?v(Iz()):C),c=(e,t,n)=>Dn(qz(e,t,n),a.await.pipe(g(v(Iz())))),l=(e,t)=>s.pipe(g(c(r=>n(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:r}),dz,`Extension command`)));return Object.freeze({createSession:e=>s.pipe(T(()=>{let r=Cb({requestId:e});return c(e=>n(`${t}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:r}),signal:e}),Ez,`Session creation`)})),deleteSession:e=>s.pipe(T(()=>{let r=xb(e);return c(e=>n(`${t}/sessions/${encodeURIComponent(r)}`,{method:`DELETE`,signal:e}),Tz,`Session deletion`)})),listSessions:e=>s.pipe(T(()=>{let r=new URLSearchParams;e!==void 0&&r.set(`after`,Sb(e));let i=r.size===0?``:`?${r.toString()}`;return c(e=>n(`${t}/sessions${i}`,{signal:e}),Sz,`Session discovery`)})),extensions:Object.freeze({list:s.pipe(g(c(e=>n(`${t}/extensions`,{signal:e}),uz,`Extension list`))),resume:e=>s.pipe(g(c(r=>n(`${t}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:r}),lz,`Extension resume`))),call:(e,n,r)=>l(`${t}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(n)}`,r)}),session:o=>{let u=xb(o),d=Uz(t,u),f=`${d}/events`;function p(e){return s.pipe(g(c(t=>n(`${d}/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({command:e}),signal:t}),e.type===`prompt`||e.type===`compact`?fz:e.type===`cancel`?pz:e.type===`fork`?hz:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>s.pipe(g(c(t=>n(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),ZR,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>y(()=>t?.requestId??rg()).pipe(T(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return p(t?.images===void 0?r:{...r,images:t.images}).pipe(lt(e=>e.requestId===n?e:new W(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:s.pipe(g(c(e=>n(`${d}/pending/latest`,{signal:e}),mz,`Newest pending prompt`))),modelPreference:Object.freeze({read:s.pipe(g(c(e=>n(`${d}/model-preference`,{signal:e}),Fy,`Model preference read`))),set:e=>s.pipe(g(c(t=>n(`${d}/model-preference`,{signal:t,method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),()=>void 0,`Model preference set`)))}),extension:e=>Object.freeze({call:(t,n)=>l(`${d}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,n)}),read:e=>s.pipe(g(oi({try:()=>wb(e),catch:e=>e instanceof W?e:Fz(`Read options are invalid`)})),T(({limit:e,before:t,includeSandboxFailures:r})=>{let i=new URLSearchParams({limit:String(e)});return t!==void 0&&i.set(`before`,t),r===!0&&i.set(`includeSandboxFailures`,`true`),c(e=>n(`${d}?${i.toString()}`,{signal:e}),vz,`Session read`)})),readSettlement:(e,t=0)=>s.pipe(g(c(r=>n(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:r}),_z,`Command settlement`))),subscribe:t=>ey(s.pipe(g(oi({try:()=>Tb(t),catch:e=>e instanceof W?e:Fz(`Subscribe options are invalid`)})),Ce(({after:t,includeSandboxFailures:n})=>Gz(Wz(f,t,n===!0),a,i,e.eventSource)))),watch:t=>Kz(t?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,r,s,a,i,e.eventSource)})},close:sr(()=>o?C:(o=!0,a.open.pipe(g(Zr([...r],e=>Aa(e,sa),{discard:!0})),g(Zr([...i],e=>Vz(e,i),{discard:!0})))))})}function Yz(e){return Mz(Jz(e),e.baseUrl.replace(/\/+$/u,``))}D(zO);function Xz(e,t){if(t===void 0)return{status:`unavailable`};if(t.status===`stopped`)return{status:`stopped`,reason:t.reason};if(t.value===null||e.projection===null)return{status:`running`,value:null};let n=D(e.projection.schema)(t.value);return n._tag===`Success`?{status:`running`,value:n.success}:{status:`stopped`,reason:`Extension projection does not match this client`}}function Zz(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 Qz=M.pipe(z(hh(1)),z(vh(128)),z(Pm(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),$z=M.pipe(z(hh(1)),z(vh(64)),z(Pm(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u))),eB=Qz.pipe(xm(`ExtensionId`)),tB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionRevision`)),nB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionFingerprint`)),rB=class extends zi(`ExtensionHookError`){};function iB(e){return sr(()=>{let t=e();return Ge(t)?t:fn({try:()=>Promise.resolve(t),catch:e=>new rB({cause:e})})})}var aB=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function oB(e,t){let n=e(t);if(n instanceof Promise||Ge(n)&&!hr(n))throw new aB;return n}export{OL as $,xc as $a,Vp as $i,qO as $n,x_ as $r,$j as $t,hR as A,Th as Aa,zh as Ai,pA as An,ca as Ao,Ey as Ar,MI as At,XL as B,km as Ba,Kp as Bi,Tk as Bn,Ki as Bo,oy as Br,EM as Bt,sR as C,xh as Ca,N as Ci,hj as Cn,va as Co,Yy as Cr,sF as Ct,BL as D,bh as Da,lm as Di,uA as Dn,fa as Do,Ny as Dr,uI as Dt,OR as E,Eh as Ea,P as Ei,wA as En,ba as Eo,W as Er,uF as Et,eR as F,B as Fa,xm as Fi,tA as Fn,Gi as Fo,Sy as Fr,PM as Ft,wR as G,Om as Ga,O as Gi,ik as Gn,vy as Gr,lM as Gt,_R as H,Yh as Ha,Up as Hi,Ck as Hn,Ji as Ho,zv as Hr,sM as Ht,rR as I,A as Ia,z as Ii,$k as In,Wi as Io,Uv as Ir,IM as It,FL as J,Nc as Ja,wm as Ji,nk as Jn,ey as Jr,yM as Jt,LL as K,cf as Ka,Xp as Ki,ak as Kn,ay as Kr,uM as Kt,nR as L,k as La,Mp as Li,qk as Ln,Zi as Lo,sy as Lr,SM as Lt,cR as M,Pm as Ma,vm as Mi,oA as Mn,ua as Mo,Ty as Mr,cN as Mt,lR as N,zm as Na,I as Ni,aA as Nn,ra as No,ky as Nr,sN as Nt,WL as O,hh as Oa,Lh as Oi,hA as On,ia as Oo,Py as Or,SI as Ot,gR as P,Im as Pa,am as Pi,Yk as Pn,sa as Po,xy as Pr,dN as Pt,bL as Q,Dc as Qa,Am as Qi,JO as Qn,S_ as Qr,nM as Qt,tR as R,bm as Ra,jp as Ri,eA as Rn,Xi as Ro,_y as Rr,wM as Rt,oR as S,ch as Sa,R as Si,fj as Sn,_a as So,xb as Sr,jF as St,QL as T,kh as Ta,M as Ti,EA as Tn,ha as To,Eb as Tr,lF as Tt,qL as U,Jh as Ua,Wp as Ui,kk as Un,zi as Uo,ny as Ur,cM as Ut,mR as V,Xh as Va,Hp as Vi,Ok as Vn,$i as Vo,Qv as Vr,TM as Vt,KL as W,zp as Wa,D as Wi,Ek as Wn,$v as Wr,dM as Wt,kL as X,Ec as Xa,Yp as Xi,lk as Xn,T_ as Xr,xM as Xt,NL as Y,kc as Ya,Jp as Yi,uk as Yn,D_ as Yr,bM as Yt,yL as Z,rd as Za,U as Zi,YO as Zn,b_ as Zr,DM as Zt,RL as _,Zm as _a,nh as _i,Bj as _n,Aa as _o,aT as _r,cF as _t,nB as a,Ah as aa,bg as ai,Uj as an,Zu as ao,JD as ar,bI as at,GL as b,Qm as ba,jh as bi,LA as bn,wa as bo,vb as br,$F as bt,$z as c,Um as ca,um as ci,Qj as cn,Ou as co,WE as cr,xI as ct,Yz as d,ah as da,Hm as di,zj as dn,Ws as do,PE as dr,DP as dt,$m as ea,Jg as ei,Jj as en,Tc as eo,GO as er,SL as et,Dz as f,V as fa,H as fi,Vj as fn,Ks as fo,FE as fr,yP as ft,JL as g,th as ga,L as gi,Fj as gn,Da as go,zT as gr,xP as gt,fz as h,Vm as ha,j as hi,Yj as hn,Sa as ho,jT as hr,LP as ht,eB as i,yh as ia,Tg as ii,Kj as in,jc as io,xD as ir,tF as it,iR as j,eh as ja,sm as ji,fA as jn,da as jo,Dy as jr,mN as jt,kR as k,Oh as ka,mm as ki,mA as kn,la as ko,My as kr,nI as kt,Zz as l,Xm as la,cm as li,Nj as ln,pc as lo,UE as lr,rI as lt,Nz as m,oh as ma,Qh as mi,Wj as mn,Lo as mo,MT as mr,IP as mt,iB as n,Sh as na,Wg as ni,Xj as nn,wc as no,RO as nr,tL as nt,Qz as o,Dh as oa,rg as oi,Mj as on,$u as oo,_D as or,lI as ot,Oz as p,dh as pa,Zh as pi,Zj as pn,ps as po,kE as pr,dP as pt,PL as q,Ad as qa,Qp as qi,dk as qn,by as qr,fM as qt,oB as r,lh as ra,wg as ri,Ij as rn,Sc as ro,kO as rr,PN as rt,tB as s,Bm as sa,F as si,Lj as sn,Qu as so,zE as sr,SP as st,aB as t,mh as ta,Gg as ti,Rj as tn,Ac as to,zO as tr,KI as tt,Xz as u,uh as ua,Nh as ui,Pj as un,Us as uo,BE as ur,sI as ut,zL as v,fh as va,im as vi,Hj as vn,Oa as vo,_b as vr,FP as vt,ZL as w,vh as wa,fm as wi,pj as wn,ga as wo,Tb as wr,rF as wt,aR as x,ph as xa,om as xi,gj as xn,Ta as xo,Cb as xr,jI as xt,YL as y,sh as ya,hm as yi,Gj as yn,Ca as yo,wb as yr,MP as yt,ER as z,ym as za,Gp as zi,Dk as zn,Qi as zo,qv as zr,CM as zt};
|
|
807
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,t,r,a,s,i.kind,sP(i),n.state,oP(i),i.workId,yj(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=jF(e,{sessionId:t.sessionId});for(let t of rM(e,(t,n)=>BF(e,u,t,n)))dF(e,{sessionId:r,id:bj.fact.generate(),entry:t});return aN(e,{sessionId:r,activityAt:i,title:iP(e,r)}),r})}function jI(e,t,n,r){if(pP(e,t)===void 0)throw $(`Session document owner is unavailable`);return BF(e,jF(e,{sessionId:t}),n,r)}function MI(e,t,n,r,i){if(pP(e,t)===void 0)throw $(`Session document owner is unavailable`);dF(e,{sessionId:t,id:bj.fact.generate(),entry:{kind:`document`,workId:null,extensionId:n,name:r,valueJson:i}})}var NI=2097152,PI=200,FI=200,II=new TextEncoder;function LI(e){return new W(`store`,`unavailable`,e)}function RI(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)AP(e,t,n)!==void 0&&r.set(n,n);return r}function zI(e,t){return n=>{let r=AP(e,t,n)?.origin;return r?.kind===`extension`?{extensionId:r.extensionId,correlation:r.correlation}:void 0}}function BI(e,t,n){return{commandIds:RI(e,t,n),diagnostics:UI(n),cancellations:new Map(n.flatMap(({entry:e})=>e.kind===`cancellation`&&e.meta!==void 0?[[e.targetWorkId,e.meta]]:[])),origin:zI(e,t)}}function VI(e,t,n,r){let i=HF(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)&&AP(e,t,n.workId)!==void 0&&a.set(n.workId,n.workId);return{commandIds:a,diagnostics:i.diagnostics,cancellations:i.cancellations,origin:zI(e,t)}}function HI(e,t){let n=pj(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:_j(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 UI(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 GI=new WeakMap;function KI(e){let t=GI.get(e);if(t===void 0)throw LI(`Session compaction entry position is unavailable`);return t}function qI(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??LF(e,t,a.head);if(o===void 0)throw LI(`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});GI.set(s,i.sequence),r.push(s)}return Object.freeze(r)}function JI(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 YI(e){return II.encode(JSON.stringify(e)).byteLength}function XI(e,t){let n=CA({generation:e,sequence:t});if(n===void 0)throw LI(`Session cursor is unavailable`);return n}function ZI(e,t,n,r,i=!1){let a=HI(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:YI(a))+(o===void 0?0:YI(o))+(s===void 0?0:YI(s));if(c>NI)throw LI(`Session projection entry exceeds the read bound`);return e.bytes+c>NI?!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 QI(e,t,n,r,i,a=!1){let o={messages:[],terminals:[],sandboxFailures:[],bytes:0},s=0;for(let t=0;t<e.length&&s!==FI;t+=1){let c=e[i===`forward`?t:e.length-1-t];if(c===void 0||!ZI(o,c,n,r,a))break;s+=1}if(s===0&&e.length>0)throw LI(`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 $I(e){return Array.isArray(e)}function eL(e,t){let{commands:n,total:r}=TP(e,t,FI+1,`prompts`),i=[],a=II.encode(JSON.stringify({prompts:[],hasMore:!1,total:r})).byteLength;for(let e of n){let t=nL(e),n=II.encode(JSON.stringify(t)).byteLength+(i.length===0?0:1);if(i.length===FI||a+n>NI)return{prompts:i,hasMore:!0,total:r};i.push(t),a+=n}return{prompts:i,hasMore:!1,total:r}}function tL(e,t,n){let r=CP(e,t,n);return r===void 0?null:nL(r)}function nL(e){let t=pj(e.entry);if(t===void 0)throw LI(`Pending Session prompt is unavailable`);let n=t.message.content,r=$I(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 rL(e,t,n){let r=wA(n);if(r?.generation===t.rootId)return IF(e,t,r.sequence)?r.sequence:void 0}function iL(e,t,n,r,i=()=>({})){return bF(e,t,()=>{let a=eL(e,t),o=jF(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:Ck(e,t)});let s=o.rootId,c=n.before===void 0?2**53-1:rL(e,o,n.before);if(c===void 0)throw LI(`Session read cursor is unavailable`);let l=FF(e,o,{before:c,from:`newest`,rows:FI}),u=QI(l.rows,l.more,n.limit,VI(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:XI(s,f.sequence),hasMore:u.hasMore,oldestCursor:u.hasMore&&p!==void 0?XI(s,p.sequence):null,messages:u.messages,terminals:u.terminals,compactions:qI(e,o,d),compactionNotices:JI(d),pending:a,activity:r.facts,progress:n.before===void 0?r.readProgress():null,toolOutput:n.before===void 0?r.toolOutput:[],extensions:i(),attention:Ck(e,t)},ee=uA(e,t);return ee!==void 0&&Object.assign(m,{parent:ee}),Object.freeze(n.includeSandboxFailures===!0?{...m,sandboxFailures:u.sandboxFailures}:m)})}var aL=Object.freeze({kind:`reset`});function oL(e,t,n){if(n===void 0)return 0;if(n.generation===t.rootId)return IF(e,t,n.sequence)?n.sequence:void 0}function sL(e,t,n,r,i,a,o,s,c){let l=FF(e,t,{after:n,from:`oldest`,rows:FI}),u=QI(l.rows,l.more,PI,VI(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:XI(t.rootId,f),messages:u.messages,terminals:u.terminals,compactions:qI(e,t,d),compactionNotices:JI(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 cL(e,t,n,r,i,a=()=>({}),o=!1){let s=n===void 0?void 0:wA(n);return n!==void 0&&s===void 0?aL:bF(e,t,()=>{let c=eL(e,t),l=jF(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:Ck(e,t),pending:c}],hasMore:!1}:aL;let u=oL(e,l,s);return u===void 0?aL:sL(e,l,u,r,i,a(),Ck(e,t),c,o)})}function lL(e,t,n){let r=AP(e,t,n);if(r===void 0)throw LI(`Accepted Session command is unavailable`);if(!NP(e,t,r.entry.workId))return;let i=PP(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=Tg(r.entry.meta);return{acceptedSender:u?.kind===`agent`?u.id:null,delegator:oA(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:mA(e,t,r.entry.workId)}}var uL=65536,dL=250,fL=2048,pL=new TextEncoder,mL=()=>({chunks:[],length:0,bytes:0});function hL(e,t){for(let n=0;n<t.length;){let r=Math.min(n+fL,t.length),i=t.charCodeAt(r-1);r<t.length&&i>=55296&&i<=56319&&r--;let a=t.slice(n,r),o=pL.encode(a).byteLength,s=e.chunks.at(-1);for(s!==void 0&&s.text.length+a.length<=fL?(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>uL&&e.chunks.length>1;){let t=e.chunks.shift();t!==void 0&&(e.bytes-=t.bytes)}}}function gL(e){return e.chunks[0]?.offset??0}function _L(e,t){return e.chunks.flatMap(e=>e.offset+e.text.length<=t?[]:[e.text.slice(Math.max(0,t-e.offset))]).join(``)}function vL(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:_L(e.text,gL(e.text)),thinking:_L(e.thinking,gL(e.thinking)),textOffset:gL(e.text),thinkingOffset:gL(e.thinking),textTruncated:gL(e.text)>0,thinkingTruncated:gL(e.thinking)>0}}function yL(e){return e===null?null:{messageId:e.messageId,revision:e.revision,text:e.textOffset+e.text.length,thinking:e.thinkingOffset+e.thinking.length}}function bL(e,t,n,r){let i=xL.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<gL(a.text)||c<gL(a.thinking)))return{messageId:a.messageId,revision:a.revision,text:{offset:s,append:_L(a.text,s)},thinking:{offset:c,append:_L(a.thinking,c)}}}var xL=new WeakMap;function SL(e,t,n){let r=xL.get(e)?.get(t);return r?.workId===n?[...r.slots.values()].filter(e=>e!==null):[]}var CL=D(P({droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))}),{onExcessProperty:`error`});function wL(e,t){return b(function*(){let n=yield*EL(e,t),r=()=>{lk(e,t.sessionId,`progress`)};return{started:e=>y(()=>{n.slots.size<4&&!n.slots.has(e.toolCall.value)&&n.slots.set(e.toolCall.value,null)}),update:e=>y(()=>{let t=n.slots.get(e.toolCall.value);if(t===void 0)return;let i=CL(e.result.data);if(Ae(i))return;let a=e.result.content.filter(e=>e.type===`text`).map(e=>e.text).join(``);new TextEncoder().encode(a).byteLength>8192||a.split(`
|
|
808
|
+
`).length>200||i.success.droppedBytes>i.success.totalBytes||(n.slots.set(e.toolCall.value,{toolCallId:e.call.id,revision:(t?.revision??0)+1,tail:a,...i.success}),r())}),terminal:e=>y(()=>{n.slots.delete(e.toolCall.value)&&r()})}})}function TL(e){let t=xL.get(e);if(t!==void 0)return t;let n=new Map;return xL.set(e,n),n}function EL(e,t){return b(function*(){let n=TL(e),r=n.get(t.sessionId);if(r?.workId===t.commandId)return r;let i={workId:t.commandId,value:null,slots:new Map};return n.set(t.sessionId,i),yield*Tr(()=>y(()=>{n.get(t.sessionId)===i&&(n.delete(t.sessionId),(i.value!==null||i.slots.size>0)&&lk(e,t.sessionId,`progress`))})),i})}function DL(e){return new W(`runtime`,`rejected`,e)}function OL(e,t,n){let r=TL(e).get(t);return vL(r?.workId===n?r.value:null)}function kL(e,t,n){let r=xL.get(e)?.get(t);return r?.workId===n&&(r.value?.text.length??0)>0}function AL(e,t,n,r){return b(function*(){let i=yield*EL(e,t);if(r!==void 0&&i.value===null){let n=mL();n.length=r.offset,hL(n,r.text),i.value={recovered:!0,messageId:r.messageId,revision:1,text:n,thinking:mL()},lk(e,t.sessionId,`progress`)}let a,o=0,s=0,c,l=()=>{c!==void 0&&clearTimeout(c),c=void 0},u=()=>{l();let n=i.value;n!==null&&(s=n.text.length+n.thinking.length,lk(e,t.sessionId,`progress`))},d=y(()=>{l();let n=i.value!==null;i.value=null,n&&lk(e,t.sessionId,`progress`),a=void 0});return yield*Tr(()=>d),Object.freeze({started:e=>y(()=>{l(),a=e,o=0,i.value?.recovered!==!0&&(i.value=null),s=0}),update:n=>sr(()=>{let r=a;if(r===void 0)return v(DL(`Mule progress arrived before its message start`));if(r.run.value!==n.run.value||r.turn.value!==n.turn.value||r.message.value!==n.message.value)return v(DL(`Mule progress identity conflicts`));let l=n.event;if(l.type!==`text_delta`&&l.type!==`thinking_delta`||l.delta.length===0)return C;let d=i.value===null||i.value.recovered===!0,f=(d?null:i.value)??{messageId:n.message.value,revision:0,text:mL(),thinking:mL()};hL(l.type===`text_delta`?f.text:f.thinking,l.delta),f.revision++,i.value=f;let p=f.text.length+f.thinking.length;d||p-s>=4096?u():c??=setTimeout(u,100);let m=Date.now();return l.type!==`text_delta`||m-o<dL?C:(o=m,oi({try:()=>{oI(e,{sessionId:t.sessionId,entry:{kind:`message_start`,workId:t.commandId,run:r.run,turn:r.turn,message:r.message,role:`assistant`},text:_L(f.text,gL(f.text)),offset:gL(f.text)})},catch:e=>new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)}))}),terminal:e=>d.pipe(g(n(e)))})})}var jL=new WeakMap;function ML(e){let t=jL.get(e);if(t!==void 0)return t;let n=new Map;return jL.set(e,n),n}function NL(e,t){return ML(e).get(t)??null}function PL(e,t,n){ML(e).set(t,Object.freeze({trigger:n})),lk(e,t,`progress`)}function FL(e,t){ML(e).delete(t)&&lk(e,t,`progress`)}var IL=Object.freeze({admitNew:()=>{}});function LL(e){return e===void 0?IL:Object.freeze({admitNew:()=>{if(e.underPressure())throw new W(`store`,`storage_pressure`,`Storage is near its budget. New Sessions and prompts are refused until space is freed; running work continues.`)}})}function RL(e,t){let n=cI(e,t);return lk(e,t.sessionId),n}function zL(e,t){let n=dI(e,t);return lk(e,t.sessionId),n}function BL(e,t){let n=fI(e,t);return n!==`stale`&&lk(e,t.sessionId),n}function VL(e){return new W(`store`,`rejected`,e)}function HL(e){return new W(`store`,`conflict`,e)}function UL(e){return oi({try:e,catch:e=>e instanceof W?e:new W(`store`,`rejected`,`Native Session store operation failed`,void 0,e)})}function WL(e){return UL(()=>{oF(e)})}function GL(e,t,n,r,i,a,o){return UL(()=>{let s=EI(e,t,n,i,a,r,o);return s?.delivery===`new`&&lk(e,t,`settlement`),s})}function KL(e,t){return UL(()=>{let n=OP(e,t.sessionId,t.delivery,t.workId);return n.length>0&&lk(e,t.sessionId),n})}function qL(e,t){return UL(()=>{kP(e,t),lk(e,t.sessionId,`settlement`)})}function JL(e,t,n,r,i){return UL(()=>{let a=TI(e,t,n,r,i);return lk(e,t,`settlement`),a?.accepted})}function YL(e,t){return UL(()=>{OI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession}),lk(e,t.sessionId)})}function XL(e,t){return UL(()=>{kI(e,t)&&lk(e,t.sessionId)})}function ZL(e,t){return UL(()=>{let n=AI(e,{sessionId:t.sessionId,entryId:t.entryId,assertIdleSession:t.assertIdleSession});return lk(e,n),Object.freeze({sessionId:n})})}function QL(e,t){return UL(()=>{let n=iI(e,{sessionId:xb(t.sessionId),commandFactId:t.commandFactId});return n.entryDelivery===`new`&&lk(e,t.sessionId),n})}function $L(e){return e.content.flatMap(e=>e.type===`text`?[e.text]:[]).join(``).trim()}function eR(e,t){return UL(()=>{let n=AP(e,t.sessionId,t.commandFactId);if(n===void 0)throw VL(`Accepted Session command is unavailable`);let r=PP(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=$L(t.value);if(e!==``)return e}}return``})}function tR(e,t){return b(function*(){let n=t.commandFactId;for(;n!==void 0;){let r=yield*eR(e,{sessionId:t.sessionId,commandFactId:n});if(r!==``)return r;let i=n;n=yield*UL(()=>{let n=AP(e,t.sessionId,i);if(n===void 0)throw VL(`Accepted Session command is unavailable`);if(hR(e,t.sessionId,i,n.entry.workId)===null)return;let r=gP(e,i);if(r===void 0)throw VL(`Accepted Session command entry is unavailable`);for(;r.parentId!==null;){let n=gP(e,r.parentId);if(n?.sessionId!==t.sessionId||n.sequence>=r.sequence)throw VL(`Session stretch ancestry is unavailable`);if(n.entry.kind===`command`)return n.id;r=n}})}return``})}function nR(e,t,n){return UL(()=>{let r=AP(e,t.sessionId,t.commandFactId);if(r===void 0)throw VL(`Accepted Session command is unavailable`);if(n!==`cancelled`)return r.entry.meta;let i=PP(e,t.sessionId,r.entry.workId).find(({entry:e})=>e.kind===`cancellation`);return i?.entry.kind===`cancellation`?i.entry.meta:void 0})}function rR(e,t){return UL(()=>{let n=AP(e,t.sessionId,t.commandFactId);if(n===void 0)throw VL(`Accepted Session command is unavailable`);return UI(PP(e,t.sessionId,n.entry.workId)).get(n.entry.workId)})}function iR(e,t,n,r,i,a){return UL(()=>{let o=xb(t),s=wb(r);return yF(e,o,()=>a(iL(e,o,s,n(),i)),s.before===void 0?void 0:wA(s.before)?.sequence)})}function aR(e,t,n){return UL(()=>VP(e,Cb({requestId:t}),n))}function oR(e,t,n){return HP(e,Cb({requestId:t}),n)}function sR(e,t){return UL(()=>UP(e,{sessionId:xb(t.sessionId),assertIdleSession:t.assertIdleSession,recordInboxDeletion:t=>{oN(e,t)}}))}function cR(e,t){return UL(()=>dN(e,t))}function lR(e,t,n,r,i,a,o,s){return UL(()=>{let c=xb(t);return yF(e,c,()=>s(cL(e,c,n,r,i,a,o)))})}function uR(e,t){return e.kind===t.kind&&e.value===t.value&&e.parent?.kind===t.parent?.kind&&e.parent?.value===t.parent?.value}function dR(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 fR(e,t,n,r,i){i?.();let a=PP(e,t.sessionId,t.commandId).find(r);if(a!==void 0){if(n.kind===`work_terminal`&&a.entry.kind===`run_terminal`||oj(a.entry,n))return`replay`;throw HL(`Mule event identity conflicts`)}for(let r=0;r<3;r+=1){let r=bj.fact.generate();if(gP(e,r)===void 0&&AP(e,t.sessionId,r)===void 0)return dF(e,{sessionId:t.sessionId,id:r,entry:n}),`new`}throw VL(`Session fact identity allocation failed`)}function pR(e,t,n,r,i){e.transactionSync(()=>fR(e,t,n,r,i))===`new`&&lk(e,t.sessionId,n.kind===`run_terminal`||n.kind===`work_terminal`?`settlement`:`durable`)}function mR(e,t,n){return UL(()=>{pR(e,t,{kind:`sandbox_failure`,workId:t.commandId,event:n},({entry:e})=>e.kind===`sandbox_failure`&&e.event.ref===n.ref)})}function hR(e,t,n,r){let i=AP(e,t,n);if(i?.entry.workId!==r)throw VL(`Accepted Session work is unavailable`);return i.origin.kind===`extension`?Object.freeze({extensionId:i.origin.extensionId,correlation:i.origin.correlation}):null}function gR(e,t,n,r){let i=hR(e,t,n,r),a=PP(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 _R(e,t){return UL(()=>{if(AP(e,t.sessionId,t.commandFactId)?.entry.workId!==t.workId)throw VL(`Settled Session work is unavailable`);let n={workId:t.workId,kind:`work_terminal`,outcome:t.outcome};pR(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 vR(e,t,n,r,i){return UL(()=>{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}),pR(e,t,a,({entry:e})=>e.kind===a.kind?e.kind===`run_started`&&a.kind===`run_started`?uR(e.run,a.run)&&dR(e.contract,n):e.kind===`turn_started`&&a.kind===`turn_started`?uR(e.turn,a.turn):e.kind===`run_terminal`&&a.kind===`run_terminal`&&uR(e.terminal,a.terminal):!1)})}function yR(e,t,n){return UL(()=>{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=PP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&uR(e.message,n.message));if(i!==void 0){if(i.entry.kind===`message`){if(i.entry.workId!==r.workId||!uR(i.entry.run,r.run)||!uR(i.entry.turn,r.turn)||i.entry.value.role!==r.role)throw HL(`Mule message-start identity conflicts`);return`replay`}if(i.entry.kind!==`message_start`||!oj(aj(i.entry),r))throw HL(`Mule message-start identity conflicts`);return`replay`}return dF(e,{sessionId:t.sessionId,id:n.message.value,entry:r,state:`streaming`}),`new`})===`new`&&lk(e,t.sessionId)})}function bR(e,t,n,r){return UL(()=>{pR(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`&&uR(e.turn,r.turn)&&e.attempt===r.attempt&&dR(e.contract,n))})}function xR(e,t,n,r){return UL(()=>{let i={kind:`message`,workId:t.commandId,run:n.run,turn:n.turn,message:n.message,value:n.value},a=n.data===void 0?i:{...i,data:n.data};e.transactionSync(()=>{let i=PP(e,t.sessionId,t.commandId).find(({entry:e})=>(e.kind===`message_start`||e.kind===`message`)&&uR(e.message,n.message));if(i?.entry.kind===`message`){if(!oj(i.entry,a))throw HL(`Mule completed-message identity conflicts`)}else fF(e,{sessionId:t.sessionId,id:n.message.value,entry:a});let o=n.retry===void 0||n.value.role!==`assistant`?`replay`:TR(e,t,wR(n.retry,r),n.turn);return i?.entry.kind===`message`&&o===`replay`?`replay`:`new`})===`new`&&lk(e,t.sessionId)})}function SR(e,t,n,r){return UL(()=>{pR(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`&&uR(e.toolCall,r.toolCall)&&dR(e.contract,n))})}function CR(e,t,n){return UL(()=>{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};pR(e,t,r===void 0?a:{...a,data:r},({entry:e})=>e.kind===`tool_outcome`&&uR(e.toolCall,n.toolCall))})}function wR(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+qO({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,dueAt:e.dueAt,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function TR(e,t,n,r){let i=PP(e,t.sessionId,t.commandId).find(({entry:e})=>e.kind===`turn_started`&&uR(e.turn,r));if(i===void 0)throw HL(`Retry has no recorded turn`);return fR(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&&uR(e.event.run,n.run))}function ER(e,t,n,r){return UL(()=>{e.transactionSync(()=>TR(e,t,n,r))===`new`&&lk(e,t.sessionId)}).pipe(ut(DR))}var DR=e=>({_tag:`MuleError`,phase:`listener`,message:`Woodstock could not record the Mule event`,cause:e});function OR(e,t,n,r,i){return b(function*(){let a=yield*AL(e,t,n=>xR(e,t,n,r),i),o=yield*wL(e,t),s=(i,s)=>{switch(i.type){case`model_prompt`:return bR(e,t,n,i);case`run_start`:case`turn_start`:case`run_end`:return vR(e,t,n,i,s);case`message_start`:return i.value.role===`user`?C:yR(e,t,i).pipe(g(i.value.role===`assistant`?a.started(i):C));case`message_update`:return a.update(i);case`message_end`:return i.value.role===`user`?C:i.value.role===`assistant`?a.terminal(i):xR(e,t,i,r);case`tool_execution_start`:return SR(e,t,n,i).pipe(g(o.started(i)));case`tool_execution_end`:return CR(e,t,i).pipe(g(o.terminal(i)));case`tool_execution_update`:return o.update(i);case`turn_end`:return C}};return(e,t)=>s(e,t).pipe(ut(DR))})}function kR(e,t,n){return UL(()=>lL(e,xb(t),xb(n)))}var AR=NN.mapFields(({extensionId:e,correlation:t})=>({extensionId:e,correlation:t})),jR=P({requestId:k(M),meta:k(HO),data:k(zO),origin:k(AR),id:M,sequence:H.check(Xm(0)),commandId:R(M),value:JA}),MR=L([`manual`,`threshold`,`overflow`]),NR=P({queue:I([P({state:j(`idle`)}),P({state:j(`queued`),commandId:jh,runningWork:R(P({phase:L([`thinking`,`streaming`,`running_tool`,`waiting_on_you`,`cancelling`])}))}),P({state:j(`running`),commandId:jh})]),cancellationRequested:cm,retry:R(P({attempt:H.check(Xm(0)),maxAttempts:H.check(Xm(0)),delayMs:H.check(V(0)),errorMessage:M,scheduledAt:H.check(V(0))})),activeTool:R(M),lastModelChoiceSequence:R(H.check(Xm(0))),compaction:R(P({trigger:MR}))}),PR=M,FR=fm(M,I([P({status:j(`running`),revision:PR,value:zO,catalog:k(zO)}),P({status:j(`stopped`),revision:PR,reason:M})])),IR=P({id:M,version:M,revision:PR,status:L([`running`,`stopped`]),reason:R(M),stoppedAt:R(N)}),LR=P({commandId:M,outcome:L([`completed`,`cancelled`,`failed`,`interrupted`]),sequence:H.check(Xm(0)),diagnostic:R(M),meta:k(HO)}),RR=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),tokensBefore:N,tokensAfter:R(N),trigger:R(MR)}),zR=P({id:M,sequence:H.check(Xm(0)),at:H.check(V(0)),trigger:MR,result:L([`nothing_to_compact`,`failed`,`stale`,`insufficient`]),diagnostic:R(M)}),BR=M.check(B(e=>new TextEncoder().encode(e).byteLength<=65536)),VR=P({messageId:M,revision:H.check(V(0)),text:BR,thinking:BR,textOffset:H.check(V(0)),thinkingOffset:H.check(V(0)),textTruncated:cm,thinkingTruncated:cm}),HR=P({commandId:M,requestId:M,meta:k(HO),origin:k(AR),text:M,images:k(F(Gy)),delivery:L([`steer`,`followUp`])}),UR=F(P({toolCallId:M,revision:H.check(V(0)),tail:M.check(B(e=>new TextEncoder().encode(e).byteLength<=8192&&e.split(`
|
|
809
|
+
`).length<=200)),droppedBytes:H.check(V(0)),totalBytes:H.check(V(0))})).check(vh(4)),WR=P({total:H.check(V(0)),prompts:F(HR),hasMore:cm}),GR=P({tokens:H.check(V(0)),window:R(H.check(Xm(0)))}),KR=P({parent:k(Ty),sessionId:M,cursor:R(M),hasMore:cm,oldestCursor:k(R(M)),messages:F(jR),terminals:F(LR),sandboxFailures:k(F(FO)),compactions:k(F(RR)),compactionNotices:k(F(zR)),pending:WR,activity:NR,progress:R(VR),toolOutput:UR,extensions:FR,attention:Ay,context:k(GR)}),qR=I([P({kind:j(`heartbeat`)}),P({kind:j(`activity`),activity:NR}),P({kind:j(`tool_output`),toolOutput:UR,activity:NR}),P({kind:j(`update`),delivery:L([`replay`,`live`]),cursor:R(M),messages:F(jR),terminals:F(LR),sandboxFailures:k(F(FO)),compactions:k(F(RR)),compactionNotices:k(F(zR)),pending:WR,activity:NR,extensions:FR,attention:Ay,context:k(GR)}),P({kind:j(`progress`),progress:P({messageId:M,revision:H.check(V(0)),text:P({offset:H.check(V(0)),append:BR}),thinking:P({offset:H.check(V(0)),append:BR})}),activity:NR}),P({kind:j(`reset`),reason:j(`history_unavailable`),cursor:R(M),baseline:KR})]),JR=P({status:j(`accepted`),commandId:M,sessionId:k(M)});O(U(I([JR,P({status:j(`held`),reason:j(`recipient_offline`),message:j(`waiting: recipient offline`)})])),{onExcessProperty:`error`});var YR=P({status:j(`unknown`)}),XR=O(U(I([JR,YR])));function ZR(e){return XR(e)}var QR=I([JR,YR,P({status:j(`too_late`),commandId:M})]),$R=P({sessionId:M}),ez=O(U(KR),{onExcessProperty:`error`}),tz=O(U(qR),{onExcessProperty:`error`}),nz=O(U(JR)),rz=O(U(QR)),iz=O(U($R)),az=O(U(zy)),oz=O(U(IR)),sz=O(U(F(IR))),cz=O(U(zO));function lz(e){return oz(e)}function uz(e){return sz(e)}function dz(e){return cz(e)}function fz(e){return nz(e)}function pz(e){return rz(e)}function mz(e){return O(U(R(HR)))(e)}function hz(e){return iz(e)}var gz=P({acceptedSender:R(M),delegator:R(M),terminal:LR,content:M,usage:F(P({provider:M,model:M,usage:WA})),toolCalls:H.check(V(0)),waitingOnYou:F(P({itemId:M,kind:M,summary:M})).check(vh(8))});function _z(e){return O(U(R(gz)))(e)??void 0}function vz(e){return ez(e)}function yz(e){return tz(e)}function bz(e){let t=az(e);return new W(t.boundary,t.cause,t.message,t.requestId)}var xz=O(U(P({sessions:F(I([P({sessionId:jh,createdAt:N,lastActivityAt:N,settledAt:k(N),title:M,state:L([`needs_you`,`running`,`errored`,`done`])}),P({sessionId:jh,state:j(`unavailable`)})])),next:A(jh)})));function Sz(e){let t=xz(e);return{sessions:t.sessions,next:t.next}}var Cz=O(U(P({sessionId:jh}))),wz=O(U(P({deleted:cm})));function Tz(e){return wz(e).deleted}function Ez(e){return Cz(e).sessionId}function Dz(e){let t={modules:e.modules??[],sources:e.sources??[],sandbox:OO(e.sandbox),access:e.access??{}};return e.execution===void 0?t:{...t,execution:e.execution}}function Oz(e,t){return Kn(e,t).then(e=>{if(ca(e))return e.value;let t=Gn(Xi(e.cause))??Ji(e.cause);return Promise.reject(t instanceof Error?t:Error(String(t)))})}function kz(e){let t=Pr(e);if(ca(t))return t.value;let n=Gn(Xi(t.cause))??Ji(t.cause);throw n instanceof Error?n:Error(String(n))}function Az(e){let t=by(e);return Object.freeze({[Symbol.asyncIterator]:()=>{let e=t[Symbol.asyncIterator]();return{next:()=>e.next(),return:()=>e.return?.()??Promise.resolve({done:!0,value:void 0})}}})}function jz(e,t){function n(e){return Oz(t.command(e))}return Object.freeze({address:e,command:n,withdraw:e=>Oz(t.withdraw(e)),abort:()=>Oz(t.abort),send:(e,n)=>Oz(t.send(e,n)),cancel:e=>Oz(t.cancel(e)),latestPending:()=>Oz(t.latestPending),modelPreference:Object.freeze({read:()=>Oz(t.modelPreference.read),set:e=>Oz(t.modelPreference.set(e))}),extension:e=>{let n=t.extension(e);return Object.freeze({call:(e,t,r)=>Oz(n.call(e,t,r))})},read:e=>Oz(t.read(e)),readSettlement:(e,n)=>Oz(t.readSettlement(e,n?.timeoutMs),n),subscribe:e=>Az(t.subscribe(e)),watch:e=>Oz(t.watch(e)).then(e=>Object.freeze({snapshot:e.snapshot,changes:Az(e.changes),close:()=>Oz(e.close)}))})}function Mz(e,t){let n=t??`local:${rg()}`;return Object.freeze({createSession:t=>Oz(e.createSession(t)),deleteSession:t=>Oz(e.deleteSession(t)),listSessions:t=>Oz(e.listSessions(t)),extensions:Object.freeze({list:()=>Oz(e.extensions.list),resume:t=>Oz(e.extensions.resume(t)),call:(t,n,r)=>Oz(e.extensions.call(t,n,r))}),session:t=>jz(`${n}/sessions/${encodeURIComponent(t)}`,e.session(t)),close:()=>Oz(e.close)})}function Nz(e){let t=`local:${rg()}`;return Object.freeze({...Mz(e,t),prepareConfiguration:async t=>{let n={extensions:t.extensions};t.tools!==void 0&&Object.assign(n,{tools:Dz(t.tools)});let r=await Oz(e.prepareConfiguration(n));return{commit:()=>{kz(r.commit)},discard:()=>Oz(r.discard)}},grants:Object.freeze({deliver:(t,n)=>kz(e.grants.deliver(t,n)),read:t=>kz(e.grants.read(t))}),withMeta:n=>Mz(e.withMeta(n),t)})}function Pz(e=`Remote Shiitake operation is unavailable`){return new W(`runtime`,`unavailable`,e)}function Fz(e){return new W(`runtime`,`invalid`,e)}function Iz(){return new W(`runtime`,`closed`,`Shiitake client is closed`)}var Lz=2,Rz=O(M);function zz(e){if(!(e instanceof MessageEvent))throw Fz(`Session stream event is invalid`);return Rz(e.data)}function Bz(e){return e.kind===`source-error`?v(Pz(`Session stream is unavailable`)):e.kind===`snapshot`?oi({try:()=>({kind:`snapshot`,value:vz(zz(e.event))}),catch:()=>Fz(`Session snapshot is invalid`)}):e.kind===`frame`?oi({try:()=>({kind:`frame`,value:yz(zz(e.event))}),catch:()=>Fz(`Session frame is invalid`)}):oi({try:()=>bz(zz(e.event)),catch:()=>Fz(`Session runtime error is invalid`)}).pipe(T(v))}function Vz(e,t){return y(()=>{e.closed||(e.closed=!0,t.delete(e),e.source.close())})}function Hz(e,t,n,r){return Uv(t=>Fr(oi({try:()=>{let i={source:new(r??EventSource)(e),closed:!1},a=(e,r)=>{Wg(t,{kind:e,event:r})||(qg(t,Wi(Pz(`Session stream client fell behind`))),_r(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===Lz&&a(`source-error`,e)}),n.add(i),i},catch:()=>Pz(`Session stream could not open`)}),e=>Vz(e,n)),{bufferSize:256,strategy:`dropping`}).pipe(ny(Bz),ay({duration:Sy,orElse:()=>qv(Pz(`Session feed is connected but silent; the service may be busy`))}),gy(t.await))}function Uz(e,t){return`${e}/sessions/${encodeURIComponent(t)}`}function Wz(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 Gz(e,t,n,r){return Hz(e,t,n,r).pipe(ny(e=>e.kind===`frame`?x(e.value):v(Fz(`Session subscription received a snapshot`))))}function Kz(e,t,n,r,i,a){return b(function*(){yield*n;let o=yield*E_(!1),s=yield*Ca();yield*y(()=>t.add(s)),yield*Da(s,y(()=>{t.delete(s)}));let c=yield*Ln(Hz(e,r,i,a).pipe(fy(Nv()),Ta(s)));if(la(c))return yield*Aa(s,c),yield*Zt(c.cause);let[l,u]=c.value;if(on(l)||l.value.kind!==`snapshot`){let e=Fz(`Session stream did not begin with a snapshot`);return yield*Aa(s,aa(e)),yield*v(e)}let d=u.pipe(ny(e=>e.kind===`frame`?x(e.value):x({kind:`reset`,reason:`history_unavailable`,cursor:e.value.cursor,baseline:e.value})),gy(o.await),py(e=>o.isOpen()&&Ki(e)?Wv:Jv(e)));return Object.freeze({snapshot:l.value.value,changes:d,close:o.open.pipe(g(Aa(s,sa)))})})}function qz(e,t,n){return pn({try:async t=>{let n=await e(t);return{response:n,body:await n.text()}},catch:()=>Pz(`${n} request failed`)}).pipe(T(({response:e,body:r})=>e.ok?oi({try:()=>t(r),catch:()=>Fz(`${n} response is invalid`)}):oi({try:()=>bz(r),catch:()=>Fz(`${n} error response is invalid`)}).pipe(T(v))))}function Jz(e){let t=e.baseUrl.replace(/\/+$/u,``),n=e.fetch??globalThis.fetch,r=new Set,i=new Set,a=T_(!1),o=!1,s=sr(()=>o?v(Iz()):C),c=(e,t,n)=>Dn(qz(e,t,n),a.await.pipe(g(v(Iz())))),l=(e,t)=>s.pipe(g(c(r=>n(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),signal:r}),dz,`Extension command`)));return Object.freeze({createSession:e=>s.pipe(T(()=>{let r=Cb({requestId:e});return c(e=>n(`${t}/sessions`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:r}),signal:e}),Ez,`Session creation`)})),deleteSession:e=>s.pipe(T(()=>{let r=xb(e);return c(e=>n(`${t}/sessions/${encodeURIComponent(r)}`,{method:`DELETE`,signal:e}),Tz,`Session deletion`)})),listSessions:e=>s.pipe(T(()=>{let r=new URLSearchParams;e!==void 0&&r.set(`after`,Sb(e));let i=r.size===0?``:`?${r.toString()}`;return c(e=>n(`${t}/sessions${i}`,{signal:e}),Sz,`Session discovery`)})),extensions:Object.freeze({list:s.pipe(g(c(e=>n(`${t}/extensions`,{signal:e}),uz,`Extension list`))),resume:e=>s.pipe(g(c(r=>n(`${t}/extensions/${encodeURIComponent(e)}/resume`,{method:`POST`,signal:r}),lz,`Extension resume`))),call:(e,n,r)=>l(`${t}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(n)}`,r)}),session:o=>{let u=xb(o),d=Uz(t,u),f=`${d}/events`;function p(e){return s.pipe(g(c(t=>n(`${d}/command`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({command:e}),signal:t}),e.type===`prompt`||e.type===`compact`?fz:e.type===`cancel`?pz:e.type===`fork`?hz:()=>void 0,`Command`)))}return Object.freeze({command:p,withdraw:e=>s.pipe(g(c(t=>n(`${d}/withdraw`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({requestId:e}),signal:t}),ZR,`Request withdrawal`))),abort:p({type:`abort`}),send:(e,t)=>y(()=>t?.requestId??rg()).pipe(T(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return p(t?.images===void 0?r:{...r,images:t.images}).pipe(ut(e=>e.requestId===n?e:new W(e.boundary,e.cause,e.message,n)))})),cancel:e=>p({type:`cancel`,...e}),latestPending:s.pipe(g(c(e=>n(`${d}/pending/latest`,{signal:e}),mz,`Newest pending prompt`))),modelPreference:Object.freeze({read:s.pipe(g(c(e=>n(`${d}/model-preference`,{signal:e}),Fy,`Model preference read`))),set:e=>s.pipe(g(c(t=>n(`${d}/model-preference`,{signal:t,method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(e)}),()=>void 0,`Model preference set`)))}),extension:e=>Object.freeze({call:(t,n)=>l(`${d}/extensions/${encodeURIComponent(e)}/commands/${encodeURIComponent(t)}`,n)}),read:e=>s.pipe(g(oi({try:()=>wb(e),catch:e=>e instanceof W?e:Fz(`Read options are invalid`)})),T(({limit:e,before:t,includeSandboxFailures:r})=>{let i=new URLSearchParams({limit:String(e)});return t!==void 0&&i.set(`before`,t),r===!0&&i.set(`includeSandboxFailures`,`true`),c(e=>n(`${d}?${i.toString()}`,{signal:e}),vz,`Session read`)})),readSettlement:(e,t=0)=>s.pipe(g(c(r=>n(`${d}/settlement?${new URLSearchParams({commandId:e,timeoutMs:String(t)}).toString()}`,{signal:r}),_z,`Command settlement`))),subscribe:t=>ey(s.pipe(g(oi({try:()=>Tb(t),catch:e=>e instanceof W?e:Fz(`Subscribe options are invalid`)})),we(({after:t,includeSandboxFailures:n})=>Gz(Wz(f,t,n===!0),a,i,e.eventSource)))),watch:t=>Kz(t?.includeSandboxFailures===!0?`${f}?includeSandboxFailures=true`:f,r,s,a,i,e.eventSource)})},close:sr(()=>o?C:(o=!0,a.open.pipe(g(Zr([...r],e=>Aa(e,sa),{discard:!0})),g(Zr([...i],e=>Vz(e,i),{discard:!0})))))})}function Yz(e){return Mz(Jz(e),e.baseUrl.replace(/\/+$/u,``))}D(zO);function Xz(e,t){if(t===void 0)return{status:`unavailable`};if(t.status===`stopped`)return{status:`stopped`,reason:t.reason};if(t.value===null||e.projection===null)return{status:`running`,value:null};let n=D(e.projection.schema)(t.value);return n._tag===`Success`?{status:`running`,value:n.success}:{status:`stopped`,reason:`Extension projection does not match this client`}}function Zz(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 Qz=M.pipe(z(hh(1)),z(vh(128)),z(Pm(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u))),$z=M.pipe(z(hh(1)),z(vh(64)),z(Pm(/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/u))),eB=Qz.pipe(xm(`ExtensionId`)),tB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionRevision`)),nB=M.pipe(z(Pm(/^sha256:[0-9a-f]{64}$/u)),xm(`ExtensionFingerprint`)),rB=class extends zi(`ExtensionHookError`){};function iB(e){return sr(()=>{let t=e();return Ke(t)?t:pn({try:()=>Promise.resolve(t),catch:e=>new rB({cause:e})})})}var aB=class extends Error{constructor(){super(`Extension transaction handler must return synchronously`),this.name=`AsyncExtensionTransactionError`}};function oB(e,t){let n=e(t);if(n instanceof Promise||Ke(n)&&!gr(n))throw new aB;return n}export{OL as $,xc as $a,Vp as $i,qO as $n,x_ as $r,$j as $t,hR as A,Th as Aa,zh as Ai,pA as An,ca as Ao,Ey as Ar,MI as At,XL as B,km as Ba,Kp as Bi,Tk as Bn,Ki as Bo,oy as Br,EM as Bt,sR as C,xh as Ca,N as Ci,hj as Cn,va as Co,Yy as Cr,sF as Ct,BL as D,bh as Da,lm as Di,uA as Dn,fa as Do,Ny as Dr,uI as Dt,OR as E,Eh as Ea,P as Ei,wA as En,ba as Eo,W as Er,uF as Et,eR as F,B as Fa,xm as Fi,tA as Fn,Gi as Fo,Sy as Fr,PM as Ft,wR as G,Om as Ga,O as Gi,ik as Gn,vy as Gr,lM as Gt,_R as H,Yh as Ha,Up as Hi,Ck as Hn,Ji as Ho,zv as Hr,sM as Ht,rR as I,A as Ia,z as Ii,$k as In,Wi as Io,Uv as Ir,IM as It,FL as J,Nc as Ja,wm as Ji,nk as Jn,ey as Jr,yM as Jt,LL as K,cf as Ka,Xp as Ki,ak as Kn,ay as Kr,uM as Kt,nR as L,k as La,Mp as Li,qk as Ln,Zi as Lo,sy as Lr,SM as Lt,cR as M,Pm as Ma,vm as Mi,oA as Mn,ua as Mo,Ty as Mr,cN as Mt,lR as N,zm as Na,I as Ni,aA as Nn,ra as No,ky as Nr,sN as Nt,WL as O,hh as Oa,Lh as Oi,hA as On,ia as Oo,Py as Or,SI as Ot,gR as P,Im as Pa,am as Pi,Yk as Pn,sa as Po,xy as Pr,dN as Pt,bL as Q,Dc as Qa,Am as Qi,JO as Qn,S_ as Qr,nM as Qt,tR as R,bm as Ra,jp as Ri,eA as Rn,Xi as Ro,_y as Rr,wM as Rt,oR as S,ch as Sa,R as Si,fj as Sn,_a as So,xb as Sr,jF as St,QL as T,kh as Ta,M as Ti,EA as Tn,ha as To,Eb as Tr,lF as Tt,qL as U,Jh as Ua,Wp as Ui,kk as Un,zi as Uo,ny as Ur,cM as Ut,mR as V,Xh as Va,Hp as Vi,Ok as Vn,$i as Vo,Qv as Vr,TM as Vt,KL as W,zp as Wa,D as Wi,Ek as Wn,$v as Wr,dM as Wt,kL as X,Ec as Xa,Yp as Xi,lk as Xn,T_ as Xr,xM as Xt,NL as Y,kc as Ya,Jp as Yi,uk as Yn,D_ as Yr,bM as Yt,yL as Z,rd as Za,U as Zi,YO as Zn,b_ as Zr,DM as Zt,RL as _,Zm as _a,nh as _i,Bj as _n,Aa as _o,aT as _r,cF as _t,nB as a,Ah as aa,bg as ai,Uj as an,Zu as ao,JD as ar,bI as at,GL as b,Qm as ba,jh as bi,LA as bn,wa as bo,vb as br,$F as bt,$z as c,Um as ca,um as ci,Qj as cn,Ou as co,WE as cr,xI as ct,Yz as d,ah as da,Hm as di,zj as dn,Ws as do,PE as dr,DP as dt,$m as ea,Jg as ei,Jj as en,Tc as eo,GO as er,SL as et,Dz as f,V as fa,H as fi,Vj as fn,Ks as fo,FE as fr,yP as ft,JL as g,th as ga,L as gi,Fj as gn,Da as go,zT as gr,xP as gt,fz as h,Vm as ha,j as hi,Yj as hn,Sa as ho,jT as hr,LP as ht,eB as i,yh as ia,Tg as ii,Kj as in,jc as io,xD as ir,tF as it,iR as j,eh as ja,sm as ji,fA as jn,da as jo,Dy as jr,mN as jt,kR as k,Oh as ka,mm as ki,mA as kn,la as ko,My as kr,nI as kt,Zz as l,Xm as la,cm as li,Nj as ln,pc as lo,UE as lr,rI as lt,Nz as m,oh as ma,Qh as mi,Wj as mn,Lo as mo,MT as mr,IP as mt,iB as n,Sh as na,Wg as ni,Xj as nn,wc as no,RO as nr,tL as nt,Qz as o,Dh as oa,rg as oi,Mj as on,$u as oo,_D as or,lI as ot,Oz as p,dh as pa,Zh as pi,Zj as pn,ps as po,kE as pr,dP as pt,PL as q,Ad as qa,Qp as qi,dk as qn,by as qr,fM as qt,oB as r,lh as ra,wg as ri,Ij as rn,Sc as ro,kO as rr,PN as rt,tB as s,Bm as sa,F as si,Lj as sn,Qu as so,zE as sr,SP as st,aB as t,mh as ta,Gg as ti,Rj as tn,Ac as to,zO as tr,KI as tt,Xz as u,uh as ua,Nh as ui,Pj as un,Us as uo,BE as ur,sI as ut,zL as v,fh as va,im as vi,Hj as vn,Oa as vo,_b as vr,FP as vt,ZL as w,vh as wa,fm as wi,pj as wn,ga as wo,Tb as wr,rF as wt,aR as x,ph as xa,om as xi,gj as xn,Ta as xo,Cb as xr,jI as xt,YL as y,sh as ya,hm as yi,Gj as yn,Ca as yo,wb as yr,MP as yt,ER as z,ym as za,Gp as zi,Dk as zn,Qi as zo,qv as zr,CM as zt};
|