expandai 0.1.1 → 0.1.2

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.
@@ -2,7 +2,7 @@ import { Layer } from 'effect';
2
2
  export { CurrentRequestHeaders } from './RequestHeaders.js';
3
3
  export declare const ServerInfo: {
4
4
  readonly name: "expandai";
5
- readonly version: "0.1.1";
5
+ readonly version: "0.1.2";
6
6
  };
7
7
  export declare const makeServerLayer: (options?: {
8
8
  readonly includeDocs?: boolean;
@@ -172,7 +172,7 @@ schema (${n._tag}): ${n}`;return o},k5=(e)=>Ts("Invalid Argument",e),Awe=(e,t,r)
172
172
  `,a)}else if(i.length===c+1)t=!0,c=-1;else if(l===c+1){if(e.length===0)s.push(i.substring(a,c));else e=e+i.substring(a,c),s.push(e),e="";a=c+2,c=i.indexOf("\r",a),l=i.indexOf(`
173
173
  `,a)}else c=i.indexOf("\r",c+1);if(t)e=e+i.substring(a,i.length-1);else e=e+i.substring(a,i.length)}}),Sr(s)},n=ko({onInput:(o)=>{let s=r(o);return Ss(s)?n:Je(ut(s),()=>n)},onFailure:(o)=>e.length===0?ar(o):Je(ut(nt(e)),()=>ar(o)),onDone:(o)=>e.length===0?fa(o):Je(ut(nt(e)),()=>fa(o))});return n});var mg=d(2,(e,t)=>ci(ge(()=>new cA(e,void 0,Z)),tl()).pipe(Ur(([r,n])=>$b(t,(o)=>{let s=r.close(o);return s!==void 0?Xo(s,n):oe})),Ya,re(([r])=>Me(()=>VL(r.run(),r))))),VL=(e,t)=>{let r=e;switch(r._tag){case oA:return zo(t.getDone(),{onFailure:bn,onSuccess:(n)=>le(pe(n))});case sA:return le(Ae(t.getEmit()));case hl:return g(r.effect,T(()=>VL(t.run(),t)));case iA:return XR(r,()=>VL(t.run(),t),(n)=>bn(n))}};var da=(e)=>O8(qt(e)),jf=(e)=>YR(pD(e),(t,r)=>t,(t,r)=>t),Qx=(e)=>YR($L(e),(t,r)=>t,(t,r)=>t);var Cg=(e)=>M8(0,e.length,e),M8=(e,t,r)=>e===t?kn:g(ut(g(r,Hi(e))),Je(()=>M8(e+1,t,r))),_8=d((e)=>qR(e[1]),(e,t,r)=>r?.concurrent?uD(e,{other:t,onSelfDone:(n)=>vL((o)=>Me(()=>o_(n,o))),onOtherDone:(n)=>vL((o)=>Me(()=>o_(o,n)))}):Je(e,(n)=>iD(t,(o)=>[n,o])));var ml=d((e)=>qR(e[1]),(e,t,r)=>r?.concurrent?iD(_8(e,t,{concurrent:!0}),(n)=>n[1]):Je(e,()=>t)),oD=Symbol.for("effect/Channel/ChannelException"),U8=(e)=>({_tag:"ChannelException",[oD]:oD,error:e}),v8=(e)=>te(e,oD);var L8=Symbol.for("effect/RcRef"),ZL={_tag:"Empty"},PDe={_tag:"Closed"},HDe={_A:Z,_E:Z};class P8 extends Vo{acquire;context;scope;idleTimeToLive;[L8]=HDe;[ta]=ta;state=ZL;semaphore=Fm(1);constructor(e,t,r,n){super();this.acquire=e,this.context=t,this.scope=r,this.idleTimeToLive=n,this.get=XL(this)}get;commit(){return this.get}}var H8=(e)=>Ke((t)=>{let r=t.getFiberRef(In),n=pr(r,jo),o=new P8(e.acquire,r,n,e.idleTimeToLive?Nn(e.idleTimeToLive):void 0);return Jt(n.addFinalizer(()=>o.semaphore.withPermits(1)(De(()=>{let s=o.state._tag==="Acquired"?_a(o.state.scope,fr):$e;return o.state=PDe,s}))),o)}),XL=(e)=>{let t=e,r=t.idleTimeToLive&&!hB(t.idleTimeToLive);return An((n)=>De(()=>{switch(t.state._tag){case"Closed":return qo;case"Acquired":return t.state.refCount++,t.state.fiber?Jt(yu(t.state.fiber),t.state):X(t.state);case"Empty":return vu().pipe(Cb("scope"),Eb("value",({scope:o})=>n(Rs(t.acquire,In,Ar(t.context,jo,o)))),Se(({scope:o,value:s})=>{let i={_tag:"Acquired",value:s,scope:o,fiber:void 0,refCount:1};return t.state=i,i}))}})).pipe(t.semaphore.withPermits(1),Cb("state"),Eb("scope",()=>jo),ws(({scope:n,state:o})=>n.addFinalizer(()=>De(()=>{if(o.refCount--,o.refCount>0||r)return $e;if(t.idleTimeToLive===void 0)return t.state=ZL,_a(o.scope,fr);return Ou(t.idleTimeToLive).pipe(Pc,ht(De(()=>{if(t.state._tag==="Acquired"&&t.state.refCount===0)return t.state=ZL,_a(o.scope,fr);return $e})),ra(V(()=>{o.fiber=void 0})),ay(t.scope),ws((s)=>{o.fiber=s}),t.semaphore.withPermits(1))}))),Se(({state:n})=>n.value))};var W8=H8,eP=XL;var Y8=Symbol.for("effect/Sink"),s0e={_A:(e)=>e,_In:(e)=>e,_L:(e)=>e,_E:(e)=>e,_R:(e)=>e};class tc{channel;[Y8]=s0e;constructor(e){this.channel=e}pipe(){return v(this,arguments)}}var V8=(e)=>new tc(gi(()=>$f(e())));var tP=()=>new tc(J8(Ot())),J8=(e)=>ko({onInput:(t)=>J8(g(e,Wt(t))),onFailure:ar,onDone:()=>fa(e)});var dD=new tc(gg(Ix()));var z8=(e,t,r)=>V8(()=>new tc(j8(e,t,r))),j8=(e,t,r)=>{if(!t(e))return To(e);return pa({onInput:(n)=>j8(r(e,n),t,r),onFailure:mi,onDone:()=>To(e)})};var $8=(e,t)=>z8(e,Zn,t);var rP=(e)=>{let t=ko({onInput:(r)=>g(qt($t(r,(n)=>e(n),{discard:!0})),Je(()=>t)),onFailure:ar,onDone:()=>kn});return new tc(t)},nP=(e)=>{let t=ko({onInput:(r)=>g(qt(e(r)),Je(()=>t)),onFailure:ar,onDone:()=>kn});return new tc(t)};var oP=(e)=>new tc(e),sP=(e)=>new tc(qt(e));var $f=(e)=>Qn(e)?$f(sP(e)):e.channel;var K8=(e)=>new tc(jf(e.pipe(re((t)=>$f(t)))));var X8=(e)=>Object.assign(e,{chunk(r){return this(le(r))},die(r){return this(Ko(r))},dieMessage(r){return this(Cf(r))},done(r){return this(Me(()=>n_(r,{onFailure:W,onSuccess:nt})))},end(){return this(xe(U()))},fail(r){return this(xe(W(r)))},fromEffect(r){return this(qm(r,{onFailure:W,onSuccess:nt}))},fromEffectChunk(r){return this(g(r,_e(W)))},halt(r){return this(bn(g(r,jc(W))))},single(r){return this(le(nt(r)))}});var c0e="effect/Take",l0e=Symbol.for(c0e),u0e={_A:(e)=>e,_E:(e)=>e};class hD{exit;[l0e]=u0e;constructor(e){this.exit=e}pipe(){return v(this,arguments)}}var mD=(e)=>new hD(so(e));var e6=(e)=>Me(()=>e.exit),gD=new hD(Yc(U()));var ED=(e)=>new hD(Kr(g(e,jc(W))));var t6=(e)=>Sf(e,{onFailure:(t)=>Ge(Wb(t),{onNone:()=>gD,onSome:ED}),onSuccess:mD});var iP=d(2,(e,{onEnd:t,onFailure:r,onSuccess:n})=>zo(e.exit,{onFailure:(o)=>Ge(Wb(o),{onNone:t,onSome:r}),onSuccess:n}));var r6=()=>xe(U());var N0e="effect/Stream",CD=Symbol.for(N0e),M0e={_R:(e)=>e,_E:(e)=>e,_A:(e)=>e};class en{channel;[CD]=M0e;constructor(e){this.channel=e}pipe(){return v(this,arguments)}}var yD=(e)=>te(e,CD)||Qn(e);var _0e=(e)=>{if(e==="unbounded")return lx();else if(typeof e==="number"||e===void 0)return lg(e??16);switch(e.strategy){case"dropping":return wR(e.bufferSize??16);case"sliding":return RR(e.bufferSize??16);default:return lg(e.bufferSize??16)}};var i6=(e,t)=>g(br(_0e(t),(r)=>fl(r)),T((r)=>g(tl(),T((n)=>g(e(X8((o)=>g(t6(o),T((s)=>hi(r,s)),Va,A5(n)).then((s)=>{if(Jo(s)){if(!df(s.cause))throw Hu(s.cause)}}))),Ue(ni(!1)),T((o)=>g(cf(o),re((s)=>s?r6():g(Vf(r),T(e6),Cy(()=>g(mm(o,!0),Ue(fl(r)))))))))))),lP,aP(x6));var a6=d(2,(e,t)=>{if(t.strategy==="dropping")return U0e(e,t.capacity);else if(t.strategy==="sliding")return v0e(e,t.capacity);let r=w6(e,t);return new en(jf(re(r,(n)=>{let o=g(qt(Vf(n)),Je(iP({onEnd:()=>kn,onFailure:ar,onSuccess:(s)=>g(ut(s),Je(()=>o))})));return o})))}),U0e=d(2,(e,t)=>{let r=br(wR(t),(n)=>fl(n));return new en(c6(r,Dr(e)))}),v0e=d(2,(e,t)=>{let r=br(RR(t),(n)=>fl(n));return new en(c6(r,Dr(e)))});var c6=(e,t)=>{let r=(o,s)=>{let i=(a)=>g(cf(s),Ur(gt),Ue(jt()),T((c)=>g(hi(o,[a,c]),Ue(mm(s,c)),Ue(gt(c)))),Va,qt);return ko({onInput:(a)=>g(jt(),T((c)=>g(hi(o,[mD(a),c]),T((l)=>g(mm(s,c),ia(()=>l))))),Va,qt,Je(()=>r(o,s))),onFailure:(a)=>i(ED(a)),onDone:()=>i(gD)})},n=(o)=>{let s=g(qt(Vf(o)),Je(([i,a])=>ml(qt(_n(a,void 0)),iP(i,{onEnd:()=>kn,onFailure:ar,onSuccess:(c)=>g(ut(c),Je(()=>s))}))));return s};return jf(g(e,T((o)=>g(jt(),Ur((s)=>_n(s,void 0)),T((s)=>g(ni(s),T((i)=>g(t,vr(r(o,i)),AD,xf)),bo(n(o))))))))},l6=d(2,(e,t)=>u6(e,(r)=>Fr(ny(r),{onLeft:t,onRight:d6}))),u6=d(2,(e,t)=>new en(g(Dr(e),fx((r)=>Dr(t(r))))));var A6=(e)=>bx(Ko(e));var p6=new en(kn),f6=d(2,(e,t)=>new en(g(Dr(e),Eg(t))));var d6=(e)=>bx(bn(e));var aP=d((e)=>yD(e[0]),(e,t,r)=>{let n=r?.bufferSize??16;if(r?.switch)return n6(r?.concurrency,()=>o6(e,1,n,t),(o)=>o6(e,o,n,t));return n6(r?.concurrency,()=>new en(xx(Dr(e),(o)=>g(o,Qp((s)=>Dr(t(s))),sC(kn,(s,i)=>g(s,ml(i)))))),(o)=>new en(g(Dr(e),xx(Cg),lD((s)=>Dr(t(s)),r))))}),n6=(e,t,r)=>{switch(e){case void 0:return t();case"unbounded":return r(Number.MAX_SAFE_INTEGER);default:return e>1?r(e):t()}},o6=d(4,(e,t,r,n)=>new en(g(Dr(e),xx(Cg),lD((o)=>Dr(n(o)),{concurrency:t,mergeStrategy:S8(),bufferSize:r})))),cP=d((e)=>yD(e[0]),(e,t)=>aP(e,Z,t));var xD=(e)=>new en(e),Dr=(e)=>{if("channel"in e)return e.channel;else if(Qn(e))return Dr(bx(e));else throw TypeError("Expected a Stream.")};var bx=(e)=>g(e,_e(W),h6),h6=(e)=>new en(da(bw(e,{onFailure:Ge({onNone:()=>kn,onSome:mi}),onSuccess:(t)=>ut(nt(t))})));var m6=d(2,(e,t)=>new en(g(Dr(e),Sx(t)))),g6=d(2,(e,t)=>new en(g(Dr(e),cD(t))));var E6=d(2,(e,t)=>new en(g(Dr(e),aD(t))));var C6=d(2,(e,t)=>new en(vr(Dr(e),t)));var y6=d(2,(e,t)=>new en(g(Dr(e),hx(t))));var x6=(e)=>D6(e,(t)=>g(re(t,(r)=>W([r,t])),Un(Ge({onNone:()=>le(U()),onSome:xe}))));var wx=d(2,(e,t)=>Dr(e).pipe(Bx($f(t)),jL)),I6=(e)=>wx(e,tP());var S6=(e)=>wx(e,dD);var B6=d(2,(e,t)=>wx(e,nP(t)));var Q6=d(2,(e,t)=>{let r=ko({onInput:(n)=>Je(ut(mD(n)),()=>r),onFailure:(n)=>ut(ED(n)),onDone:()=>ut(gD)});return g(vr(Dr(e),r),cD((n)=>hi(t,n)),gg,AD,Va)});var lP=(e)=>new en(Eg(pD(g(e,re(nt))),oe));var b6=(e)=>C6(e,KL());var uP=(e)=>new en(gi(()=>Dr(e())));var w6=d((e)=>yD(e[0]),(e,t)=>Ur(br(t?.strategy==="unbounded"?lx():t?.strategy==="dropping"?wR(t.capacity??2):t?.strategy==="sliding"?RR(t.capacity??2):lg(t?.capacity??2),(r)=>fl(r)),(r)=>xf(Q6(e,r))));var R6=d(2,(e,t)=>{let r=gi(()=>{let n={ref:Ot()},o={ref:!1},s=gi(()=>{let l=n.ref;if(Ss(l))return pa({onInput:(u)=>g(ut(u),Je(()=>s)),onFailure:mi,onDone:To});return n.ref=Ot(),g(Cg(l),Je(()=>s))}),i=(l)=>{let u=n.ref,A=Wt(u,Ih(l,(p)=>p.length!==0));return n.ref=A,A},a=pa({onInput:(l)=>Je(ut(l),()=>a),onFailure:mi,onDone:(l)=>ml(dl(()=>{o.ref=!0}),To(l))}),c=g(t,$f,GR,Je(([l,u])=>g(fa([o.ref,i(l)]),Je(([A,p])=>{let f=A&&Ss(p)?kn:c;return g(ut(nt(u)),Je(()=>f))}))));return g(Dr(e),vr(a),vr(s),Bx(c))});return new en(r)});var D6=(e,t)=>uP(()=>{let r=(n)=>da(re(t(n),Ge({onNone:()=>kn,onSome:([o,s])=>Je(ut(o),()=>r(s))})));return new en(r(e))});var k6=(e)=>cP(bx(e)),T6=(e)=>cP(lP(e));var AP=CD;var F6=i6;var N6=a6,pP=l6;var M6=A6;var L0e=p6,_6=f6;var yg=xD;var U6=m6,v6=g6;var L6=E6;var ID=y6;var xg=wx,P6=I6;var P0e=S6;var fP=B6;var H6=b6;var W6=uP;var q6=R6;var G6=k6,rc=T6;var Y6=Symbol.for("effect/Brand/Refined");var Rx=()=>Object.assign((e)=>e,{[Y6]:Y6,option:(e)=>W(e),either:(e)=>Ae(e),is:(e)=>!0});var J6=dD;var z6=$8;var j6=rP;var $6=oP;var K6=K8;var dP=Symbol.for("@effect/platform/CommandExecutor"),Z6=Symbol.for("@effect/platform/Process"),X6=Rx(),e7=Rx(),BD=dt("@effect/platform/CommandExecutor"),t7=(e)=>{let t=(n)=>rc(re(e(n),(o)=>o.stdout)),r=(n,o)=>{let s=new TextDecoder(o);return H6(U6(t(n),Qp((i)=>s.decode(i))))};return{[dP]:dP,start:e,exitCode:(n)=>wo(T(e(n),(o)=>o.exitCode)),stream:t,string:(n,o="utf-8")=>{let s=new TextDecoder(o);return g(e(n),T((i)=>xg(i.stdout,H0e)),re((i)=>s.decode(i)),wo)},lines:(n,o="utf-8")=>g(r(n,o),P6,re(QY)),streamLines:r}},H0e=z6(new Uint8Array,(e,t)=>sC(t,e,(r,n)=>{let o=new Uint8Array(r.length+n.length);return o.set(r),o.set(n,r.length),o}));var hP=Symbol.for("@effect/platform/Command");var n7=(e)=>Array.from(mP(e)),mP=(e)=>{switch(e._tag){case"StandardCommand":return nt(e);case"PipedCommand":return Wt(mP(e.left),mP(e.right))}};var o7={[hP]:hP,pipe(){return v(this,arguments)},...Cs},W0e={...o7,_tag:"StandardCommand",toJSON(){return{_id:"@effect/platform/Command",_tag:this._tag,command:this.command,args:this.args,env:Object.fromEntries(this.env),cwd:this.cwd.toJSON(),shell:this.shell,gid:this.gid.toJSON(),uid:this.uid.toJSON()}}},QD=(e)=>Object.assign(Object.create(W0e),e),q0e={...o7,_tag:"PipedCommand",toJSON(){return{_id:"@effect/platform/Command",_tag:this._tag,left:this.left.toJSON(),right:this.right.toJSON()}}},gP=(e)=>Object.assign(Object.create(q0e),e),s7=(e,...t)=>QD({command:e,args:t,env:Mc(),cwd:U(),shell:!1,stdin:"pipe",stdout:"pipe",stderr:"pipe",gid:U(),uid:U()});var EP=d(2,(e,t)=>{switch(e._tag){case"StandardCommand":return QD({...e,stderr:t});case"PipedCommand":return gP({...e,right:EP(e.right,t)})}}),CP=d(2,(e,t)=>{switch(e._tag){case"StandardCommand":return QD({...e,stdin:t});case"PipedCommand":return gP({...e,left:CP(e.left,t)})}}),yP=d(2,(e,t)=>{switch(e._tag){case"StandardCommand":return QD({...e,stdout:t});case"PipedCommand":return gP({...e,right:yP(e.right,t)})}}),i7=(e)=>T(BD,(t)=>t.start(e));var xP=n7;var a7=s7;var Y0e=i7;var V0e=EP,bD=CP,J0e=yP;var Dx=BD,IP=Z6,c7=X6,l7=e7,u7=t7;var RD=Symbol.for("@effect/platform/Error");var BP=(e,t)=>{class r extends fy{_tag=t}return r.prototype[e]=e,r.prototype.name=t,r},A7=N("Clipboard","Command","FileSystem","KeyValueStore","Path","Stream","Terminal");class Oo extends at("@effect/platform/Error/BadArgument")("BadArgument",{module:A7,method:m,description:M(m),cause:M(Pt)}){[RD]=RD;get message(){return`${this.module}.${this.method}${this.description?`: ${this.description}`:""}`}}var z0e=N("AlreadyExists","BadResource","Busy","InvalidData","NotFound","PermissionDenied","TimedOut","UnexpectedEof","Unknown","WouldBlock","WriteZero");class gl extends at("@effect/platform/Error/SystemError")("SystemError",{reason:z0e,module:A7,method:m,description:M(m),syscall:M(m),pathOrDescriptor:M(Ie(m,K)),cause:M(Pt)}){[RD]=RD;get message(){return`${this.reason}: ${this.module}.${this.method}${this.pathOrDescriptor!==void 0?` (${this.pathOrDescriptor})`:""}${this.description?`: ${this.description}`:""}`}}var QP=Symbol.for("@effect/platform/Cookies"),$0e=(e)=>te(e,QP),p7=Symbol.for("@effect/platform/Cookies/Cookie");var K0e={[QP]:QP,...Cs,toJSON(){return{_id:"@effect/platform/Cookies",cookies:fY(this.cookies,(e)=>e.toJSON())}},pipe(){return v(this,arguments)}},Z0e=(e)=>{let t=Object.create(K0e);return t.cookies=e,t},d7=(e)=>{let t={};for(let r of e)t[r.name]=r;return Z0e(t)},DD=(e)=>{let t=typeof e==="string"?[e]:e,r=[];for(let n of t){let o=X0e(n.trim());if(fe(o))r.push(o.value)}return d7(r)};function X0e(e){let t=e.split(";").map((a)=>a.trim()).filter((a)=>a!=="");if(t.length===0)return U();let r=t[0].indexOf("=");if(r===-1)return U();let n=t[0].slice(0,r);if(!eke.test(n))return U();let o=t[0].slice(r+1),s=rke(o);if(t.length===1)return W(Object.assign(Object.create(f7),{name:n,value:s,valueEncoded:o}));let i={};for(let a=1;a<t.length;a++){let c=t[a],l=c.indexOf("="),u=l===-1?c:c.slice(0,l).trim(),A=l===-1?void 0:c.slice(l+1).trim();switch(u.toLowerCase()){case"domain":{if(A===void 0)break;let p=A.trim().replace(/^\./,"");if(p)i.domain=p;break}case"expires":{if(A===void 0)break;let p=new Date(A);if(!isNaN(p.getTime()))i.expires=p;break}case"max-age":{if(A===void 0)break;let p=parseInt(A,10);if(!isNaN(p))i.maxAge=mB(p);break}case"path":{if(A===void 0)break;if(A[0]==="/")i.path=A;break}case"priority":{if(A===void 0)break;switch(A.toLowerCase()){case"low":i.priority="low";break;case"medium":i.priority="medium";break;case"high":i.priority="high";break}break}case"httponly":{i.httpOnly=!0;break}case"secure":{i.secure=!0;break}case"partitioned":{i.partitioned=!0;break}case"samesite":{if(A===void 0)break;switch(A.toLowerCase()){case"lax":i.sameSite="lax";break;case"strict":i.sameSite="strict";break;case"none":i.sameSite="none";break}break}}}return W(Object.assign(Object.create(f7),{name:n,value:s,valueEncoded:o,options:Object.keys(i).length>0?i:void 0}))}var kD=d7([]);var eke=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,f7={[p7]:p7,...Cs,toJSON(){return{_id:"@effect/platform/Cookies/Cookie",name:this.name,value:this.value,options:this.options}}};var tke=d((e)=>$0e(e[0]),(e,t)=>pY(e.cookies,t));var rke=(e)=>{try{return decodeURIComponent(e)}catch{return e}};var h7=T8;var bP=dx;var m7=Eg;var lA=Je;var g7=qt;var wP=gi;var kx=kn;var OD=ut;var RP=dt("@effect/platform/FileSystem"),Ox=(e)=>typeof e==="bigint"?e:BigInt(e);var Tx=BigInt(1024),Sxt=Tx*Tx*Tx*Tx*Tx;var E7=(e)=>RP.of({...e,exists:(t)=>g(e.access(t),bo(!0),qa("SystemError",(r)=>r.reason==="NotFound"?le(!1):xe(r))),readFileString:(t,r)=>Wm(e.readFile(t),{try:(n)=>new TextDecoder(r).decode(n),catch:(n)=>new Oo({module:"FileSystem",method:"readFileString",description:"invalid encoding",cause:n})}),stream:(t,r)=>g(e.open(t,{flag:"r"}),r?.offset?Ur((n)=>n.seek(r.offset,"start")):Z,re((n)=>nke(n,r)),rc),sink:(t,r)=>g(e.open(t,{flag:"w",...r}),re((n)=>j6((o)=>n.writeAll(o))),K6),writeFileString:(t,r,n)=>T(Qo({try:()=>new TextEncoder().encode(r),catch:(o)=>new Oo({module:"FileSystem",method:"writeFileString",description:"could not encode string",cause:o})}),(o)=>e.writeFile(t,o,n))});var nke=(e,{bufferSize:t=16,bytesToRead:r,chunkSize:n=Ox(65536)}={})=>{let o=r!==void 0?Ox(r):void 0,s=Ox(n);function i(a){if(o!==void 0&&o<=a)return kx;let c=o!==void 0&&o-a<s?o-a:s;return lA(e.readAlloc(c),Ge({onNone:()=>kx,onSome:(l)=>lA(OD(nt(l)),(u)=>i(a+BigInt(l.length)))}))}return N6(yg(i(BigInt(0))),{capacity:t})};var Sg=Ox;var Ms=RP,C7=E7;var ND=Symbol.for("@effect/platform/FileSystem/File");var y7=Rx(),x7=Um("Create"),I7=Um("Update"),S7=Um("Remove");class DP extends ba("@effect/platform/FileSystem/WatchBackend")(){}var B7=Symbol.for("@effect/platform/Headers");var Nx=Object.assign(Object.create(null),{[B7]:B7,[zE](e){return UD(this,KQ(e,TP))}}),MD=(e)=>Object.assign(Object.create(Nx),e);var Bg=Object.create(Nx),Kf=(e)=>{if(e===void 0)return Bg;else if(Symbol.iterator in e){let r=Object.create(Nx);for(let[n,o]of e)r[n.toLowerCase()]=o;return r}let t=Object.create(Nx);for(let[r,n]of Object.entries(e))if(Array.isArray(n))t[r.toLowerCase()]=n.join(", ");else if(n!==void 0)t[r.toLowerCase()]=n;return t},Q7=(e)=>Object.setPrototypeOf(e,Nx);var _D=d(3,(e,t,r)=>{let n=MD(e);return n[t.toLowerCase()]=r,n}),b7=d(2,(e,t)=>MD({...e,...Kf(t)})),kP=d(2,(e,t)=>{let r=MD(e);return Object.assign(r,t),r}),w7=d(2,(e,t)=>{let r=MD(e),n=(o)=>{if(typeof o==="string"){let s=o.toLowerCase();if(s in e)delete r[s]}else for(let s in e)if(o.test(s))delete r[s]};if(Array.isArray(t))for(let o=0;o<t.length;o++)n(t[o]);else n(t);return r}),UD=d(2,(e,t)=>{let r={...e},n=(o)=>{if(typeof o==="string"){let s=o.toLowerCase();if(s in e)r[s]=ja(e[s])}else for(let s in e)if(o.test(s))r[s]=ja(e[s])};if(Array.isArray(t))for(let o=0;o<t.length;o++)n(t[o]);else n(t);return r}),TP=me("@effect/platform/Headers/currentRedactedNames",()=>$u(["authorization","cookie","set-cookie","x-api-key"]));var R7=Symbol.for("@effect/platform/HttpClientError");var D7=R7;class ha extends BP(D7,"RequestError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){return this.description?`${this.reason}: ${this.description} (${this.methodAndUrl})`:`${this.reason} error (${this.methodAndUrl})`}}class is extends BP(D7,"ResponseError"){get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return this.description?`${this.reason}: ${this.description} (${e})`:`${this.reason} error (${e})`}}var uA=(e)=>{let t=k7(e),r=[];for(let n=0;n<t.length;n++)if(Array.isArray(t[n][0])){let[o,s]=t[n];r.push([`${o[0]}[${o.slice(1).join("][")}]`,s])}else r.push(t[n]);return r},k7=(e)=>{let t=Symbol.iterator in e?et(e):Object.entries(e),r=[];for(let[n,o]of t)if(Array.isArray(o)){for(let s=0;s<o.length;s++)if(o[s]!==void 0)r.push([n,String(o[s])])}else if(typeof o==="object"){let s=k7(o);for(let[i,a]of s)r.push([[n,...typeof i==="string"?[i]:i],a])}else if(o!==void 0)r.push([n,String(o)]);return r};var T7=[];var O7=d(2,(e,t)=>{let r=uA(t),n=new Set;for(let o=0;o<r.length;o++)n.add(r[o][0]);for(let o=0;o<e.length;o++){if(n.has(e[o][0]))continue;r.push(e[o])}return r});var OP=(e,t,r)=>{try{let n=new URL(e,ike());for(let o=0;o<t.length;o++){let[s,i]=t[o];if(i!==void 0)n.searchParams.append(s,i)}if(r._tag==="Some")n.hash=r.value;return Ae(n)}catch(n){return pe(n)}},F7=(e)=>new URLSearchParams(e).toString(),ike=()=>{if("location"in globalThis&&globalThis.location!==void 0&&globalThis.location.origin!==void 0&&globalThis.location.pathname!==void 0)return location.origin+location.pathname;return};var ma=Symbol.for("@effect/platform/HttpIncomingMessage"),as=(e,t)=>{let r=os(e,t);return(n)=>T(n.json,r)};class LD extends Mn()("@effect/platform/HttpIncomingMessage/MaxBodySize",{defaultValue:U}){}var PD=(e,t)=>{let r=e.headers["content-type"]??"",n;if(r.includes("application/json"))try{n=ts(e.json)}catch{}else if(r.includes("text/")||r.includes("urlencoded"))try{n=ts(e.text)}catch{}let o={...t,headers:uh(e.headers),remoteAddress:e.remoteAddress.toJSON()};if(n!==void 0)o.body=n;return o};var N7=(e)=>Q7({b3:`${e.traceId}-${e.spanId}-${e.sampled?"1":"0"}${e.parent._tag==="Some"?`-${e.parent.value.spanId}`:""}`,traceparent:`00-${e.traceId}-${e.spanId}-${e.sampled?"01":"00"}`});var FP=Symbol.for("@effect/platform/HttpBody"),M7=Symbol.for("@effect/platform/HttpBody/HttpBodyError"),cke=Um("HttpBodyError"),lke=(e)=>cke({[M7]:M7,reason:e});class NP{[FP];constructor(){this[FP]=FP}[Re](){return this.toJSON()}toString(){return je(this)}}class _7 extends NP{_tag="Empty";toJSON(){return{_id:"@effect/platform/HttpBody",_tag:"Empty"}}}var U7=new _7;class v7 extends NP{body;contentType;_tag="Uint8Array";constructor(e,t){super();this.body=e,this.contentType=t}get contentLength(){return this.body.length}toJSON(){return{_id:"@effect/platform/HttpBody",_tag:"Uint8Array",body:this.contentType.startsWith("text/")||this.contentType.endsWith("json")?new TextDecoder().decode(this.body):`Uint8Array(${this.body.length})`,contentType:this.contentType,contentLength:this.contentLength}}}var L7=(e,t)=>new v7(e,t??"application/octet-stream"),uke=new TextEncoder,MP=(e,t)=>L7(uke.encode(e),t??"text/plain"),P7=(e,t)=>MP(JSON.stringify(e),t??"application/json"),H7=(e,t)=>Qo({try:()=>P7(e,t),catch:(r)=>lke({_tag:"JsonError",error:r})});var W7=Symbol.for("@effect/platform/HttpClientRequest"),pke={[W7]:W7,...Cs,toJSON(){return{_id:"@effect/platform/HttpClientRequest",method:this.method,url:this.url,urlParams:this.urlParams,hash:this.hash,headers:uh(this.headers),body:this.body.toJSON()}},pipe(){return v(this,arguments)}};function nc(e,t,r,n,o,s){let i=Object.create(pke);return i.method=e,i.url=t,i.urlParams=r,i.hash=n,i.headers=o,i.body=s,i}var fke=nc("GET","",T7,U(),Bg,U7),El=(e)=>(t,r)=>q7(fke,{method:e,url:t,...r??void 0}),WD=El("GET"),qD=El("POST"),_P=El("PUT"),UP=El("PATCH"),vP=El("DELETE"),LP=El("HEAD"),PP=El("OPTIONS"),q7=d(2,(e,t)=>{let r=e;if(t.method)r=V7(r,t.method);if(t.url)r=WP(r,t.url);if(t.headers)r=_x(r,t.headers);if(t.urlParams)r=qP(r,t.urlParams);if(t.hash)r=z7(r,t.hash);if(t.body)r=GD(r,t.body);if(t.accept)r=HP(r,t.accept);if(t.acceptJson)r=Y7(r);return r}),Mx=d(3,(e,t,r)=>nc(e.method,e.url,e.urlParams,e.hash,_D(e.headers,t,r),e.body)),_x=d(2,(e,t)=>nc(e.method,e.url,e.urlParams,e.hash,b7(e.headers,t),e.body)),dke=(e)=>typeof e==="string"?e:Jn(e);var G7=d(2,(e,t)=>Mx(e,"Authorization",`Bearer ${dke(t)}`)),HP=d(2,(e,t)=>Mx(e,"Accept",t)),Y7=HP("application/json"),V7=d(2,(e,t)=>nc(t,e.url,e.urlParams,e.hash,e.headers,e.body)),WP=d(2,(e,t)=>{if(typeof t==="string")return nc(e.method,t,e.urlParams,e.hash,e.headers,e.body);let r=new URL(t.toString()),n=uA(r.searchParams),o=r.hash?W(r.hash.slice(1)):U();return r.search="",r.hash="",nc(e.method,r.toString(),n,o,e.headers,e.body)});var J7=d(2,(e,t)=>nc(e.method,t.endsWith("/")&&e.url.startsWith("/")?t+e.url.slice(1):t+e.url,e.urlParams,e.hash,e.headers,e.body));var qP=d(2,(e,t)=>nc(e.method,e.url,O7(e.urlParams,t),e.hash,e.headers,e.body)),z7=d(2,(e,t)=>nc(e.method,e.url,e.urlParams,W(t),e.headers,e.body));var GD=d(2,(e,t)=>{let r=e.headers;if(t._tag==="Empty"||t._tag==="FormData")r=w7(r,["Content-type","Content-length"]);else{let n=t.contentType;if(n)r=_D(r,"content-type",n);let o=t.contentLength;if(o)r=_D(r,"content-length",o.toString())}return nc(e.method,e.url,e.urlParams,e.hash,r,t)});var j7=d(2,(e,t)=>re(H7(t),(r)=>GD(e,r)));var $7=d(2,(e,t)=>GD(e,MP(F7(uA(t)),"application/x-www-form-urlencoded")));var Ux=Symbol.for("@effect/platform/HttpClientResponse");var Z7=d(2,(e,t)=>{let r=e.status;if(t[r])return t[r](e);else if(r>=200&&r<300&&t["2xx"])return t["2xx"](e);else if(r>=300&&r<400&&t["3xx"])return t["3xx"](e);else if(r>=400&&r<500&&t["4xx"])return t["4xx"](e);else if(r>=500&&r<600&&t["5xx"])return t["5xx"](e);return t.orElse(e)});var gke=(e)=>`http.request.header.${e}`,Eke="http.request.method",Cke=(e)=>`http.response.header.${e}`,yke="http.response.status_code",xke="server.address",Ike="server.port",Ske="url.full",Bke="url.path",Qke="url.scheme",bke="url.query",GP=Symbol.for("@effect/platform/HttpClient"),VD=dt("@effect/platform/HttpClient"),eee=me(Symbol.for("@effect/platform/HttpClient/tracerDisabledWhen"),()=>$u(Or));var tee=me(Symbol.for("@effect/platform/HttpClient/currentTracerPropagation"),()=>$u(!0));var ree=Mn()("@effect/platform/HttpClient/SpanNameGenerator",{defaultValue:()=>(e)=>`http.client ${e.method}`});var wke={[GP]:GP,pipe(){return v(this,arguments)},...Cs,toJSON(){return{_id:"@effect/platform/HttpClient"}},get(e,t){return this.execute(WD(e,t))},head(e,t){return this.execute(LP(e,t))},post(e,t){return this.execute(qD(e,t))},put(e,t){return this.execute(_P(e,t))},patch(e,t){return this.execute(UP(e,t))},del(e,t){return this.execute(vP(e,t))},options(e,t){return this.execute(PP(e,t))}};var JD=(e,t)=>{let r=Object.create(wke);return r.preprocess=t,r.postprocess=e,r.execute=function(n){return e(t(n))},r},YD=me("@effect/platform/HttpClient/responseRegistry",()=>{if("FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry){let t=new FinalizationRegistry((r)=>{r.abort()});return{register(r,n){t.register(r,n,r)},unregister(r){t.unregister(r)}}}let e=new Map;return{register(t,r){e.set(t,setTimeout(()=>r.abort(),5000))},unregister(t){let r=e.get(t);if(r===void 0)return;clearTimeout(r),e.delete(t)}}}),Rke=me("@effect/platform/HttpClient/scopedRequests",()=>new WeakMap),nee=(e)=>JD((t)=>T(t,(r)=>oa((n)=>{let o=Rke.get(r),s=o??new AbortController,i=OP(r.url,r.urlParams,r.hash);if(i._tag==="Left")return xe(new ha({request:r,reason:"InvalidUrl",cause:i.left}));let a=i.right;if(!n.getFiberRef(u5)||n.getFiberRef(eee)(r)){let u=e(r,a,s.signal,n);if(o)return u;return Zc((A)=>lo(A(u),{onSuccess(p){return YD.register(p,s),le(new YP(p,s))},onFailure(p){if(df(p))s.abort();return bn(p)}}))}let l=pr(n.currentContext,ree);return Rw(l(r),{kind:"client",captureStackTrace:!1},(u)=>{if(u.attribute(Eke,r.method),u.attribute(xke,a.origin),a.port!=="")u.attribute(Ike,+a.port);u.attribute(Ske,a.toString()),u.attribute(Bke,a.pathname),u.attribute(Qke,a.protocol.slice(0,-1));let A=a.search.slice(1);if(A!=="")u.attribute(bke,A);let p=n.getFiberRef(TP),f=UD(r.headers,p);for(let h in f)u.attribute(gke(h),String(f[h]));return r=n.getFiberRef(tee)?_x(r,N7(u)):r,Zc((h)=>h(e(r,a,s.signal,n)).pipe(Ry(u),lo({onSuccess:(E)=>{u.attribute(yke,E.status);let x=UD(E.headers,p);for(let y in x)u.attribute(Cke(y),String(x[y]));if(o)return le(E);return YD.register(E,s),le(new YP(E,s))},onFailure(E){if(!o&&df(E))s.abort();return bn(E)}})))})})),le);class YP{original;controller;constructor(e,t){this.original=e,this.controller=t}[Ux]=Ux;[ma]=ma;applyInterrupt(e){return Me(()=>(YD.unregister(this.original),gw(e,()=>ge(()=>{this.controller.abort()}))))}get request(){return this.original.request}get status(){return this.original.status}get headers(){return this.original.headers}get cookies(){return this.original.cookies}get remoteAddress(){return this.original.remoteAddress}get formData(){return this.applyInterrupt(this.original.formData)}get text(){return this.applyInterrupt(this.original.text)}get json(){return this.applyInterrupt(this.original.json)}get urlParamsBody(){return this.applyInterrupt(this.original.urlParamsBody)}get arrayBuffer(){return this.applyInterrupt(this.original.arrayBuffer)}get stream(){return W6(()=>(YD.unregister(this.original),_6(this.original.stream,ge(()=>{this.controller.abort()}))))}toJSON(){return this.original.toJSON()}[Re](){return this.original[Re]()}}var{del:Dke,execute:kke,get:Tke,head:Oke,options:Fke,patch:Nke,post:Mke,put:_ke}=V3(VD);var oee=d(2,(e,t)=>{let r=e;return JD((n)=>t(r.postprocess(n)),r.preprocess)});var see=d(2,(e,t)=>{let r=e;return JD(r.postprocess,(n)=>re(r.preprocess(n),t))});var iee=(e)=>nl(VD,T(Rn(),(t)=>re(e,(r)=>oee(r,xw((n)=>Jr(t,n))))));var Xf=VD;var zD=nee;var jD=see;var $D=iee;var Ei=El,VP=WD,KD=qD;var bg=Mx,aee=_x;var vke=G7;var ZD=J7;var yl=qP;var Ci=j7;var Lke=$7;var pA=Ux;var _s=Z7;var XD=Symbol.for("@effect/platform/Path"),zP=dt("@effect/platform/Path");function cee(e,t){let r="",n=0,o=-1,s=0,i;for(let a=0;a<=e.length;++a){if(a<e.length)i=e.charCodeAt(a);else if(i===47)break;else i=47;if(i===47){if(o===a-1||s===1);else if(o!==a-1&&s===2){if(r.length<2||n!==2||r.charCodeAt(r.length-1)!==46||r.charCodeAt(r.length-2)!==46){if(r.length>2){let c=r.lastIndexOf("/");if(c!==r.length-1){if(c===-1)r="",n=0;else r=r.slice(0,c),n=r.length-1-r.lastIndexOf("/");o=a,s=0;continue}}else if(r.length===2||r.length===1){r="",n=0,o=a,s=0;continue}}if(t){if(r.length>0)r+="/..";else r="..";n=2}}else{if(r.length>0)r+="/"+e.slice(o+1,a);else r=e.slice(o+1,a);n=a-o-1}o=a,s=0}else if(i===46&&s!==-1)++s;else s=-1}return r}function Pke(e,t){let r=t.dir||t.root,n=t.base||(t.name||"")+(t.ext||"");if(!r)return n;if(r===t.root)return r+n;return r+e+n}function Hke(e){if(e.protocol!=="file:")return xe(new Oo({module:"Path",method:"fromFileUrl",description:"URL must be of scheme file"}));else if(e.hostname!=="")return xe(new Oo({module:"Path",method:"fromFileUrl",description:"Invalid file URL host"}));let t=e.pathname;for(let r=0;r<t.length;r++)if(t[r]==="%"){let n=t.codePointAt(r+2)|32;if(t[r+1]==="2"&&n===102)return xe(new Oo({module:"Path",method:"fromFileUrl",description:"must not include encoded / characters"}))}return le(decodeURIComponent(t))}var lee=function(){let t="",r=!1,n=void 0;for(let o=arguments.length-1;o>=-1&&!r;o--){let s;if(o>=0)s=arguments[o];else{let i=globalThis.process;if(n===void 0&&"process"in globalThis&&typeof i==="object"&&i!==null&&typeof i.cwd==="function")n=i.cwd();s=n}if(s.length===0)continue;t=s+"/"+t,r=s.charCodeAt(0)===47}if(t=cee(t,!r),r)if(t.length>0)return"/"+t;else return"/";else if(t.length>0)return t;else return"."},Wke=47;function qke(e){let t=new URL("file://"),r=lee(e);if(e.charCodeAt(e.length-1)===Wke&&r[r.length-1]!=="/")r+="/";return t.pathname=jke(r),le(t)}var Gke=/%/g,Yke=/\\/g,Vke=/\n/g,Jke=/\r/g,zke=/\t/g;function jke(e){if(e.includes("%"))e=e.replace(Gke,"%25");if(e.includes("\\"))e=e.replace(Yke,"%5C");if(e.includes(`
174
174
  `))e=e.replace(Vke,"%0A");if(e.includes("\r"))e=e.replace(Jke,"%0D");if(e.includes("\t"))e=e.replace(zke,"%09");return e}var JP=zP.of({[XD]:XD,resolve:lee,normalize(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,r=e.charCodeAt(e.length-1)===47;if(e=cee(e,!t),e.length===0&&!t)e=".";if(e.length>0&&r)e+="/";if(t)return"/"+e;return e},isAbsolute(e){return e.length>0&&e.charCodeAt(0)===47},join(){if(arguments.length===0)return".";let e;for(let t=0;t<arguments.length;++t){let r=arguments[t];if(r.length>0)if(e===void 0)e=r;else e+="/"+r}if(e===void 0)return".";return JP.normalize(e)},relative(e,t){if(e===t)return"";if(e=JP.resolve(e),t=JP.resolve(t),e===t)return"";let r=1;for(;r<e.length;++r)if(e.charCodeAt(r)!==47)break;let n=e.length,o=n-r,s=1;for(;s<t.length;++s)if(t.charCodeAt(s)!==47)break;let a=t.length-s,c=o<a?o:a,l=-1,u=0;for(;u<=c;++u){if(u===c){if(a>c){if(t.charCodeAt(s+u)===47)return t.slice(s+u+1);else if(u===0)return t.slice(s+u)}else if(o>c){if(e.charCodeAt(r+u)===47)l=u;else if(u===0)l=0}break}let p=e.charCodeAt(r+u),f=t.charCodeAt(s+u);if(p!==f)break;else if(p===47)l=u}let A="";for(u=r+l+1;u<=n;++u)if(u===n||e.charCodeAt(u)===47)if(A.length===0)A+="..";else A+="/..";if(A.length>0)return A+t.slice(s+l);else{if(s+=l,t.charCodeAt(s)===47)++s;return t.slice(s)}},dirname(e){if(e.length===0)return".";let t=e.charCodeAt(0),r=t===47,n=-1,o=!0;for(let s=e.length-1;s>=1;--s)if(t=e.charCodeAt(s),t===47){if(!o){n=s;break}}else o=!1;if(n===-1)return r?"/":".";if(r&&n===1)return"//";return e.slice(0,n)},basename(e,t){let r=0,n=-1,o=!0,s;if(t!==void 0&&t.length>0&&t.length<=e.length){if(t.length===e.length&&t===e)return"";let i=t.length-1,a=-1;for(s=e.length-1;s>=0;--s){let c=e.charCodeAt(s);if(c===47){if(!o){r=s+1;break}}else{if(a===-1)o=!1,a=s+1;if(i>=0)if(c===t.charCodeAt(i)){if(--i===-1)n=s}else i=-1,n=a}}if(r===n)n=a;else if(n===-1)n=e.length;return e.slice(r,n)}else{for(s=e.length-1;s>=0;--s)if(e.charCodeAt(s)===47){if(!o){r=s+1;break}}else if(n===-1)o=!1,n=s+1;if(n===-1)return"";return e.slice(r,n)}},extname(e){let t=-1,r=0,n=-1,o=!0,s=0;for(let i=e.length-1;i>=0;--i){let a=e.charCodeAt(i);if(a===47){if(!o){r=i+1;break}continue}if(n===-1)o=!1,n=i+1;if(a===46){if(t===-1)t=i;else if(s!==1)s=1}else if(t!==-1)s=-1}if(t===-1||n===-1||s===0||s===1&&t===n-1&&t===r+1)return"";return e.slice(t,n)},format:function(t){if(t===null||typeof t!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof t);return Pke("/",t)},parse(e){let t={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return t;let r=e.charCodeAt(0),n=r===47,o;if(n)t.root="/",o=1;else o=0;let s=-1,i=0,a=-1,c=!0,l=e.length-1,u=0;for(;l>=o;--l){if(r=e.charCodeAt(l),r===47){if(!c){i=l+1;break}continue}if(a===-1)c=!1,a=l+1;if(r===46){if(s===-1)s=l;else if(u!==1)u=1}else if(s!==-1)u=-1}if(s===-1||a===-1||u===0||u===1&&s===a-1&&s===i+1){if(a!==-1)if(i===0&&n)t.base=t.name=e.slice(1,a);else t.base=t.name=e.slice(i,a)}else{if(i===0&&n)t.name=e.slice(1,s),t.base=e.slice(1,a);else t.name=e.slice(i,s),t.base=e.slice(i,a);t.ext=e.slice(s,a)}if(i>0)t.dir=e.slice(0,i-1);else if(n)t.dir="/";return t},sep:"/",fromFileUrl:Hke,toFileUrl:qke,toNamespacedPath:Z});var ed=XD,Fo=zP;import*as r0 from"node:child_process";var Gt=(e,t)=>(r,[n])=>{let o="Unknown";switch(r.code){case"ENOENT":o="NotFound";break;case"EACCES":o="PermissionDenied";break;case"EEXIST":o="AlreadyExists";break;case"EISDIR":o="BadResource";break;case"ENOTDIR":o="BadResource";break;case"EBUSY":o="Busy";break;case"ELOOP":o="BadResource";break}return new gl({reason:o,module:e,method:t,pathOrDescriptor:n,syscall:r.syscall,description:r.message,cause:r})};import{Readable as Kke}from"node:stream";var vx=(e,t,r)=>yg(pee(e,t,r)),uee=(e,t)=>{let r=t.maxBytes?Number(t.maxBytes):void 0;return Yu(ge(()=>{let n=e();return n.setEncoding(t.encoding??"utf8"),n}),(n)=>_r((o)=>{let s="",i=0;n.once("error",(a)=>{o(xe(t.onFailure(a)))}),n.once("end",()=>{o(le(s))}),n.on("data",(a)=>{if(s+=a,i+=Buffer.byteLength(a),r&&i>r)o(xe(t.onFailure(Error("maxBytes exceeded"))))})}),(n)=>ge(()=>{if("closed"in n&&!n.closed)n.destroy()}))},Aee=(e,t)=>{let r=t.maxBytes?Number(t.maxBytes):void 0;return Yu(ge(e),(n)=>_r((o)=>{let s=Buffer.alloc(0),i=0;n.once("error",(a)=>{o(xe(t.onFailure(a)))}),n.once("end",()=>{o(le(s))}),n.on("data",(a)=>{if(s=Buffer.concat([s,a]),i+=a.length,r&&i>r)o(xe(t.onFailure(Error("maxBytes exceeded"))))})}),(n)=>ge(()=>{if("closed"in n&&!n.closed)n.destroy()}))};var pee=(e,t,r)=>wP(()=>Xke(e(),t,Xs(void 0),r)),fee=(e,t,{encoding:r,endOnDone:n=!0}={},o=oe)=>{let s=Zke(e,r),i=n?_r((a)=>{if("closed"in e&&e.closed)a(oe);else e.once("finish",()=>a(oe)),e.end()}):oe;return{awaitRead:()=>oe,emit:s,error:(a)=>Ue(i,t(a)),done:(a)=>Ue(i,o)}},Zke=(e,t)=>(r)=>r.length===0?oe:_r((n)=>{let o=r[Symbol.iterator](),s=o.next();function i(){let a=s;s=o.next();let c=e.write(a.value,t);if(s.done)n(oe);else if(c)i();else e.once("drain",i)}i()}),Xke=(e,t,r,n)=>{if(!e.readable)return kx;let o=by(!1);function s(){o.unsafeOpen()}function i(u){r.current=Yc(t(u)),o.unsafeOpen()}function a(){r.current=oi,o.unsafeOpen()}e.on("readable",s),e.on("error",i),e.on("end",a);let c=n?.chunkSize?Number(n.chunkSize):void 0,l=wP(function u(){let A=e.read(c);if(A===null){if(r.current)return g7(r.current);return o.unsafeClose(),lA(o.await,u)}let p=[A];while(!0){if(A=e.read(c),A===null)return lA(OD(Sr(p)),u);p.push(A)}});return m7(l,ge(()=>{if(e.off("readable",s),e.off("error",i),e.off("end",a),n?.closeOnDone!==!1&&"closed"in e&&!e.closed)e.destroy()}))};class dee extends Kke{readLatch;fiber=void 0;constructor(e,t){super({});this.readLatch=by(!1),this.fiber=Ku(e)(this.readLatch.whenOpen(fP(t,(r)=>this.readLatch.whenOpen(ge(()=>{if(r.length===0)return;this.readLatch.unsafeClose();for(let n of r)if(typeof n==="string")this.push(n,"utf8");else this.push(n)}))))),this.fiber.addObserver((r)=>{if(this.fiber=void 0,Im(r))this.push(null);else this.destroy(Hu(r.cause))})}_read(e){this.readLatch.unsafeOpen()}_destroy(e,t){if(!this.fiber)return t(e);Bf(Ds(this.fiber)).addObserver((r)=>{t(r._tag==="Failure"?Hu(r.cause):e)})}}var hee=(e)=>re(tl(),(t)=>new dee(t,e));var t0=(e,t,r)=>$6(mee(e,t,r)),mee=(e,t,r)=>lA(ci(ge(()=>e()),jt()),([n,o])=>bP(tTe(n,o,t),fee(n,(s)=>Wa(o,s),r,uw(o,oe)))),tTe=(e,t,r)=>Me(()=>{function n(o){ii(t,xe(r(o)))}return e.on("error",n),sa(gt(t),ge(()=>{e.removeListener("error",n)}))});var nTe=(e)=>typeof e==="string"?e:"pipe",gee=(e)=>typeof e==="string"?e:"pipe",Lx=(e)=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),dA=(e,t,r)=>{let n=xP(r).reduce((o,s)=>{let i=`${s.command} ${s.args.join(" ")}`;return o.length===0?i:`${o} | ${i}`},"");return Gt("Command",e)(t,[n])},oTe={[IP]:IP,...Cs,toJSON(){return{_id:"@effect/platform/CommandExecutor/Process",pid:this.pid}}},Px=(e)=>(t)=>{switch(t._tag){case"StandardCommand":{let r=T(jt(),(s)=>_r((i)=>{let a=r0.spawn(t.command,t.args,{stdio:[nTe(t.stdin),gee(t.stdout),gee(t.stderr)],cwd:Ve(t.cwd,ih),shell:t.shell,env:{...process.env,...Object.fromEntries(t.env)},detached:process.platform!=="win32"});return a.on("error",(c)=>{i(xe(dA("spawn",c,t)))}),a.on("exit",(...c)=>{ii(s,le(c))}),a.on("spawn",()=>{i(le([a,s]))}),ge(()=>{a.kill("SIGTERM")})})),n=process.platform==="win32"?(s,i)=>_r((a)=>{r0.exec(`taskkill /pid ${s.pid} /T /F`,(c)=>{if(c)a(xe(dA("kill",Lx(c),t)));else a(oe)})}):(s,i)=>Qo({try:()=>process.kill(-s.pid,i),catch:(a)=>dA("kill",Lx(a),t)}),o=(s,i)=>Me(()=>s.kill(i)?oe:xe(dA("kill",new globalThis.Error("Failed to kill process"),t)));return g(Ge(t.cwd,{onNone:()=>oe,onSome:(s)=>e.access(s)}),Ue(br(r,([s,i])=>T(qu(i),(a)=>{if(!a)return n(s,"SIGTERM").pipe(ww(()=>o(s,"SIGTERM")),Ue(gt(i)),Ga);return T(gt(i),([c])=>{if(c!==0&&c!==null)return n(s,"SIGTERM").pipe(Ga);return oe})}))),re(([s,i])=>{let a=J6;if(s.stdin!==null)a=t0(()=>s.stdin,(h)=>dA("toWritable",Lx(h),t));let c=T(gt(i),([h,E])=>{if(h!==null)return le(c7(h));return xe(dA("exitCode",new globalThis.Error(`Process interrupted due to receipt of signal: ${E}`),t))}),l=Y3(qu(i)),u=(h="SIGTERM")=>n(s,h).pipe(ww(()=>o(s,h)),Ue(Va(gt(i)))),A=l7(s.pid),p=vx(()=>s.stderr,(h)=>dA("fromReadable(stderr)",Lx(h),t)),f=vx(()=>s.stdout,(h)=>dA("fromReadable(stdout)",Lx(h),t));if(typeof t.stdout!=="string")f=q6(f,t.stdout);return Object.assign(Object.create(oTe),{pid:A,exitCode:c,isRunning:l,kill:u,stdin:a,stderr:p,stdout:f})}),typeof t.stdin==="string"?Z:Ur((s)=>yf(xg(t.stdin,s.stdin))))}case"PipedCommand":{let r=xP(t);if(r.length===1)return g(r[0],Px(e));let n=r[0],o=r.slice(1),s=o.slice(0,o.length-1),i=o[o.length-1],a=s.reduce((c,l)=>g(bD(l,c),Px(e),re((u)=>u.stdout),rc),g(Px(e)(n),re((c)=>c.stdout),rc));return g(bD(i,a),Px(e))}}},Eee=nl(Dx,g(Ms,re((e)=>u7(Px(e)))));var Cee=Eee;var yee=(e,t,r)=>(...n)=>_r((o)=>{try{e(...n,(s,i)=>{if(s)o(xe(t?t(s,n):s));else o(le(i))})}catch(s){o(r?xe(r(s,n)):Ko(s))}});var gr=yee;import*as xee from"node:crypto";import*as Te from"node:fs";import*as Iee from"node:os";import*as wg from"node:path";var cr=(e)=>(t)=>new Oo({module:"FileSystem",method:e,cause:t}),cTe=(()=>{let e=gr(Te.access,Gt("FileSystem","access"),cr("access"));return(t,r)=>{let n=Te.constants.F_OK;if(r?.readable)n|=Te.constants.R_OK;if(r?.writable)n|=Te.constants.W_OK;return e(t,n)}})(),lTe=(()=>{let e=gr(Te.cp,Gt("FileSystem","copy"),cr("copy"));return(t,r,n)=>e(t,r,{force:n?.overwrite??!1,preserveTimestamps:n?.preserveTimestamps??!1,recursive:!0})})(),uTe=(()=>{let e=gr(Te.copyFile,Gt("FileSystem","copyFile"),cr("copyFile"));return(t,r)=>e(t,r)})(),ATe=(()=>{let e=gr(Te.chmod,Gt("FileSystem","chmod"),cr("chmod"));return(t,r)=>e(t,r)})(),pTe=(()=>{let e=gr(Te.chown,Gt("FileSystem","chown"),cr("chown"));return(t,r,n)=>e(t,r,n)})(),fTe=(()=>{let e=gr(Te.link,Gt("FileSystem","link"),cr("link"));return(t,r)=>e(t,r)})(),dTe=(()=>{let e=gr(Te.mkdir,Gt("FileSystem","makeDirectory"),cr("makeDirectory"));return(t,r)=>e(t,{recursive:r?.recursive??!1,mode:r?.mode})})(),jP=(e)=>{let t=gr(Te.mkdtemp,Gt("FileSystem",e),cr(e));return(r)=>Me(()=>{let n=r?.prefix??"",o=typeof r?.directory==="string"?wg.join(r.directory,"."):Iee.tmpdir();return t(n?wg.join(o,n):o+"/")})},hTe=jP("makeTempDirectory"),$P=(e)=>{let t=gr(Te.rm,Gt("FileSystem",e),cr(e));return(r,n)=>t(r,{recursive:n?.recursive??!1,force:n?.force??!1})},mTe=$P("remove"),gTe=(()=>{let e=jP("makeTempDirectoryScoped"),t=$P("makeTempDirectoryScoped");return(r)=>br(e(r),(n)=>pn(t(n,{recursive:!0})))})(),See=(e)=>{let t=gr(Te.open,Gt("FileSystem",e),cr(e)),r=gr(Te.close,Gt("FileSystem",e),cr(e));return(n,o)=>g(br(t(n,o?.flag??"r",o?.mode),(s)=>pn(r(s))),re((s)=>CTe(y7(s),o?.flag?.startsWith("a")??!1)))},ETe=See("open"),CTe=(()=>{let e=(u)=>gr(Te.read,Gt("FileSystem",u),cr(u)),t=e("read"),r=e("readAlloc"),n=gr(Te.fstat,Gt("FileSystem","stat"),cr("stat")),o=gr(Te.ftruncate,Gt("FileSystem","truncate"),cr("truncate")),s=gr(Te.fsync,Gt("FileSystem","sync"),cr("sync")),i=(u)=>gr(Te.write,Gt("FileSystem",u),cr(u)),a=i("write"),c=i("writeAll");class l{fd;append;[ND];semaphore=J3(1);position=0n;constructor(u,A){this.fd=u,this.append=A,this[ND]=ND}get stat(){return re(n(this.fd),Qee)}get sync(){return s(this.fd)}seek(u,A){let p=Sg(u);return this.semaphore.withPermits(1)(ge(()=>{if(A==="start")this.position=p;else if(A==="current")this.position=this.position+p;return this.position}))}read(u){return this.semaphore.withPermits(1)(re(Me(()=>t(this.fd,{buffer:u,position:this.position})),(A)=>{let p=Sg(A);return this.position=this.position+p,p}))}readAlloc(u){let A=Number(u);return this.semaphore.withPermits(1)(T(ge(()=>Buffer.allocUnsafeSlow(A)),(p)=>re(r(this.fd,{buffer:p,position:this.position}),(f)=>{if(f===0)return U();if(this.position=this.position+BigInt(f),f===A)return W(p);let h=Buffer.allocUnsafeSlow(f);return p.copy(h,0,0,f),W(h)})))}truncate(u){return this.semaphore.withPermits(1)(re(o(this.fd,u?Number(u):void 0),()=>{if(!this.append){let A=BigInt(u??0);if(this.position>A)this.position=A}}))}write(u){return this.semaphore.withPermits(1)(re(Me(()=>a(this.fd,u,void 0,void 0,this.append?void 0:Number(this.position))),(A)=>{let p=Sg(A);if(!this.append)this.position=this.position+p;return p}))}writeAllChunk(u){return T(Me(()=>c(this.fd,u,void 0,void 0,this.append?void 0:Number(this.position))),(A)=>{if(A===0)return xe(new gl({module:"FileSystem",method:"writeAll",reason:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}));if(!this.append)this.position=this.position+BigInt(A);return A<u.length?this.writeAllChunk(u.subarray(A)):oe})}writeAll(u){return this.semaphore.withPermits(1)(this.writeAllChunk(u))}}return(u,A)=>new l(u,A)})(),Bee=(e)=>{let t=jP(e),r=See(e),n=(o)=>ge(()=>xee.randomBytes(o).toString("hex"));return(o)=>g(ci(t(o),n(6)),re(([s,i])=>wg.join(s,i+(o?.suffix??""))),Ur((s)=>wo(r(s,{flag:"w+"}))))},yTe=Bee("makeTempFile"),xTe=(()=>{let e=Bee("makeTempFileScoped"),t=$P("makeTempFileScoped");return(r)=>br(e(r),(n)=>pn(t(wg.dirname(n),{recursive:!0})))})(),ITe=(e,t)=>Zo({try:()=>Te.promises.readdir(e,t),catch:(r)=>Gt("FileSystem","readDirectory")(r,[e])}),STe=(e)=>_r((t,r)=>{try{Te.readFile(e,{signal:r},(n,o)=>{if(n)t(xe(Gt("FileSystem","readFile")(n,[e])));else t(le(o))})}catch(n){t(xe(cr("readFile")(n)))}}),BTe=(()=>{let e=gr(Te.readlink,Gt("FileSystem","readLink"),cr("readLink"));return(t)=>e(t)})(),QTe=(()=>{let e=gr(Te.realpath,Gt("FileSystem","realPath"),cr("realPath"));return(t)=>e(t)})(),bTe=(()=>{let e=gr(Te.rename,Gt("FileSystem","rename"),cr("rename"));return(t,r)=>e(t,r)})(),Qee=(e)=>({type:e.isFile()?"File":e.isDirectory()?"Directory":e.isSymbolicLink()?"SymbolicLink":e.isBlockDevice()?"BlockDevice":e.isCharacterDevice()?"CharacterDevice":e.isFIFO()?"FIFO":e.isSocket()?"Socket":"Unknown",mtime:st(e.mtime),atime:st(e.atime),birthtime:st(e.birthtime),dev:e.dev,rdev:st(e.rdev),ino:st(e.ino),mode:e.mode,nlink:st(e.nlink),uid:st(e.uid),gid:st(e.gid),size:Sg(e.size),blksize:Xt(st(e.blksize),Sg),blocks:st(e.blocks)}),KP=(()=>{let e=gr(Te.stat,Gt("FileSystem","stat"),cr("stat"));return(t)=>re(e(t),Qee)})(),wTe=(()=>{let e=gr(Te.symlink,Gt("FileSystem","symlink"),cr("symlink"));return(t,r)=>e(t,r)})(),RTe=(()=>{let e=gr(Te.truncate,Gt("FileSystem","truncate"),cr("truncate"));return(t,r)=>e(t,r!==void 0?Number(r):void 0)})(),DTe=(()=>{let e=gr(Te.utimes,Gt("FileSystem","utime"),cr("utime"));return(t,r,n)=>e(t,r,n)})(),kTe=(e,t)=>F6((r)=>br(ge(()=>{let n=Te.watch(e,{recursive:t?.recursive},(o,s)=>{if(!s)return;switch(o){case"rename":{r.fromEffect(Ju(KP(s),{onSuccess:(i)=>le(x7({path:s})),onFailure:(i)=>i._tag==="SystemError"&&i.reason==="NotFound"?le(S7({path:s})):xe(i)}));return}case"change":{r.single(I7({path:s}));return}}});return n.on("error",(o)=>{r.fail(new gl({module:"FileSystem",reason:"Unknown",method:"watch",pathOrDescriptor:e,cause:o}))}),n.on("close",()=>{r.end()}),n}),(n)=>ge(()=>n.close()))),TTe=(e,t,r)=>KP(t).pipe(re((n)=>e.pipe(an((o)=>o.register(t,n,r)),Ve(()=>kTe(t,r)))),G6),OTe=(e,t,r)=>_r((n,o)=>{try{Te.writeFile(e,t,{signal:o,flag:r?.flag,mode:r?.mode},(s)=>{if(s)n(xe(Gt("FileSystem","writeFile")(s,[e])));else n(oe)})}catch(s){n(xe(cr("writeFile")(s)))}}),FTe=re(xy(DP),(e)=>C7({access:cTe,chmod:ATe,chown:pTe,copy:lTe,copyFile:uTe,link:fTe,makeDirectory:dTe,makeTempDirectory:hTe,makeTempDirectoryScoped:gTe,makeTempFile:yTe,makeTempFileScoped:xTe,open:ETe,readDirectory:ITe,readFile:STe,readLink:BTe,realPath:QTe,remove:mTe,rename:bTe,stat:KP,symlink:wTe,truncate:RTe,utimes:DTe,watch(t,r){return TTe(e,t,r)},writeFile:OTe})),bee=nl(Ms,FTe);var n0=bee;import*as Hx from"node:path";import*as o0 from"node:url";var ZP=(e)=>Qo({try:()=>o0.fileURLToPath(e),catch:(t)=>new Oo({module:"Path",method:"fromFileUrl",description:`Invalid file URL: ${e}`,cause:t})}),XP=(e)=>Qo({try:()=>o0.pathToFileURL(e),catch:(t)=>new Oo({module:"Path",method:"toFileUrl",description:`Invalid path: ${e}`,cause:t})}),MTe=ol(Fo,Fo.of({[ed]:ed,...Hx.posix,fromFileUrl:ZP,toFileUrl:XP})),_Te=ol(Fo,Fo.of({[ed]:ed,...Hx.win32,fromFileUrl:ZP,toFileUrl:XP})),Ree=ol(Fo,Fo.of({[ed]:ed,...Hx,fromFileUrl:ZP,toFileUrl:XP}));var s0=Ree;var kee=dt("@effect/platform/Terminal");var eH=kee;var c0=Symbol.for("effect/Mailbox"),tH=Symbol.for("effect/Mailbox/ReadonlyMailbox");var td=Ot(),Tee=mt(td),i0=mt(!1),a0=mt(!0),Oee=[td,!0];class Fee extends Vo{scheduler;capacity;strategy;[c0]=c0;[tH]=tH;state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};messages=[];messagesChunk=Ot();constructor(e,t,r){super();this.scheduler=e,this.capacity=t,this.strategy=r}offer(e){return De(()=>{if(this.state._tag!=="Open")return i0;else if(this.messages.length+this.messagesChunk.length>=this.capacity)switch(this.strategy){case"dropping":return i0;case"suspend":if(this.capacity<=0&&this.state.takers.size>0)return this.messages.push(e),this.releaseTaker(),a0;return this.offerRemainingSingle(e);case"sliding":return this.unsafeTake(),this.messages.push(e),a0}return this.messages.push(e),this.scheduleReleaseTaker(),a0})}unsafeOffer(e){if(this.state._tag!=="Open")return!1;else if(this.messages.length+this.messagesChunk.length>=this.capacity){if(this.strategy==="sliding")return this.unsafeTake(),this.messages.push(e),!0;else if(this.capacity<=0&&this.state.takers.size>0)return this.messages.push(e),this.releaseTaker(),!0;return!1}return this.messages.push(e),this.scheduleReleaseTaker(),!0}offerAll(e){return De(()=>{if(this.state._tag!=="Open")return X(Fn(e));let t=this.unsafeOfferAllArray(e);if(t.length===0)return Tee;else if(this.strategy==="dropping")return X(Sr(t));return this.offerRemainingArray(t)})}unsafeOfferAll(e){return Sr(this.unsafeOfferAllArray(e))}unsafeOfferAllArray(e){if(this.state._tag!=="Open")return et(e);else if(this.capacity===Number.POSITIVE_INFINITY||this.strategy==="sliding"){if(this.messages.length>0)this.messagesChunk=Wt(this.messagesChunk,Sr(this.messages));if(this.strategy==="sliding")this.messagesChunk=this.messagesChunk.pipe(Wt(Fn(e)),uF(this.capacity));else if(Sp(e))this.messagesChunk=Wt(this.messagesChunk,e);else this.messages=et(e);return this.scheduleReleaseTaker(),[]}let t=this.capacity<=0?this.state.takers.size:this.capacity-this.messages.length-this.messagesChunk.length;if(t===0)return et(e);let r=[],n=0;for(let o of e){if(n<t)this.messages.push(o);else r.push(o);n++}return this.scheduleReleaseTaker(),r}fail(e){return this.done(Wc(e))}failCause(e){return this.done(lt(e))}unsafeDone(e){if(this.state._tag!=="Open")return!1;else if(this.state.offers.size===0&&this.messages.length===0&&this.messagesChunk.length===0)return this.finalize(e),!0;return this.state={...this.state,_tag:"Closing",exit:e},!0}shutdown=V(()=>{if(this.state._tag==="Done")return!0;this.messages=[],this.messagesChunk=td;let e=this.state.offers;if(this.finalize(this.state._tag==="Open"?fr:this.state.exit),e.size>0){for(let t of e)if(t._tag==="Single")t.resume(i0);else t.resume(mt(Sr(t.remaining.slice(t.offset))));e.clear()}return!0});done(e){return V(()=>this.unsafeDone(e))}end=this.done(fr);clear=De(()=>{if(this.state._tag==="Done")return Zh(this.state.exit,td);let e=this.unsafeTakeAll();return this.releaseCapacity(),X(e)});takeAll=De(()=>{if(this.state._tag==="Done")return Zh(this.state.exit,Oee);let e=this.unsafeTakeAll();if(e.length===0)return ht(this.awaitTake,this.takeAll);return X([e,this.releaseCapacity()])});takeN(e){return De(()=>{if(this.state._tag==="Done")return Zh(this.state.exit,Oee);else if(e<=0)return X([td,!1]);e=Math.min(e,this.capacity);let t;if(e<=this.messagesChunk.length)t=yh(this.messagesChunk,e),this.messagesChunk=Wi(this.messagesChunk,e);else if(e<=this.messages.length+this.messagesChunk.length)this.messagesChunk=Wt(this.messagesChunk,Sr(this.messages)),this.messages=[],t=yh(this.messagesChunk,e),this.messagesChunk=Wi(this.messagesChunk,e);else return ht(this.awaitTake,this.takeN(e));return X([t,this.releaseCapacity()])})}unsafeTake(){if(this.state._tag==="Done")return OQ(this.state.exit,Wc(new y4));let e;if(this.messagesChunk.length>0)e=oC(this.messagesChunk),this.messagesChunk=Wi(this.messagesChunk,1);else if(this.messages.length>0)e=this.messages[0],this.messagesChunk=Wi(Sr(this.messages),1),this.messages=[];else if(this.capacity<=0&&this.state.offers.size>0)return this.capacity=1,this.releaseCapacity(),this.capacity=0,this.messages.length>0?mt(this.messages.pop()):void 0;else return;return this.releaseCapacity(),mt(e)}take=De(()=>this.unsafeTake()??ht(this.awaitTake,this.take));await=ka((e)=>{if(this.state._tag==="Done")return e(this.state.exit);return this.state.awaiters.add(e),V(()=>{if(this.state._tag!=="Done")this.state.awaiters.delete(e)})});unsafeSize(){let e=this.messages.length+this.messagesChunk.length;return this.state._tag==="Done"?U():W(e)}size=V(()=>this.unsafeSize());commit(){return this.takeAll}pipe(){return v(this,arguments)}toJSON(){return{_id:"effect/Mailbox",state:this.state._tag,size:this.unsafeSize().toJSON()}}toString(){return je(this)}[Re](){return je(this)}offerRemainingSingle(e){return ka((t)=>{if(this.state._tag!=="Open")return t(i0);let r={_tag:"Single",message:e,resume:t};return this.state.offers.add(r),V(()=>{if(this.state._tag==="Open")this.state.offers.delete(r)})})}offerRemainingArray(e){return ka((t)=>{if(this.state._tag!=="Open")return t(mt(Sr(e)));let r={_tag:"Array",remaining:e,offset:0,resume:t};return this.state.offers.add(r),V(()=>{if(this.state._tag==="Open")this.state.offers.delete(r)})})}releaseCapacity(){if(this.state._tag==="Done")return this.state.exit._tag==="Success";else if(this.state.offers.size===0){if(this.state._tag==="Closing"&&this.messages.length===0&&this.messagesChunk.length===0)return this.finalize(this.state.exit),this.state.exit._tag==="Success";return!1}let e=this.capacity-this.messages.length-this.messagesChunk.length;for(let t of this.state.offers)if(e===0)return!1;else if(t._tag==="Single")this.messages.push(t.message),e--,t.resume(a0),this.state.offers.delete(t);else{for(;t.offset<t.remaining.length;t.offset++){if(e===0)return!1;this.messages.push(t.remaining[t.offset]),e--}t.resume(Tee),this.state.offers.delete(t)}return!1}awaitTake=ka((e)=>{if(this.state._tag==="Done")return e(this.state.exit);return this.state.takers.add(e),V(()=>{if(this.state._tag!=="Done")this.state.takers.delete(e)})});scheduleRunning=!1;scheduleReleaseTaker(){if(this.scheduleRunning)return;this.scheduleRunning=!0,this.scheduler.scheduleTask(this.releaseTaker,0)}releaseTaker=()=>{if(this.scheduleRunning=!1,this.state._tag==="Done")return;else if(this.state.takers.size===0)return;for(let e of this.state.takers)if(this.state.takers.delete(e),e(fr),this.messages.length+this.messagesChunk.length===0)break};unsafeTakeAll(){if(this.messagesChunk.length>0){let e=this.messages.length>0?Wt(this.messagesChunk,Sr(this.messages)):this.messagesChunk;return this.messagesChunk=td,this.messages=[],e}else if(this.messages.length>0){let e=Sr(this.messages);return this.messages=[],e}else if(this.state._tag!=="Done"&&this.state.offers.size>0)return this.capacity=1,this.releaseCapacity(),this.capacity=0,nt(this.messages.pop());return td}finalize(e){if(this.state._tag==="Done")return;let t=this.state;this.state={_tag:"Done",exit:e};for(let r of t.takers)r(e);t.takers.clear();for(let r of t.awaiters)r(e);t.awaiters.clear()}}var Nee=(e)=>Ke((t)=>X(new Fee(t.currentScheduler,typeof e==="number"?e:e?.capacity??Number.POSITIVE_INFINITY,typeof e==="number"?"suspend":e?.strategy??"suspend")));var rH=(e)=>{let t=Je(e.takeAll,([r,n])=>n?r.length===0?kn:ut(r):ml(ut(r),t));return t},Mee=(e)=>xD(rH(e));var HTe=c0;var _ee=(e)=>te(e,HTe);var hA=Nee;var Uee=rH,vee=Mee;import*as u0 from"node:readline";var Lee=(e)=>e.key.ctrl&&(e.key.name==="c"||e.key.name==="d"),Pee=tr(function*(e=Lee){let t=process.stdin,r=process.stdout,n=yield*W8({acquire:br(ge(()=>{let u=u0.createInterface({input:t,escapeCodeTimeout:50});if(u0.emitKeypressEvents(t,u),t.isTTY)t.setRawMode(!0);return u}),(u)=>ge(()=>{if(t.isTTY)t.setRawMode(!1);u.close()}))}),o=ge(()=>r.columns??0),s=ge(()=>r.rows??0),i=ge(()=>Boolean(r.isTTY)),a=Ze(function*(){yield*eP(n);let u=yield*hA(),A=(p,f)=>{let h={input:st(p),key:{name:f.name??"",ctrl:!!f.ctrl,meta:!!f.meta,shift:!!f.shift}};if(u.unsafeOffer(h),e(h))u.unsafeDone(oi)};return yield*Ew(()=>ge(()=>t.off("keypress",A))),t.on("keypress",A),u}),c=eP(n).pipe(T((u)=>_r((A)=>{let p=(f)=>A(le(f));return u.once("line",p),ge(()=>u.off("line",p))})),wo),l=(u)=>Ya(_r((A)=>{r.write(u,(p)=>p?A(xe(new Oo({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:p}))):A(oe))}));return eH.of({columns:o,rows:s,isTTY:i,readInput:a,readLine:c,display:l})}),Hee=zu(eH,Pee(Lee));var Wee=Hee;class A0 extends ba("@effect/platform/Transferable/Collector")(){}var qee=()=>{let e=[],t=(o)=>{e.push(...o)},r=()=>e,n=()=>{let o=e;return e=[],o};return A0.of({unsafeAddAll:t,addAll:(o)=>ge(()=>t(o)),unsafeRead:r,read:ge(r),unsafeClear:n,clear:ge(n)})};var Gee=Symbol.for("@effect/platform/WorkerError");var Yee=Gee;class xl extends at()("WorkerError",{reason:N("spawn","decode","send","unknown","encode"),cause:Pt}){[Yee]=Yee;static Cause=NX({error:this,defect:Pt});static encodeCause=cR(this.Cause);static decodeCause=$v(this.Cause);get message(){switch(this.reason){case"send":return"An error occurred calling .postMessage";case"spawn":return"An error occurred while spawning a worker";case"decode":return"An error occurred during decoding";case"encode":return"An error occurred during encoding";case"unknown":return"An unexpected error occurred"}}}var nH=Symbol.for("@effect/platform/Worker/PlatformWorker"),p0=dt("@effect/platform/Worker/PlatformWorker"),oH=Symbol.for("@effect/platform/Worker/WorkerManager"),sH=dt("@effect/platform/Worker/WorkerManager"),Vee=dt("@effect/platform/Worker/Spawner"),Jee=Ze(function*(){let e=yield*p0,t=0;return sH.of({[oH]:oH,spawn({encode:r,initialMessage:n}){return Ze(function*(){let o=t++,s=0,i=new Map,a=qee(),c=r?(x)=>Ue(a.clear,es(r(x),A0,a)):le,l=yield*jt(),u=yield*e.spawn(o);yield*u.run((x)=>{if(x[0]===0)return uw(l,oe);return A(x[1])}).pipe(Cy((x)=>$t(i.values(),(y)=>(Wu in y)?Wa(y,x):y.failCause(x))),If(Ja),Ey(ov(1000)),el({package:"@effect/platform",module:"Worker"}),wn,xf),yield*Ew(()=>Ue($t(i.values(),(x)=>(Wu in x)?TU(x):x.end,{discard:!0}),ge(()=>i.clear())));let A=(x)=>Me(()=>{let y=i.get(x[0]);if(!y)return oe;switch(x[1]){case 0:return Wu in y?_n(y,x[2][0]):y.offerAll(x[2]);case 1:{if(x.length===2)return Wu in y?TU(y):y.end;return Wu in y?_n(y,x[2][0]):Ue(y.offerAll(x[2]),y.end)}case 2:case 3:{if(x[1]===2)return Wu in y?kU(y,x[2]):y.fail(x[2]);let I=xl.decodeCause(x[2]);return Wu in y?Wa(y,I):y.failCause(I)}}}),p=(x,y)=>oa((I)=>{let S=I.getFiberRef(Ty),b=yo(S,n$).pipe(xs((D)=>D._tag==="Span")),R=s++;return y.pipe(Ur((D)=>(i.set(R,D),c(x).pipe(Ur((q)=>u.send([R,0,q,b._tag==="Some"?[b.value.traceId,b.value.spanId,b.value.sampled]:void 0],a.unsafeRead())),ao((q)=>_ee(D)?D.failCause(q):Wa(D,q))))),re((D)=>({id:R,mailbox:D})))}),f=({id:x},y)=>{let I=ge(()=>i.delete(x));return Jo(y)?Ue(pn(u.send([x,1])),I):I},h=(x)=>yg(h7(p(x,hA()),({mailbox:y})=>Uee(y),f)),E=(x)=>Yu(p(x,jt()),({mailbox:y})=>gt(y),f);if(yield*gt(l),n)yield*ge(n).pipe(T(E),_e((x)=>new xl({reason:"spawn",cause:x})));return{id:o,execute:h,executeEffect:E}})}})}),zee=nl(sH,Jee);var jee=()=>(e)=>p0.of({[nH]:nH,spawn(t){return Ze(function*(){let r=yield*Vee,n,o=[];return{run:(a)=>Zc((c)=>Ze(function*(){let l=yield*yy,u=yield*e.setup({worker:r(t),scope:l});n=u,yield*na(l,ge(()=>{n=void 0}));let A=(yield*tl()).pipe(p5(kV(sy))),p=yield*$U(),f=Ku(A);if(yield*e.listen({port:u,scope:l,emit(h){KU(p,f(a(h)))},deferred:p.deferred}),o.length>0){for(let[h,E]of o)u.postMessage([0,h],E);o.length=0}return yield*c(m5(p))}).pipe(wo)),send:(a,c)=>Qo({try:()=>{if(n===void 0)o.push([a,c]);else n.postMessage([0,a],c)},catch:(l)=>new xl({reason:"send",cause:l})})}})}});var $ee=jee,Kee=p0;var Zee=zee;var zTe=$ee()({setup({scope:e,worker:t}){return T(jt(),(r)=>{let n="postMessage"in t?{postMessage(o,s){t.postMessage(o,s)},kill:()=>t.terminate(),worker:t}:{postMessage(o,s){t.send(o)},kill:()=>t.kill("SIGKILL"),worker:t};return t.on("exit",()=>{ii(r,oi)}),bo(na(e,Me(()=>(n.postMessage([1]),gt(r))).pipe(wn,Vu(5000),ao(()=>ge(()=>n.kill())))),n)})},listen({deferred:e,emit:t,port:r}){return r.worker.on("message",(n)=>{t(n)}),r.worker.on("messageerror",(n)=>{ii(e,new xl({reason:"decode",cause:n}))}),r.worker.on("error",(n)=>{ii(e,new xl({reason:"unknown",cause:n}))}),r.worker.on("exit",(n)=>{ii(e,new xl({reason:"unknown",cause:Error(`exited with code ${n}`)}))}),oe}}),Xee=ol(Kee,zTe),ete=rs(Zee,Xee);var tte=ete;var KTe=g(kw(s0,Cee,Wee,tte),HU(n0));var iH=n0;import*as d0 from"node:http";import*as h0 from"node:https";import{Readable as lte}from"node:stream";import{pipeline as XTe}from"node:stream/promises";var ote=t0;var f0=vx;var ste=hee;var ite=uee,ate=Aee;class aH extends JE{source;onError;remoteAddressOverride;[ma];constructor(e,t,r){super();this.source=e,this.onError=t,this.remoteAddressOverride=r,this[ma]=ma}get headers(){return Kf(this.source.headers)}get remoteAddress(){return st(this.remoteAddressOverride??this.source.socket.remoteAddress)}textEffect;get text(){if(this.textEffect)return this.textEffect;return this.textEffect=ts(Hm(T(LD,(e)=>ite(()=>this.source,{onFailure:this.onError,maxBytes:Bt(e)})))),this.textEffect}get unsafeText(){return ts(this.text)}get json(){return Wm(this.text,{try:(e)=>e===""?null:JSON.parse(e),catch:this.onError})}get unsafeJson(){return ts(this.json)}get urlParamsBody(){return T(this.text,(e)=>Qo({try:()=>uA(new URLSearchParams(e)),catch:this.onError}))}get stream(){return f0(()=>this.source,this.onError)}get arrayBuffer(){return T(LD,(e)=>ate(()=>this.source,{onFailure:this.onError,maxBytes:Bt(e)}))}}var cH=Symbol.for("@effect/platform-node/Http/NodeClient/HttpAgent"),lH=dt("@effect/platform-node/Http/NodeClient/HttpAgent"),ute=(e)=>re(Gu([br(ge(()=>new d0.Agent(e)),(t)=>ge(()=>t.destroy())),br(ge(()=>new h0.Agent(e)),(t)=>ge(()=>t.destroy()))]),([t,r])=>({[cH]:cH,http:t,https:r})),Ate=(e)=>zu(lH,ute(e)),pte=Ate(),eOe=(e)=>zD((t,r,n)=>{let o=r.protocol==="https:"?h0.request(r,{agent:e.https,method:t.method,headers:t.headers,signal:n}):d0.request(r,{agent:e.http,method:t.method,headers:t.headers,signal:n});return g(Ue(tOe(o,t,t.body),rOe(o,t),{concurrent:!0}),re((s)=>new fte(t,s)))}),tOe=(e,t,r)=>Me(()=>{switch(r._tag){case"Empty":return e.end(),cte(e,t);case"Uint8Array":case"Raw":return e.end(r.body),cte(e,t);case"FormData":{let n=new Response(r.formData);return n.headers.forEach((o,s)=>{e.setHeader(s,o)}),Zo({try:()=>XTe(lte.fromWeb(n.body),e),catch:(o)=>new ha({request:t,reason:"Transport",cause:o})})}case"Stream":return xg(L6(r.stream,(n)=>new ha({request:t,reason:"Encode",cause:n})),ote(()=>e,(n)=>new ha({request:t,reason:"Transport",cause:n})))}}),rOe=(e,t)=>_r((r)=>{function n(s){r(xe(new ha({request:t,reason:"Transport",cause:s})))}e.on("error",n);function o(s){e.off("error",n),r(le(s))}return e.on("upgrade",o),e.on("response",o),ge(()=>{e.off("error",n),e.off("upgrade",o),e.off("response",o)})}),cte=(e,t)=>_r((r)=>{function n(s){r(xe(new ha({request:t,reason:"Transport",cause:s})))}e.once("error",n);function o(){e.off("error",n),r(oe)}return e.once("finish",o),ge(()=>{e.off("error",n),e.off("finish",o)})});class fte extends aH{request;[pA];constructor(e,t){super(t,(r)=>new is({request:e,response:this,reason:"Decode",cause:r}));this.request=e,this[pA]=pA}get status(){return this.source.statusCode}cachedCookies;get cookies(){if(this.cachedCookies!==void 0)return this.cachedCookies;let e=this.source.headers["set-cookie"];if(Array.isArray(e))return this.cachedCookies=DD(e);return this.cachedCookies=kD}get formData(){return Zo({try:()=>{let e={headers:new globalThis.Headers(this.source.headers)};if(this.source.statusCode)e.status=this.source.statusCode;if(this.source.statusMessage)e.statusText=this.source.statusMessage;return new Response(lte.toWeb(this.source),e).formData()},catch:this.onError})}toJSON(){return PD(this,{_id:"@effect/platform/HttpClientResponse",request:this.request.toJSON(),status:this.status})}}var dte=re(lH,eOe),hte=$D(dte),mte=rs(hte,pte);var $pe=DO(MW(),1);RO(Yd,DO(MW(),1));var _W=dt("@effect/platform-node/NodeHttpClient/Dispatcher");var Kpe="@effect/platform-node/NodeHttpClient/undiciOptions",Zpe=(e)=>zD((t,r,n,o)=>{let i=o.getFiberRef(Ty).unsafeMap.get(Kpe)??{};return FJe(t.body).pipe(T((a)=>Zo({try:()=>e.request({...i,signal:n,method:t.method,headers:t.headers,origin:r.origin,path:r.pathname+r.search+r.hash,body:a,headersTimeout:3600000,bodyTimeout:0}),catch:(c)=>new ha({request:t,reason:"Transport",cause:c})})),re((a)=>new Xpe(t,a)))});function FJe(e){switch(e._tag){case"Empty":return le(null);case"Uint8Array":case"Raw":return le(e.body);case"FormData":return le(e.formData);case"Stream":return ste(e.stream)}}function NJe(e){}class Xpe extends JE{request;source;[ma];[pA];constructor(e,t){super();this.request=e,this.source=t,this[ma]=ma,this[pA]=pA,t.body.on("error",NJe)}get status(){return this.source.statusCode}get statusText(){return}cachedCookies;get cookies(){if(this.cachedCookies!==void 0)return this.cachedCookies;let e=this.source.headers["set-cookie"];if(e!==void 0)return this.cachedCookies=DD(Array.isArray(e)?e:[e]);return this.cachedCookies=kD}get headers(){return Kf(this.source.headers)}get remoteAddress(){return U()}get stream(){return f0(()=>this.source.body,(e)=>new is({request:this.request,response:this,reason:"Decode",cause:e}))}get json(){return Wm(this.text,{try:(e)=>e===""?null:JSON.parse(e),catch:(e)=>new is({request:this.request,response:this,reason:"Decode",cause:e})})}textBody;get text(){return this.textBody??=Zo({try:()=>this.source.body.text(),catch:(e)=>new is({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Hm,ts)}get urlParamsBody(){return T(this.text,(e)=>Qo({try:()=>uA(new URLSearchParams(e)),catch:(t)=>new is({request:this.request,response:this,reason:"Decode",cause:t})}))}formDataBody;get formData(){return this.formDataBody??=Zo({try:()=>this.source.body.formData(),catch:(e)=>new is({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Hm,ts)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody??=Zo({try:()=>this.source.body.arrayBuffer(),catch:(e)=>new is({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Hm,ts)}toJSON(){return PD(this,{_id:"@effect/platform/HttpClientResponse",request:this.request.toJSON(),status:this.status})}}var efe=$D(re(_W,Zpe));var _Je=mte;var UJe=_W;var vJe=efe;var vW=s0;var rfe=new URL("../",import.meta.url),nfe=new URL("skills/expandai/",rfe),uwt=new URL("assets/opencode/expandai-webfetch.js",rfe);class LJe extends at()("McpParseError",{path:m,error:Pt}){get message(){return`Failed to parse MCP config at ${this.path}: ${je(this.error)}`}}class PJe extends at()("McpWriteError",{path:m,error:Pt}){get message(){return`Failed to write MCP config at ${this.path}: ${je(this.error)}`}}var HJe=N("claude-code","cursor","opencode","codex","fx"),ife=N(...HJe.literals,"unknown"),mwt=N("project","global"),sT=hn({key:m,value:bt}),gwt=Aa(B({mcpServers:C(sT,{default:()=>({})})},sT),{space:2}),Ewt=Aa(B({mcp:C(sT,{default:()=>({})})},sT),{space:2}),afe="expandai",WJe={command:"expandai",args:[]},qJe={command:"npx",args:["-y","expandai"]};var ofe=Ze(function*(){let e=yield*Ms,t=yield*Fo,r=yield*Bo("PATH").pipe(rf("")),n=yield*Bo("PATHEXT").pipe(rf(".COM;.EXE;.BAT;.CMD")),o=t.sep==="\\",s=o?["",...nC(n.split(";"),CU)]:[""];return{resolve:Pe("CliInvocation.resolve")(function*(){let a=nC(r.split(o?";":":"),CU);return(yield*G3(a,(l)=>G3(s,(u)=>e.exists(t.join(l.replace(/^"(.*)"$/u,"$1"),`expandai${u}`)).pipe(By(()=>!1)))))?WJe:qJe})}});class LW extends za()("@expandai/cli/Install/CliInvocation",{dependencies:[iH,vW],effect:ofe}){static layer=nl(LW,ofe.pipe(re(LW.make)))}var GJe=Pe(function*(e){let t=yield*Ms;if(!(yield*t.exists(e)))return"{}";return yield*t.readFileString(e)}),sfe=Pe(function*(e,t){let r=yield*Ms,n=yield*Fo;yield*r.makeDirectory(n.dirname(e),{recursive:!0}),yield*r.writeFileString(e,`${t}
175
- `)});class YJe extends za()("@expandai/cli/Install/ConfigIo",{dependencies:[iH,vW],effect:Ze(function*(){let e=yield*Ms,t=yield*Fo,r=Pe("ConfigIo.read")(function*(a,c){let l=yield*GJe(a).pipe(es(Ms,e));return yield*fR(c)(l)}),n=Pe("ConfigIo.write")(function*(a,c,l){let u=yield*Wf(l)(c);yield*sfe(a,u).pipe(es(Ms,e),es(Fo,t))}),o=Pe("ConfigIo.exists")(function*(a){return yield*e.exists(a)}),s=Pe("ConfigIo.readText")(function*(a){return(yield*e.exists(a))?yield*e.readFileString(a):""}),i=Pe("ConfigIo.writeText")(function*(a,c){yield*sfe(a,c).pipe(es(Ms,e),es(Fo,t))});return{read:r,write:n,exists:o,readText:s,writeText:i}})}){}class VJe extends za()("@expandai/cli/Install/SkillIo",{dependencies:[iH,vW],effect:Ze(function*(){let e=yield*Ms,t=yield*Fo,r=yield*t.fromFileUrl(nfe),n=Pe("SkillIo.install")(function*(a){return yield*e.makeDirectory(t.dirname(a),{recursive:!0}),yield*e.copy(r,a,{overwrite:!0}),a}),o=Pe("SkillIo.uninstall")(function*(a){if(yield*e.exists(a))yield*e.remove(a,{recursive:!0});return a}),s=Pe("SkillIo.isCurrent")(function*(a){let c=t.join(a,"SKILL.md");if(!(yield*e.exists(c)))return!1;let[l,u]=yield*Gu([e.readFileString(c),e.readFileString(t.join(r,"SKILL.md"))]);return l===u}),i=Pe("SkillIo.isInstalled")(function*(a){return yield*e.exists(t.join(a,"SKILL.md"))});return{install:n,uninstall:o,isCurrent:s,isInstalled:i}})}){}var XI="0.1.1";var cfe=Symbol.for("effect/PrimaryKey");var PW=Symbol.for("@effect/rpc/RpcSchema/Stream"),ufe=(e)=>e.ast.annotations[Df]===PW;var Afe=({failure:e,success:t})=>Object.assign(fi([t,e],{decode:(r,n)=>lfe(Xa(dL(r)),Xa(n)),encode:(r,n)=>lfe(ec(dL(r)),ec(n))},{schemaId:PW,[PW]:{success:t,failure:e}}),{success:t,failure:e}),zJe=(e)=>te(e,AP),lfe=(e,t)=>(r,n,o)=>T(Rn(),(s)=>{if(!zJe(r))return xe(new mr(o,r));return le(r.pipe(v6((i)=>e(i,n)),pP((i)=>{if(sR(i))return M6(i);return Ju(t(i,n),{onFailure:Ko,onSuccess:xe})}),ID(s)))});var ffe=Symbol.for("@effect/rpc/Rpc");var $Je={[ffe]:ffe,pipe(){return v(this,arguments)},setSuccess(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return Ml({_tag:this._tag,payloadSchema:dn(e)?e:B(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:new Set([...this.middlewares,e])})},prefix(e){return Ml({_tag:`${e}${this._tag}`,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},annotate(e,t){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:Ar(this.annotations,e,t)})},annotateContext(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:Jr(this.annotations,e)})}},Ml=(e)=>{function t(){}return Object.setPrototypeOf(t,$Je),Object.assign(t,e),t.key=`@effect/rpc/Rpc/${e._tag}`,t},mo=(e,t)=>{let r=t?.success??ag,n=t?.error??nA,o;if(t?.primaryKey)o=class extends we(`@effect/rpc/Rpc/${e}`)(t.payload){[cfe](){return t.primaryKey(this)}};else o=dn(t?.payload)?t?.payload:t?.payload?B(t?.payload):ag;return Ml({_tag:e,payloadSchema:o,successSchema:t?.stream?Afe({success:r,failure:n}):r,errorSchema:t?.stream?nA:n,defectSchema:t?.defect??Pt,annotations:Mr(),middlewares:new Set})},dfe=(e)=>Ml({_tag:e._tag,payloadSchema:e,successSchema:e.success,errorSchema:e.failure,defectSchema:Pt,annotations:Mr(),middlewares:new Set});var KJe=Symbol.for("@effect/rpc/Rpc/Wrapper"),hfe=(e)=>(KJe in e);var ZJe=BigInt(0),Efe=tr(function*(e,t){let r=t?.spanPrefix??"RpcClient",n=t?.supportsAck??!0,o=t?.disableTracing??!1,s=t?.generateRequestId??(()=>ZJe++),i=yield*Rn(),a=pr(i,sy),c=new Map,l=!1;yield*na(a,Me(()=>(l=!0,u(T$(XJe)))));let u=tr(function*(I){for(let[S,b]of c)if(c.delete(S),b._tag==="Mailbox")yield*b.mailbox.done(I);else b.resume(I)}),A=(I)=>{let S=ufe(I.successSchema),b=h(I);return(R,D)=>{let q=D?.headers?Kf(D.headers):Bg,k=D?.context??Mr();if(!S){let J=(G)=>p(I,b,G,I.payloadSchema.make?I.payloadSchema.make(R):R,q,k,D?.discard??!1);return o?J(void 0):Rw(`${r}.${I._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes},J)}let O=f(I,b,I.payloadSchema.make?I.payloadSchema.make(R):R,q,D?.streamBufferSize??16,k);if(D?.asMailbox)return O;return rc(re(O,vee))}},p=(I,S,b,R,D,q,k)=>oa((O)=>{if(l)return ks;let J=s(),G=S({_tag:"Request",id:J,tag:I._tag,payload:R,traceId:b?.traceId,spanId:b?.spanId,sampled:b?.sampled,headers:kP(O.getFiberRef(gfe),D)});if(k)return T(G,(_)=>t.onFromClient({message:_,context:q,discard:k}));let Q=zU({context:O.currentContext,fiberRefs:O.getFiberRefs(),runtimeFlags:Oy.runtimeFlags}),F,L=!1;return gw(_r((_)=>{let j={_tag:"Effect",rpc:I,context:q,resume(ae){if(L=!0,_(ae),F&&!F.unsafePoll())O.currentScheduler.scheduleTask(()=>{F.unsafeInterruptAsFork(O.id())},0,F)}};c.set(J,j),F=G.pipe(T((ae)=>t.onFromClient({message:ae,context:q,discard:k})),b?Ry(b):Z,Ku(Q)),F.addObserver((ae)=>{if(ae._tag==="Failure")return _(ae)})}),(_)=>{if(L)return oe;c.delete(J);let j=Array.from(_).flatMap((ae)=>Array.from(PF(ae)));return Ue(Ds(F),E(J,j,q))})}),f=tr(function*(I,S,b,R,D,q){if(l)return yield*ks;let k=o?void 0:yield*j3(`${r}.${I._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes}),O=yp(Z_()),J=s(),G=Fc(O.currentContext,sy);yield*$b(G,(F)=>{if(!c.has(J))return oe;return c.delete(J),E(J,Jo(F)?Array.from(Hb(F.cause)).flatMap((L)=>Array.from(PF(L))):[],q)});let Q=yield*hA(D);return c.set(J,{_tag:"Mailbox",rpc:I,mailbox:Q,scope:G,context:q}),yield*S({_tag:"Request",id:J,tag:I._tag,traceId:k?.traceId,payload:b,spanId:k?.spanId,sampled:k?.sampled,headers:kP(O.getFiberRef(gfe),R)}).pipe(T((F)=>t.onFromClient({message:F,context:q,discard:!1})),k?Ry(k):Z,ao((F)=>Q.failCause(F)),wn,ai(G)),Q}),h=(I)=>{let S=[];for(let b of I.middlewares.values()){let R=i.unsafeMap.get(`${b.key}/Client`);if(!R)continue;S.push(R)}return S.length===0?le:function(b){let R=0;return re(Qw({while:()=>R<S.length,body:()=>S[R]({rpc:I,request:b}),step(D){b=D,R++}}),()=>b)}},E=(I,S,b)=>_r((R)=>{let D=yp(Z_()),q=zU({context:D.currentContext,fiberRefs:D.getFiberRefs(),runtimeFlags:Oy.runtimeFlags});t.onFromClient({message:{_tag:"Interrupt",requestId:I,interruptors:S},context:b,discard:!1}).pipe(Vu(1000),Ku(q)).addObserver(()=>{R(oe)})}),x=(I)=>{switch(I._tag){case"Chunk":{let S=I.requestId,b=c.get(S);if(!b||b._tag!=="Mailbox")return oe;return b.mailbox.offerAll(I.values).pipe(n?Ue(t.onFromClient({message:{_tag:"Ack",requestId:I.requestId},context:b.context,discard:!1})):Z,ao((R)=>b.mailbox.done(Kr(R))))}case"Exit":{let S=I.requestId,b=c.get(S);if(!b)return oe;if(c.delete(S),b._tag==="Effect")return b.resume(I.exit),oe;return b.mailbox.done(D$(I.exit))}case"Defect":return u(Sm(I.defect));case"ClientEnd":return oe}},y;if(t.flatten){let I=new Map;y=function(b,R,D){let q=I.get(b);if(!q)q=A(e.requests.get(b)),I.set(b,q);return q(R,D)}}else{y={};for(let I of e.requests.values()){let S=I._tag.indexOf("."),b=S===-1?void 0:I._tag.slice(0,S);if(b!==void 0&&!(b in y))y[b]={};let R=b!==void 0?y[b]:y,D=b!==void 0?I._tag.slice(S+1):I._tag;R[D]=A(I)}}return{client:y,write:x}}),XJe=qB(-503,0);var gfe=me("@effect/rpc/RpcClient/currentHeaders",()=>$u(Bg));var Cfe=/\+/g,yfe=function(){};yfe.prototype=Object.create(null);function xfe(e){let t=new yfe;if(typeof e!=="string")return t;let r=e.length,n="",o="",s=-1,i=-1,a=!1,c=!1,l=!1,u=!1,A=!1,p=0;for(let f=0;f<r+1;f++)if(p=f!==r?e.charCodeAt(f):38,p===38){if(A=i>s,!A)i=f;if(n=e.slice(s+1,i),A||n.length>0){if(l)n=n.replace(Cfe," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(A){if(o=e.slice(i+1,f),u)o=o.replace(Cfe," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let h=t[n];if(h===void 0)t[n]=o;else if(h.pop)h.push(o);else t[n]=[h,o]}o="",s=f,i=f,a=!1,c=!1,l=!1,u=!1}else if(p===61)if(i<=s)i=f;else c=!0;else if(p===43)if(i>s)u=!0;else l=!0;else if(p===37)if(i>s)c=!0;else a=!0;return t}var rze=/^https?:\/\/.*?\//,HW=/(\/:[^/()]*?)\?(\/?)/,Qfe=(e={})=>new bfe(e);class bfe{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(HW);if(n&&n.index!==void 0){nze(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let s=t.replace(HW,"$1$2"),i=t.replace(HW,"$2");this.on(e,s,r),this.on(e,i,r);return}if(this.options.ignoreDuplicateSlashes)t=Ife(t);if(this.options.ignoreTrailingSlash)t=Sfe(t);let o=typeof e==="string"?[e]:e;for(let s of o)this._on(s,t,r)}all(e,t){this.on(lze,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new eS("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new eS(""),this.trees[e].staticChildren["/"]=c}let o=this.trees[e].prefix.length,s=this.trees[e],i=[];for(let c=0;c<=n.length;c++){if(n.charCodeAt(c)===58&&n.charCodeAt(c+1)===58){c++;continue}let l=n.charCodeAt(c)===58&&n.charCodeAt(c+1)!==58,u=n.charCodeAt(c)===42;if(l||u||c===n.length&&c!==o){let A=n.slice(o,c);if(!this.options.caseSensitive)A=A.toLowerCase();A=A.split("::").join(":"),A=A.split("%").join("%25"),s=s.createStaticChild(A)}if(l){let A=!1,p=[],f=c+1;for(let h=f;;h++){let E=n.charCodeAt(h),x=E===40,y=E===45||E===46,I=E===47||h===n.length;if(x||y||I){let S=n.slice(f,h);if(i.push(S),A=A||x||y,x){let D=sze(n,h),q=n.slice(h,D+1);p.push(ize(q)),h=D+1}else p.push("(.*?)");let b=h;for(;h<n.length;h++){let D=n.charCodeAt(h);if(D===47)break;if(D===58)if(n.charCodeAt(h+1)===58)h++;else break}let R=n.slice(b,h);if(R)R=R.split("::").join(":"),R=R.split("%").join("%25"),p.push(aze(R));if(f=h+1,I||n.charCodeAt(h)===47||h===n.length){let D=A?"()"+R:R,q=n.slice(c,h);n=n.slice(0,c+1)+D+n.slice(h),c+=D.length;let k=A?new RegExp("^"+p.join("")+"$"):void 0;s=s.createParametricChild(k,R,q),o=c+1;break}}}}else if(u){if(i.push("*"),s=s.createWildcardChild(),o=c+1,c!==n.length-1)throw Error("Wildcard must be the last character in the route")}}if(!this.options.caseSensitive)n=n.toLowerCase();if(n==="*")n="/*";for(let c of this.routes)if(c.method===e&&c.pattern===n)throw Error(`Method '${e}' already declared for route '${n}'`);let a={method:e,path:t,pattern:n,params:i,handler:r};this.routes.push(a),s.addRoute(a)}has(e,t){let r=this.trees[e];if(r===void 0)return!1;let n=r.getStaticChild(t);if(n===void 0)return!1;return n.isLeafNode}find(e,t){let r=this.trees[e];if(r===void 0)return;if(t.charCodeAt(0)!==47)t=t.replace(rze,"/");if(this.options.ignoreDuplicateSlashes)t=Ife(t);let n,o,s;try{n=cze(t),t=n.path,o=n.querystring,s=n.shouldDecodeParam}catch(p){return}if(this.options.ignoreTrailingSlash)t=Sfe(t);let i=t;if(this.options.caseSensitive===!1)t=t.toLowerCase();let a=this.options.maxParamLength,c=r.prefix.length,l=[],u=t.length,A=[];while(!0){if(c===u&&r.isLeafNode){let f=r.handlerStorage?.find();if(f!==void 0)return{handler:f.handler,params:f.createParams(l),searchParams:xfe(o)}}let p=r.getNextNode(t,c,A,l.length);if(p===void 0){if(A.length===0)return;let f=A.pop();c=f.brotherPathIndex,l.splice(f.paramsCount),p=f.brotherNode}if(r=p,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let f=i.slice(c);if(s)f=Bfe(f);l.push(f),c=u;continue}if(r._tag==="ParametricNode"){let f=i.indexOf("/",c);if(f===-1)f=u;let h=i.slice(c,f);if(s)h=Bfe(h);if(r.regex!==void 0){let E=r.regex.exec(h);if(E===null)continue;for(let x=1;x<E.length;x++){let y=E[x];if(y.length>a)return;l.push(y)}}else{if(h.length>a)return;l.push(h)}c=f}}}}class wfe{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:oze(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class WW{isLeafNode=!1;routes;handlerStorage;addRoute(e){if(this.routes===void 0)this.routes=[e];else this.routes.push(e);if(this.handlerStorage===void 0)this.handlerStorage=new wfe;this.isLeafNode=!0,this.handlerStorage.add(e)}}class qW extends WW{staticChildren={};findStaticMatchingChild(e,t){let r=this.staticChildren[e.charAt(t)];if(r===void 0||!r.matchPrefix(e,t))return;return r}getStaticChild(e,t=0){if(e.length===t)return this;let r=this.findStaticMatchingChild(e,t);if(r===void 0)return;return r.getStaticChild(e,t+r.prefix.length)}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let r=e.charAt(0);return this.staticChildren[r]=new eS(e),this.staticChildren[r]}}class eS extends qW{_tag="StaticNode";constructor(e){super();this.setPrefix(e)}prefix;matchPrefix;parametricChildren=[];wildcardChild;setPrefix(e){if(this.prefix=e,e.length===1)this.matchPrefix=(t,r)=>!0;else{let t=e.length;this.matchPrefix=function(r,n){for(let o=1;o<t;o++)if(r.charCodeAt(n+o)!==this.prefix.charCodeAt(o))return!1;return!0}}}getParametricChild(e){if(e===void 0)return this.parametricChildren.find((r)=>r.isRegex===!1);let t=e.source;return this.parametricChildren.find((r)=>{if(r.regex===void 0)return!1;return r.regex.source===t})}createParametricChild(e,t,r){let n=this.getParametricChild(e);if(n!==void 0)return n.nodePaths.add(r),n;return n=new Rfe(e,t,r),this.parametricChildren.push(n),this.parametricChildren.sort((o,s)=>{if(!o.isRegex)return 1;if(!s.isRegex)return-1;if(o.staticSuffix===void 0)return 1;if(s.staticSuffix===void 0)return-1;if(s.staticSuffix.endsWith(o.staticSuffix))return 1;if(o.staticSuffix.endsWith(s.staticSuffix))return-1;return 0}),n}createWildcardChild(){if(this.wildcardChild===void 0)this.wildcardChild=new Dfe;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new eS(r);return o.staticChildren[n.charAt(0)]=this,e.staticChildren[r.charAt(0)]=o,o}getNextNode(e,t,r,n){let o=this.findStaticMatchingChild(e,t),s=0;if(o===void 0){if(this.parametricChildren.length===0)return this.wildcardChild;o=this.parametricChildren[0],s=1}if(this.wildcardChild!==void 0)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let i=this.parametricChildren.length-1;i>=s;i--)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.parametricChildren[i]});return o}}class Rfe extends qW{regex;staticSuffix;_tag="ParametricNode";constructor(e,t,r){super();this.regex=e,this.staticSuffix=t,this.isRegex=!!e,this.nodePaths=new Set([r])}isRegex;nodePaths;getNextNode(e,t){return this.findStaticMatchingChild(e,t)}}class Dfe extends WW{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var nze=(e,t)=>{if(!e)throw Error(t)};function Ife(e){return e.replace(/\/\/+/g,"/")}function Sfe(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function oze(e){let t=e.length;return function(r){let n={};for(let o=0;o<t;o++)n[e[o]]=r[o];return n}}function sze(e,t){let r=1;while(t<e.length){if(t++,e[t]==="\\"){t++;continue}if(e[t]===")")r--;else if(e[t]==="(")r++;if(!r)return t}throw TypeError('Invalid regexp expression in "'+e+'"')}function ize(e){if(e.charCodeAt(1)===94)e=e.slice(0,1)+e.slice(2);if(e.charCodeAt(e.length-2)===36)e=e.slice(0,e.length-2)+e.slice(e.length-1);return e}function aze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kfe(e,t){if(e===50){if(t===53)return"%";if(t===51)return"#";if(t===52)return"$";if(t===54)return"&";if(t===66)return"+";if(t===98)return"+";if(t===67)return",";if(t===99)return",";if(t===70)return"/";if(t===102)return"/";return}if(e===51){if(t===65)return":";if(t===97)return":";if(t===66)return";";if(t===98)return";";if(t===68)return"=";if(t===100)return"=";if(t===70)return"?";if(t===102)return"?";return}if(e===52&&t===48)return"@";return}function cze(e){let t=!1,r=!1,n="";for(let s=1;s<e.length;s++){let i=e.charCodeAt(s);if(i===37){let a=e.charCodeAt(s+1),c=e.charCodeAt(s+2);if(kfe(a,c)===void 0)t=!0;else{if(r=!0,a===50&&c===53)t=!0,e=e.slice(0,s+1)+"25"+e.slice(s+1),s+=2;s+=2}}else if(i===63||i===59||i===35){n=e.slice(s+1),e=e.slice(0,s);break}}return{path:t?decodeURI(e):e,querystring:n,shouldDecodeParam:r}}function Bfe(e){let t=e.indexOf("%");if(t===-1)return e;let r="",n=t;for(let o=t;o<e.length;o++)if(e.charCodeAt(o)===37){let s=e.charCodeAt(o+1),i=e.charCodeAt(o+2),a=kfe(s,i);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var lze=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];var Tfe=Qfe;var Mfe=(e,t)=>{let r=t.definitionPath??"#/$defs/",n=(a)=>r+a,o=t.target??"jsonSchema7",s=t.topLevelReferenceStrategy??"keep",i=t.additionalPropertiesStrategy??"strict";return rn(e,t.definitions,"handle-identifier",[],{getRef:n,target:o,topLevelReferenceStrategy:s,additionalPropertiesStrategy:i},"handle-annotation","handle-errors")},tS={$id:"/schemas/never",not:{}},Vd={$id:"/schemas/any"},_fe={$id:"/schemas/unknown"},Ufe={$id:"/schemas/void"},pze={$id:"/schemas/object",anyOf:[{type:"object"},{type:"array"}]},fze={$id:"/schemas/%7B%7D",anyOf:[{type:"object"},{type:"array"}]};function vfe(e){if(e!==void 0)return Bt(Zu(e))}function Lfe(e){if(e!==void 0)return Bt(Ly(e))}function Pfe(e){if(e!==void 0)return e9(e);return U()}function dze(e,t){return aR(e,!1)(t)}function Hfe(e){if(e!==void 0)return Bt(X5(e))}function hze(e,t){let r=aR(e,!1),n=tu(t,(o)=>r(o).pipe(xs(iT)));return n.length>0?n:void 0}function Ofe(e,t,r){if(t!==void 0)switch(e._tag){case"StringKeyword":return t!==Vm.annotations[r]?t:void 0;case"NumberKeyword":return t!==Jm.annotations[r]?t:void 0;case"BooleanKeyword":return t!==zm.annotations[r]?t:void 0}return t}function iT(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean")return!0;if(Array.isArray(e)||typeof e==="object"){if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>iT(n,t));let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return!1;if(Object.getOwnPropertySymbols(e).length>0)return!1;return Object.values(e).every((n)=>iT(n,t))}finally{t.delete(e)}}return!1}function Wfe(e,t,r,n,o){let s={};if(t!==void 0)s.description=t;if(r!==void 0)s.title=r;if(fe(n)){let i=dze(e,n.value);if(fe(i)&&iT(i.value))s.default=i.value}if(o!==void 0){let i=hze(e,o);if(i!==void 0)s.examples=i}if(Object.keys(s).length===0)return;return s}function GW(e,t){return Wfe(e,vfe(t),Lfe(t),Pfe(t),Hfe(t))}function qfe(e){return Wfe(e,Ofe(e,vfe(e),ui),Ofe(e,Lfe(e),zn),Pfe(e),Hfe(e))}function YW(e,t){if(t){if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}return e}var aT=(e)=>{if(ot(wv(e)))return Pv(e,aT,(t)=>aT(t.from))},mze=(e)=>e.annotations[Df]===Jw,gze=(e,t)=>{if(Za(e)){if(e.annotations[Df]===Hw)return"type"in t&&t.type!=="integer"}return"type"in t||"oneOf"in t||"anyOf"in t||"$ref"in t},Eze=(e,t,r)=>{let n={...e,...qfe(r),...t};n.allOf??=[];let o=(s,i)=>{if(s in t&&s in e)n.allOf.unshift({[s]:e[s]}),n.allOf=n.allOf.filter(i)};if(o("minLength",(s)=>s.minLength>t.minLength),o("maxLength",(s)=>s.maxLength<t.maxLength),o("pattern",(s)=>s.pattern!==t.pattern),o("minItems",(s)=>s.minItems>t.minItems),o("maxItems",(s)=>s.maxItems<t.maxItems),o("minimum",(s)=>s.minimum>t.minimum),o("maximum",(s)=>s.maximum<t.maximum),o("exclusiveMinimum",(s)=>s.exclusiveMinimum>t.exclusiveMinimum),o("exclusiveMaximum",(s)=>s.exclusiveMaximum<t.exclusiveMaximum),o("multipleOf",(s)=>s.multipleOf!==t.multipleOf),n.allOf.length===0)delete n.allOf;return n};function Cze(e){switch(e.target){case"jsonSchema7":return!1;case"jsonSchema2019-09":case"jsonSchema2020-12":case"openApi3.1":return!0}}function yze(e){switch(e.additionalPropertiesStrategy){case"allow":return!0;case"strict":return!1}}function Zt(e,t){return Gfe(e,qfe(t))}function Gfe(e,t){if(t===void 0||Object.keys(t).length===0)return e;if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}function VW(e){let t=Bt(Dv(e));if(t===void 0){if(Nv(e))return VW(e.f());if(eR(e)&&Wy(e.from)&&i9(e.to)){let r=e.to,n=il(r);if(fe(n))return VW(r)}}return t}function rn(e,t,r,n,o,s,i){if(r==="handle-identifier"&&(o.topLevelReferenceStrategy!=="skip"||Nv(e))){let c=VW(e);if(c!==void 0){let l=c.replace(/~/ig,"~0").replace(/\//ig,"~1"),u={$ref:o.getRef(l)};if(!jO(t,c))t[c]=u,t[c]=rn(e,t,"ignore-identifier",n,o,"handle-annotation",i);return u}}if(s==="handle-annotation"){let c=wv(e);if(fe(c)){let l=c.value;if(gze(e,l))switch(e._tag){case"Declaration":return Zt(l,e);default:return l}else switch(e._tag){case"Refinement":{let u=My(e);if(u===void 0)return Eze(rn(e.from,t,r,n,o,"handle-annotation",i),l,e);else return rn(u,t,r,n,o,"handle-annotation",i)}default:return{...rn(e,t,r,n,o,"ignore-annotation",i),...l}}}}let a=il(e);if(fe(a))return rn(a.value,t,r,n,o,"handle-annotation",i);switch(e._tag){case"Declaration":case"UndefinedKeyword":case"BigIntKeyword":case"UniqueSymbol":case"SymbolKeyword":{if(i==="ignore-errors")return Zt(Vd,e);throw Error(cv(n,e))}case"Suspend":{if(r==="handle-identifier"){if(i==="ignore-errors")return Zt(Vd,e);throw Error(O5(n,e))}return rn(e.f(),t,"ignore-identifier",n,o,"handle-annotation",i)}case"NeverKeyword":return Zt(tS,e);case"VoidKeyword":return Zt(Ufe,e);case"UnknownKeyword":return Zt(_fe,e);case"AnyKeyword":return Zt(Vd,e);case"ObjectKeyword":return Zt(pze,e);case"StringKeyword":return Zt({type:"string"},e);case"NumberKeyword":return Zt({type:"number"},e);case"BooleanKeyword":return Zt({type:"boolean"},e);case"Literal":{let c=e.literal;if(c===null)return Zt({type:"null"},e);else if(Ut(c))return Zt({type:"string",enum:[c]},e);else if(On(c))return Zt({type:"number",enum:[c]},e);else if(gs(c))return Zt({type:"boolean",enum:[c]},e);if(i==="ignore-errors")return Zt(Vd,e);throw Error(cv(n,e))}case"Enums":{let c=e.enums.map((l)=>({type:On(l[1])?"number":"string",title:l[0],enum:[l[1]]}));return c.length>=1?Zt({$comment:"/schemas/enums",anyOf:c},e):Zt(tS,e)}case"TupleType":{let c=e.elements.map((f,h)=>YW(rn(f.type,t,"handle-identifier",n.concat(h),o,"handle-annotation",i),GW(f.type,f))),l=e.rest.map((f)=>YW(rn(f.type,t,"handle-identifier",n,o,"handle-annotation",i),GW(f.type,f))),u={type:"array"},A=e.elements.length;if(A>0)if(u.minItems=A-e.elements.filter((f)=>f.isOptional).length,o.target==="jsonSchema7")u.items=c;else u.prefixItems=c;let p=l.length;if(p>0){let f=l[0];if(p===1&&e.elements.every((E)=>E.type===e.rest[0].type))if(o.target==="jsonSchema7")u.items=f;else u.items=f,delete u.prefixItems;else if(o.target==="jsonSchema7")u.additionalItems=f;else u.items=f;if(p>1){if(i==="ignore-errors")return Zt(Vd,e);throw Error(F5(n))}}else if(A>0)if(o.target==="jsonSchema7")u.additionalItems=!1;else u.items=!1;else u.maxItems=0;return Zt(u,e)}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Zt(fze,e);let c={type:"object",required:[],properties:{},additionalProperties:yze(o)},l=void 0,u=void 0;for(let A of e.indexSignatures){let p=aT(A.type)??A.type,f=A.parameter;switch(f._tag){case"StringKeyword":{c.additionalProperties=rn(p,t,"handle-identifier",n,o,"handle-annotation",i);break}case"TemplateLiteral":{l=rn(p,t,"handle-identifier",n,o,"handle-annotation",i),u={type:"string",pattern:Zm(f).source};break}case"Refinement":{l=rn(p,t,"handle-identifier",n,o,"handle-annotation",i),u=rn(f,t,"handle-identifier",n,o,"handle-annotation",i);break}case"SymbolKeyword":{let h=n.concat("[symbol]");c.additionalProperties=rn(p,t,"handle-identifier",h,o,"handle-annotation",i),u=rn(f,t,"handle-identifier",h,o,"handle-annotation",i);break}}}for(let A=0;A<e.propertySignatures.length;A++){let p=e.propertySignatures[A],f=p.name;if(Ut(f)){let h=aT(p.type),E=h??p.type;if(c.properties[f]=YW(rn(E,t,"handle-identifier",n.concat(p.name),o,"handle-annotation",i),GW(E,p)),!p.isOptional&&h===void 0)c.required.push(f)}else{if(i==="ignore-errors")return Zt(Vd,e);throw Error(N5(f,n))}}if(l!==void 0)delete c.additionalProperties,c.patternProperties={"":l};if(u!==void 0)c.propertyNames=u;return Zt(c,e)}case"Union":{let c=e.types.map((u)=>rn(u,t,"handle-identifier",n,o,"handle-annotation",i)),l=Qze(c);switch(l.length){case 0:return tS;case 1:return Zt(l[0],e);default:return Zt({anyOf:l},e)}}case"Refinement":return rn(e.from,t,r,n,o,"handle-annotation",i);case"TemplateLiteral":{let c=Zm(e);return Zt({type:"string",title:String(e),description:"a template literal",pattern:c.source},e)}case"Transformation":{if(mze(e.from)){let l={type:"string",contentMediaType:"application/json"};if(Cze(o))l.contentSchema=rn(e.to,t,r,n,o,"handle-annotation",i);return l}let c=rn(e.from,t,r,n,o,"handle-annotation",i);if(e.transformation._tag==="TypeLiteralTransformation"&&Ffe(c)){let l=rn(e.to,{},"ignore-identifier",n,o,"handle-annotation","ignore-errors");if(Ffe(l))for(let u of e.transformation.propertySignatureTransformations){let{to:A,from:p}=u;if(Ut(A)&&Ut(p)){let f=l.properties[A];if(zl(f)){let h=c.properties[p];if(zl(h)){let E={};if(Ut(f.title))E.title=f.title;if(Ut(f.description))E.description=f.description;if(Array.isArray(f.examples))E.examples=f.examples;if(Object.hasOwn(f,"default")&&f.default!==void 0)E.default=f.default;c.properties[p]=Gfe(h,E)}}}}}return Zt(c,e)}}}function Ffe(e){return zl(e)&&e.type==="object"&&zl(e.properties)}function xze(e){return e===tS||te(e,"$id")&&e.$id===tS.$id&&Object.keys(e).length===3&&e.title===Ff.annotations[zn]}function Ize(e){return"$id"in e&&e.$id===Vd.$id}function Sze(e){return"$id"in e&&e.$id===_fe.$id}function Bze(e){return"$id"in e&&e.$id===Ufe.$id}function Nfe(e){return te(e,"enum")&&"type"in e&&Object.keys(e).length===2}function Qze(e){let t=[];for(let r of e){if(xze(r))continue;if(Ize(r)||Sze(r)||Bze(r))return[r];if(Nfe(r)&&t.length>0){let n=t[t.length-1];if(Nfe(n)&&n.type===r.type){t[t.length-1]={type:n.type,enum:[...n.enum,...r.enum]};continue}}t.push(r)}return t}var wze={add(...e){return VA({requests:Yfe(...this.requests.values(),...e),annotations:this.annotations})},merge(...e){let t=new Map(this.requests),r=new Map(this.annotations.unsafeMap);for(let n of e){for(let[o,s]of n.requests)t.set(o,s);for(let[o,s]of n.annotations.unsafeMap)r.set(o,s)}return VA({requests:t,annotations:Rh(r)})},middleware(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.middleware(e));return VA({requests:t,annotations:this.annotations})},toHandlersContext(e){return Ze(this,function*(){let t=yield*Rn(),r=Qn(e)?yield*e:e,n=new Map;for(let[o,s]of Object.entries(r)){let i=this.requests.get(o);n.set(i.key,{handler:s,context:t})}return Rh(n)})},prefix(e){let t=new Map;for(let r of this.requests.values()){let n=r.prefix(e);t.set(n._tag,n)}return VA({requests:t,annotations:this.annotations})},toLayer(e){return Dy(this.toHandlersContext(e))},of:Z,toLayerHandler(e,t){return Dy(Ze(this,function*(){let r=yield*Rn(),n=Qn(t)?yield*t:t,o=new Map,s=this.requests.get(e);return o.set(s.key,{handler:n,context:r}),Rh(o)}))},accessHandler(e){return vU((t)=>{let r=this.requests.get(e),{context:n,handler:o}=t.unsafeMap.get(r.key);return(s,i)=>{let a=o(s,i),c=hfe(a)?a.value:a;return Qn(c)?Xo(c,n):ID(c,n)}})},annotate(e,t){return VA({requests:this.requests,annotations:Ar(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsContext(Oc(e,t))},annotateContext(e){return VA({requests:this.requests,annotations:Jr(this.annotations,e)})},annotateRpcsContext(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.annotateContext(Jr(e,n.annotations)));return VA({requests:t,annotations:this.annotations})}},VA=(e)=>Object.assign(function(){},wze,{requests:e.requests,annotations:e.annotations}),Yfe=(...e)=>{let t=new Map;for(let r of e)t.set(r._tag,dn(r)?dfe(r):r);return t},Vfe=(...e)=>VA({requests:Yfe(...e),annotations:Mr()});var Dze=Ie(m,K),Jfe=Ie(m,K);class _l extends B({_meta:M(B({progressToken:M(Jfe)}))}){}class JA extends B({_meta:M(hn({key:m,value:bt}))}){}class zA extends B({_meta:M(hn({key:m,value:bt}))}){}var zfe=m;class kze extends B({..._l.fields,cursor:M(zfe)}){}class rS extends B({...JA.fields,nextCursor:M(zfe)}){}var jfe=N("user","assistant");class Jd extends B({audience:M(be(jfe)),priority:M(K.pipe(gR(0,1)))}){}class JW extends B({name:m,title:M(m),version:m}){}class $fe extends we("@effect/ai/McpSchema/ClientCapabilities")({experimental:M(hn({key:m,value:B({})})),roots:M(B({listChanged:M(se)})),sampling:M(B({})),elicitation:M(B({}))}){}class Kfe extends B({experimental:M(hn({key:m,value:B({})})),logging:M(B({})),completions:M(B({})),prompts:M(B({listChanged:M(se)})),resources:M(B({subscribe:M(se),listChanged:M(se)})),tools:M(B({listChanged:M(se)}))}){}class hs extends we("@effect/ai/McpSchema/McpError")({code:K,message:m,data:M(bt)}){}var Tze=-32600,Oze=-32601,Fze=-32602,Nze=-32603,Mze=-32700;class _ze extends at()("ParseError",{...hs.fields,code:di(Mze)}){}class Uze extends at()("InvalidRequest",{...hs.fields,code:di(Tze)}){}class vze extends at()("MethodNotFound",{...hs.fields,code:di(Oze)}){}class nS extends at()("InvalidParams",{...hs.fields,code:di(Fze)}){}class yE extends at()("InternalError",{...hs.fields,code:di(Nze)}){static notImplemented=new yE({message:"Not implemented"})}class Zfe extends we("@effect/ai/McpSchema/InitializeResult")({...JA.fields,protocolVersion:m,capabilities:Kfe,serverInfo:JW,instructions:M(m)}){}class Lze extends mo("initialize",{success:Zfe,error:hs,payload:{..._l.fields,protocolVersion:m,capabilities:$fe,clientInfo:JW}}){}class Xfe extends mo("notifications/cancelled",{payload:{...zA.fields,requestId:Dze,reason:M(m)}}){}class ede extends mo("notifications/progress",{payload:{...zA.fields,progressToken:Jfe,progress:M(K),total:M(K),message:M(m)}}){}class oS extends we("@effect/ai/McpSchema/Resource")({uri:m,name:m,title:M(m),description:M(m),mimeType:M(m),annotations:M(Jd),size:M(K)}){}class cT extends we("@effect/ai/McpSchema/ResourceTemplate")({uriTemplate:m,name:m,title:M(m),description:M(m),mimeType:M(m),annotations:M(Jd)}){}class zW extends B({uri:m,mimeType:M(m)}){}class jW extends B({...zW.fields,text:m}){}class $W extends B({...zW.fields,blob:yR}){}class tde extends we("@effect/ai/McpSchema/ListResourcesResult")({...rS.fields,resources:be(oS)}){}class rde extends we("@effect/ai/McpSchema/ListResourceTemplatesResult")({...rS.fields,resourceTemplates:be(cT)}){}class nde extends B({...JA.fields,contents:be(Ie(jW,$W))}){}class Pze extends mo("resources/read",{success:nde,error:hs,payload:{..._l.fields,uri:m}}){}class ode extends mo("notifications/resources/list_changed",{payload:Al(zA)}){}class Hze extends mo("resources/subscribe",{error:hs,payload:{..._l.fields,uri:m}}){}class Wze extends mo("resources/unsubscribe",{error:hs,payload:{..._l.fields,uri:m}}){}class sde extends mo("notifications/resources/updated",{payload:{...zA.fields,uri:m}}){}class ide extends B({name:m,title:M(m),description:M(m),required:M(se)}){}class KW extends we("@effect/ai/McpSchema/Prompt")({name:m,title:M(m),description:M(m),arguments:M(be(ide))}){}class ZW extends B({type:di("text"),text:m,annotations:M(Jd)}){}class ade extends B({type:di("image"),data:yR,mimeType:m,annotations:M(Jd)}){}class cde extends B({type:di("audio"),data:yR,mimeType:m,annotations:M(Jd)}){}class lde extends B({type:di("resource"),resource:Ie(jW,$W),annotations:M(Jd)}){}class ude extends B({...oS.fields,type:di("resource_link")}){}class XW extends Ie(ZW,ade,cde,lde,ude){}class Ade extends B({role:jfe,content:XW}){}class pde extends we("@effect/ai/McpSchema/ListPromptsResult")({...rS.fields,prompts:be(KW)}){}class eq extends we("@effect/ai/McpSchema/GetPromptResult")({...JA.fields,messages:be(Ade),description:M(m)}){}class qze extends mo("prompts/get",{success:eq,error:hs,payload:{..._l.fields,name:m,title:M(m),arguments:M(hn({key:m,value:m}))}}){}class fde extends mo("notifications/prompts/list_changed",{payload:Al(zA)}){}class lT extends we("@effect/ai/McpSchema/ToolAnnotations")({title:M(m),readOnlyHint:C(se,{default:()=>!1}),destructiveHint:C(se,{default:()=>!0}),idempotentHint:C(se,{default:()=>!1}),openWorldHint:C(se,{default:()=>!0})}){}class uT extends we("@effect/ai/McpSchema/Tool")({name:m,title:M(m),description:M(m),inputSchema:bt,annotations:M(lT)}){}class dde extends we("@effect/ai/McpSchema/ListToolsResult")({...rS.fields,tools:be(uT)}){}class sS extends we("@effect/ai/McpSchema/CallToolResult")({...JA.fields,content:be(XW),structuredContent:M(bt),isError:M(se)}){}class Gze extends mo("tools/call",{success:sS,error:hs,payload:{..._l.fields,name:m,arguments:hn({key:m,value:bt})}}){}class hde extends mo("notifications/tools/list_changed",{payload:Al(zA)}){}var mde=N("debug","info","notice","warning","error","critical","alert","emergency");class Yze extends mo("logging/setLevel",{payload:{..._l.fields,level:mde},error:hs}){}class gde extends mo("notifications/message",{payload:B({...zA.fields,level:mde,logger:M(m),data:bt})}){}class iS extends we("@effect/ai/McpSchema/CompleteResult")({completion:B({values:be(m),total:M(K),hasMore:M(se)})}){static empty=iS.make({completion:{values:[],total:0,hasMore:!1}})}class Ede extends we("@effect/ai/McpSchema/ElicitAcceptResult")({...JA.fields,action:N("accept"),content:bt}){}class Cde extends we("@effect/ai/McpSchema/ElicitDeclineResult")({...JA.fields,action:N("cancel","decline")}){}var Vze=Ie(Ede,Cde);class tq extends mo("elicitation/create",{success:Vze,error:hs,payload:{message:m,requestedSchema:bt}}){}class yde extends at("@effect/ai/McpSchema/ElicitationDeclined")("ElicitationDeclined",{request:tq.payloadSchema,cause:M(Pt)}){}class rq extends Vfe(Xfe,ede,gde,sde,ode,hde,fde){}var xde=Symbol.for("@effect/ai/McpSchema/ParamNameId");var Jze="~@effect/ai/Tool",Ide="~@effect/ai/Tool/ProviderDefined";var Sde={[Jze]:{_Requirements:Z},pipe(){return v(this,arguments)},addDependency(){return jA({...this})},setParameters(e){return jA({...this,parametersSchema:dn(e)?e:B(e)})},setSuccess(e){return jA({...this,successSchema:e})},setFailure(e){return jA({...this,failureSchema:e})},annotate(e,t){return jA({...this,annotations:Ar(this.annotations,e,t)})},annotateContext(e){return jA({...this,annotations:Jr(this.annotations,e)})}},_wt={...Sde,[Ide]:Ide},jA=(e)=>{let t=Object.assign(Object.create(Sde),e);return t.id=`@effect/ai/Tool/${e.name}`,t};var zze=B({}),nq=(e,t)=>{let r=t?.success??ag,n=t?.failure??nA;return jA({name:e,description:t?.description,parametersSchema:t?.parameters?B(t?.parameters):zze,successSchema:r,failureSchema:n,failureMode:t?.failureMode??"error",annotations:Mr()})};var Bde=(e)=>jA({name:e._tag,description:Bt(Zu(e.ast.to)),parametersSchema:e,successSchema:e.success,failureSchema:e.failure,failureMode:"error",annotations:Mr()});class oq extends ba("@effect/ai/Tool/Title")(){}class xE extends Mn()("@effect/ai/Tool/Readonly",{defaultValue:Or}){}class IE extends Mn()("@effect/ai/Tool/Destructive",{defaultValue:Zn}){}class sq extends Mn()("@effect/ai/Tool/Idempotent",{defaultValue:Or}){}class iq extends Mn()("@effect/ai/Tool/OpenWorld",{defaultValue:Zn}){}class Ec extends ba("@effect/ai/McpServer")(){static make=Ze(function*(){let e=Kze(),t=Vr(),r=new Map,n=[],o=[],s=[],i=new Map,a=new Map,c=yield*hA(),l=new Map,u=yield*Efe(rq,{spanPrefix:"McpServer/Notifications",onFromClient(A){let p=A.message;if(p._tag!=="Request")return oe;if(p.tag.includes("list_changed")){if(!l.has(p.tag))l.set(p.tag,setTimeout(()=>{c.unsafeOffer(p),l.delete(p.tag)},0))}else c.unsafeOffer(p);return u.write({clientId:0,requestId:p.id,_tag:"Exit",exit:oi})}});return Ec.of({notifications:u.client,notificationsMailbox:c,initializedClients:new Set,get tools(){return t},addTool:(A)=>Me(()=>(t.push(A.tool),r.set(A.tool.name,A.handle),u.client["notifications/tools/list_changed"]({}))),callTool:(A)=>Me(()=>{let p=r.get(A.name);if(!p)return xe(new nS({message:`Tool '${A.name}' not found`}));return p(A.arguments)}),get resources(){return n},get resourceTemplates(){return o},addResource:(A,p)=>Me(()=>(n.push(A),e.add(A.uri,{_tag:"Resource",effect:p}),u.client["notifications/resources/list_changed"]({}))),addResourceTemplate:({completions:A,handle:p,routerPath:f,template:h})=>Me(()=>{o.push(h),e.add(f,{_tag:"ResourceTemplate",handle:p});for(let[E,x]of Object.entries(A))a.set(`ref/resource/${h.uriTemplate}/${E}`,x);return u.client["notifications/resources/list_changed"]({})}),findResource:(A)=>Me(()=>{let p=e.find(A);if(!p)return le({contents:[]});else if(p.handler._tag==="Resource")return p.handler.effect;let f=[];for(let h of Object.keys(p.params))f[Number(h)]=p.params[h];return p.handler.handle(A,f)}),get prompts(){return s},addPrompt:(A)=>Me(()=>{s.push(A.prompt),i.set(A.prompt.name,A.handle);for(let[p,f]of Object.entries(A.completions))a.set(`ref/prompt/${A.prompt.name}/${p}`,f);return u.client["notifications/prompts/list_changed"]({})}),getPromptResult:tr(function*({arguments:A,name:p}){let f=i.get(p);if(!f)return yield*new nS({message:`Prompt '${p}' not found`});return yield*f(A??{})}),completion:tr(function*(A){let p=A.ref,f=p.type==="ref/resource"?`ref/resource/${p.uri}/${A.argument.name}`:`ref/prompt/${p.name}/${A.argument.name}`,h=a.get(f);return h?yield*h(A.argument.value):iS.empty})})});static layer=zu(Ec,Ec.make)}var jze=tr(function*(e){let t=yield*Ec,r=yield*e,n=yield*Rn();for(let o of Object.values(r.tools)){let s=new uT({name:o.name,description:o.description,inputSchema:Xze(o.parametersSchema.ast),annotations:new lT({...yo(o.annotations,oq).pipe(Xt((i)=>({title:i})),Bt),readOnlyHint:pr(o.annotations,xE),destructiveHint:pr(o.annotations,IE),idempotentHint:pr(o.annotations,sq),openWorldHint:pr(o.annotations,iq)})});yield*t.addTool({tool:s,handle(i){return r.handle(o.name,i).pipe(Xo(n),bw({onFailure:(a)=>new sS({isError:!0,structuredContent:typeof a==="object"?a:void 0,content:[{type:"text",text:JSON.stringify(a)}]}),onSuccess:(a)=>new sS({isError:!1,structuredContent:typeof a.encodedResult==="object"?a.encodedResult:void 0,content:[{type:"text",text:JSON.stringify(a.encodedResult)}]})}))}})}}),$ze=(e)=>Dw(jze(e)).pipe(rs(Ec.layer)),Qde=function(){if(arguments.length===1){let o=arguments[0];return Ze(function*(){let s=yield*Rn();yield*(yield*Ec).addResource(new oS({...o,annotations:o}),o.content.pipe(Xo(s),re((a)=>bde(o.uri,a)),ao((a)=>{let c=Gb(a)[0];return new yE({message:c.message})})))})}let{params:e,routerPath:t,schema:r,uriPath:n}=Zze(...arguments);return tr(function*(o){let s=yield*Rn(),i=yield*Ec,a=os(r),c=new cT({...o,uriTemplate:n,annotations:o}),l={};for(let[u,A]of Object.entries(o.completion??{})){let p=Wf(be(e[u])),f=(h)=>A(h).pipe(T(p),re((E)=>new iS({completion:{values:E,total:E.length,hasMore:!1}})),ao((E)=>{let x=Gb(E)[0];return new yE({message:x.message})}),Xo(s));l[u]=f}yield*i.addResourceTemplate({template:c,routerPath:t,completions:l,handle:(u,A)=>a(A).pipe(_e((p)=>new nS({message:p.message})),T((p)=>o.content(u,...p).pipe(re((f)=>bde(u,f)),ao((f)=>{let h=Gb(f)[0];return new yE({message:h.message})}))),Xo(s))})})},wde=function(){if(arguments.length===1)return Dw(Qde(arguments[0])).pipe(rs(Ec.layer));let e=Qde(...arguments);return(t)=>Dw(e(t)).pipe(rs(Ec.layer))};var Kze=()=>{let e=Tfe({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(n,o)=>{e.on("GET",n,o)},find:(n)=>e.find("GET",n)}},Zze=(e,...t)=>{let r=e[0].replace(":","::"),n=e[0],o={},s=dR();if(t.length>0){let i=[];for(let a=0;a<t.length;a++){let c=t[a],l=e[a+1],u=String(a);i.push(c),r+=`:${u}${l.replace(":","::")}`;let A=Xr(xde)(c.ast).pipe(Ve(()=>`param${u}`));o[A]=c,n+=`{${A}}${l}`}s=dR(...i)}return{routerPath:r,uriPath:n,schema:s,params:o}};var Xze=(e)=>{if(Ny(e).length===0)return{type:"object",properties:{},required:[],additionalProperties:!1};let r={},n=Mfe(e,{definitions:r,topLevelReferenceStrategy:"skip"});if(Object.keys(r).length===0)return n;return n.$defs=r,n},bde=(e,t)=>{if(typeof t==="string")return{contents:[{uri:e,text:t}]};else if(t instanceof Uint8Array)return{contents:[{uri:e,blob:t}]};return t};var AT="~@effect/ai/AiError";class pT extends at("@effect/ai/AiError/MalformedInput")("MalformedInput",{module:m,method:m,description:M(m),cause:M(Pt)}){[AT]=AT}class cS extends at("@effect/ai/AiError/MalformedOutput")("MalformedOutput",{module:m,method:m,description:M(m),cause:M(Pt)}){[AT]=AT;static fromParseError({error:e,...t}){return new cS({...t,cause:e})}}var tje={...um,...Cs,of:Z,toContext(e){return Ze(this,function*(){let t=yield*Rn(),r=Qn(e)?yield*e:e,n=new Map;for(let[o,s]of Object.entries(r)){let i=this.tools[o];n.set(i.id,{handler:s,context:t})}return Rh(n)})},toLayer(e){return Dy(this.toContext(e))},commit(){return Ze(this,function*(){let e=this.tools,t=yield*Rn(),r=new WeakMap,n=(s)=>{let i=r.get(s);if(WE(i)){let a=t.unsafeMap.get(s.id),c=os(s.parametersSchema),l=Ie(s.successSchema,s.failureSchema),u=lX(l),A=Wf(l);i={context:a.context,handler:a.handler,decodeParameters:c,validateResult:u,encodeResult:A},r.set(s,i)}return i},o=Pe("Toolkit.handle",{captureStackTrace:!1})(function*(s,i){yield*z3({tool:s,parameters:i});let a=e[s];if(WE(a)){let f=Object.keys(e).join(",");return yield*new cS({module:"Toolkit",method:`${s}.handle`,description:`Failed to find tool with name '${s}' in toolkit - available tools: ${f}`})}let c=n(a),l=yield*_e(c.decodeParameters(i),(f)=>new cS({module:"Toolkit",method:`${s}.handle`,description:`Failed to decode tool call parameters for tool '${s}' from:
175
+ `)});class YJe extends za()("@expandai/cli/Install/ConfigIo",{dependencies:[iH,vW],effect:Ze(function*(){let e=yield*Ms,t=yield*Fo,r=Pe("ConfigIo.read")(function*(a,c){let l=yield*GJe(a).pipe(es(Ms,e));return yield*fR(c)(l)}),n=Pe("ConfigIo.write")(function*(a,c,l){let u=yield*Wf(l)(c);yield*sfe(a,u).pipe(es(Ms,e),es(Fo,t))}),o=Pe("ConfigIo.exists")(function*(a){return yield*e.exists(a)}),s=Pe("ConfigIo.readText")(function*(a){return(yield*e.exists(a))?yield*e.readFileString(a):""}),i=Pe("ConfigIo.writeText")(function*(a,c){yield*sfe(a,c).pipe(es(Ms,e),es(Fo,t))});return{read:r,write:n,exists:o,readText:s,writeText:i}})}){}class VJe extends za()("@expandai/cli/Install/SkillIo",{dependencies:[iH,vW],effect:Ze(function*(){let e=yield*Ms,t=yield*Fo,r=yield*t.fromFileUrl(nfe),n=Pe("SkillIo.install")(function*(a){return yield*e.makeDirectory(t.dirname(a),{recursive:!0}),yield*e.copy(r,a,{overwrite:!0}),a}),o=Pe("SkillIo.uninstall")(function*(a){if(yield*e.exists(a))yield*e.remove(a,{recursive:!0});return a}),s=Pe("SkillIo.isCurrent")(function*(a){let c=t.join(a,"SKILL.md");if(!(yield*e.exists(c)))return!1;let[l,u]=yield*Gu([e.readFileString(c),e.readFileString(t.join(r,"SKILL.md"))]);return l===u}),i=Pe("SkillIo.isInstalled")(function*(a){return yield*e.exists(t.join(a,"SKILL.md"))});return{install:n,uninstall:o,isCurrent:s,isInstalled:i}})}){}var XI="0.1.2";var cfe=Symbol.for("effect/PrimaryKey");var PW=Symbol.for("@effect/rpc/RpcSchema/Stream"),ufe=(e)=>e.ast.annotations[Df]===PW;var Afe=({failure:e,success:t})=>Object.assign(fi([t,e],{decode:(r,n)=>lfe(Xa(dL(r)),Xa(n)),encode:(r,n)=>lfe(ec(dL(r)),ec(n))},{schemaId:PW,[PW]:{success:t,failure:e}}),{success:t,failure:e}),zJe=(e)=>te(e,AP),lfe=(e,t)=>(r,n,o)=>T(Rn(),(s)=>{if(!zJe(r))return xe(new mr(o,r));return le(r.pipe(v6((i)=>e(i,n)),pP((i)=>{if(sR(i))return M6(i);return Ju(t(i,n),{onFailure:Ko,onSuccess:xe})}),ID(s)))});var ffe=Symbol.for("@effect/rpc/Rpc");var $Je={[ffe]:ffe,pipe(){return v(this,arguments)},setSuccess(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return Ml({_tag:this._tag,payloadSchema:dn(e)?e:B(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:new Set([...this.middlewares,e])})},prefix(e){return Ml({_tag:`${e}${this._tag}`,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},annotate(e,t){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:Ar(this.annotations,e,t)})},annotateContext(e){return Ml({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:Jr(this.annotations,e)})}},Ml=(e)=>{function t(){}return Object.setPrototypeOf(t,$Je),Object.assign(t,e),t.key=`@effect/rpc/Rpc/${e._tag}`,t},mo=(e,t)=>{let r=t?.success??ag,n=t?.error??nA,o;if(t?.primaryKey)o=class extends we(`@effect/rpc/Rpc/${e}`)(t.payload){[cfe](){return t.primaryKey(this)}};else o=dn(t?.payload)?t?.payload:t?.payload?B(t?.payload):ag;return Ml({_tag:e,payloadSchema:o,successSchema:t?.stream?Afe({success:r,failure:n}):r,errorSchema:t?.stream?nA:n,defectSchema:t?.defect??Pt,annotations:Mr(),middlewares:new Set})},dfe=(e)=>Ml({_tag:e._tag,payloadSchema:e,successSchema:e.success,errorSchema:e.failure,defectSchema:Pt,annotations:Mr(),middlewares:new Set});var KJe=Symbol.for("@effect/rpc/Rpc/Wrapper"),hfe=(e)=>(KJe in e);var ZJe=BigInt(0),Efe=tr(function*(e,t){let r=t?.spanPrefix??"RpcClient",n=t?.supportsAck??!0,o=t?.disableTracing??!1,s=t?.generateRequestId??(()=>ZJe++),i=yield*Rn(),a=pr(i,sy),c=new Map,l=!1;yield*na(a,Me(()=>(l=!0,u(T$(XJe)))));let u=tr(function*(I){for(let[S,b]of c)if(c.delete(S),b._tag==="Mailbox")yield*b.mailbox.done(I);else b.resume(I)}),A=(I)=>{let S=ufe(I.successSchema),b=h(I);return(R,D)=>{let q=D?.headers?Kf(D.headers):Bg,k=D?.context??Mr();if(!S){let J=(G)=>p(I,b,G,I.payloadSchema.make?I.payloadSchema.make(R):R,q,k,D?.discard??!1);return o?J(void 0):Rw(`${r}.${I._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes},J)}let O=f(I,b,I.payloadSchema.make?I.payloadSchema.make(R):R,q,D?.streamBufferSize??16,k);if(D?.asMailbox)return O;return rc(re(O,vee))}},p=(I,S,b,R,D,q,k)=>oa((O)=>{if(l)return ks;let J=s(),G=S({_tag:"Request",id:J,tag:I._tag,payload:R,traceId:b?.traceId,spanId:b?.spanId,sampled:b?.sampled,headers:kP(O.getFiberRef(gfe),D)});if(k)return T(G,(_)=>t.onFromClient({message:_,context:q,discard:k}));let Q=zU({context:O.currentContext,fiberRefs:O.getFiberRefs(),runtimeFlags:Oy.runtimeFlags}),F,L=!1;return gw(_r((_)=>{let j={_tag:"Effect",rpc:I,context:q,resume(ae){if(L=!0,_(ae),F&&!F.unsafePoll())O.currentScheduler.scheduleTask(()=>{F.unsafeInterruptAsFork(O.id())},0,F)}};c.set(J,j),F=G.pipe(T((ae)=>t.onFromClient({message:ae,context:q,discard:k})),b?Ry(b):Z,Ku(Q)),F.addObserver((ae)=>{if(ae._tag==="Failure")return _(ae)})}),(_)=>{if(L)return oe;c.delete(J);let j=Array.from(_).flatMap((ae)=>Array.from(PF(ae)));return Ue(Ds(F),E(J,j,q))})}),f=tr(function*(I,S,b,R,D,q){if(l)return yield*ks;let k=o?void 0:yield*j3(`${r}.${I._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes}),O=yp(Z_()),J=s(),G=Fc(O.currentContext,sy);yield*$b(G,(F)=>{if(!c.has(J))return oe;return c.delete(J),E(J,Jo(F)?Array.from(Hb(F.cause)).flatMap((L)=>Array.from(PF(L))):[],q)});let Q=yield*hA(D);return c.set(J,{_tag:"Mailbox",rpc:I,mailbox:Q,scope:G,context:q}),yield*S({_tag:"Request",id:J,tag:I._tag,traceId:k?.traceId,payload:b,spanId:k?.spanId,sampled:k?.sampled,headers:kP(O.getFiberRef(gfe),R)}).pipe(T((F)=>t.onFromClient({message:F,context:q,discard:!1})),k?Ry(k):Z,ao((F)=>Q.failCause(F)),wn,ai(G)),Q}),h=(I)=>{let S=[];for(let b of I.middlewares.values()){let R=i.unsafeMap.get(`${b.key}/Client`);if(!R)continue;S.push(R)}return S.length===0?le:function(b){let R=0;return re(Qw({while:()=>R<S.length,body:()=>S[R]({rpc:I,request:b}),step(D){b=D,R++}}),()=>b)}},E=(I,S,b)=>_r((R)=>{let D=yp(Z_()),q=zU({context:D.currentContext,fiberRefs:D.getFiberRefs(),runtimeFlags:Oy.runtimeFlags});t.onFromClient({message:{_tag:"Interrupt",requestId:I,interruptors:S},context:b,discard:!1}).pipe(Vu(1000),Ku(q)).addObserver(()=>{R(oe)})}),x=(I)=>{switch(I._tag){case"Chunk":{let S=I.requestId,b=c.get(S);if(!b||b._tag!=="Mailbox")return oe;return b.mailbox.offerAll(I.values).pipe(n?Ue(t.onFromClient({message:{_tag:"Ack",requestId:I.requestId},context:b.context,discard:!1})):Z,ao((R)=>b.mailbox.done(Kr(R))))}case"Exit":{let S=I.requestId,b=c.get(S);if(!b)return oe;if(c.delete(S),b._tag==="Effect")return b.resume(I.exit),oe;return b.mailbox.done(D$(I.exit))}case"Defect":return u(Sm(I.defect));case"ClientEnd":return oe}},y;if(t.flatten){let I=new Map;y=function(b,R,D){let q=I.get(b);if(!q)q=A(e.requests.get(b)),I.set(b,q);return q(R,D)}}else{y={};for(let I of e.requests.values()){let S=I._tag.indexOf("."),b=S===-1?void 0:I._tag.slice(0,S);if(b!==void 0&&!(b in y))y[b]={};let R=b!==void 0?y[b]:y,D=b!==void 0?I._tag.slice(S+1):I._tag;R[D]=A(I)}}return{client:y,write:x}}),XJe=qB(-503,0);var gfe=me("@effect/rpc/RpcClient/currentHeaders",()=>$u(Bg));var Cfe=/\+/g,yfe=function(){};yfe.prototype=Object.create(null);function xfe(e){let t=new yfe;if(typeof e!=="string")return t;let r=e.length,n="",o="",s=-1,i=-1,a=!1,c=!1,l=!1,u=!1,A=!1,p=0;for(let f=0;f<r+1;f++)if(p=f!==r?e.charCodeAt(f):38,p===38){if(A=i>s,!A)i=f;if(n=e.slice(s+1,i),A||n.length>0){if(l)n=n.replace(Cfe," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(A){if(o=e.slice(i+1,f),u)o=o.replace(Cfe," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let h=t[n];if(h===void 0)t[n]=o;else if(h.pop)h.push(o);else t[n]=[h,o]}o="",s=f,i=f,a=!1,c=!1,l=!1,u=!1}else if(p===61)if(i<=s)i=f;else c=!0;else if(p===43)if(i>s)u=!0;else l=!0;else if(p===37)if(i>s)c=!0;else a=!0;return t}var rze=/^https?:\/\/.*?\//,HW=/(\/:[^/()]*?)\?(\/?)/,Qfe=(e={})=>new bfe(e);class bfe{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(HW);if(n&&n.index!==void 0){nze(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let s=t.replace(HW,"$1$2"),i=t.replace(HW,"$2");this.on(e,s,r),this.on(e,i,r);return}if(this.options.ignoreDuplicateSlashes)t=Ife(t);if(this.options.ignoreTrailingSlash)t=Sfe(t);let o=typeof e==="string"?[e]:e;for(let s of o)this._on(s,t,r)}all(e,t){this.on(lze,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new eS("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new eS(""),this.trees[e].staticChildren["/"]=c}let o=this.trees[e].prefix.length,s=this.trees[e],i=[];for(let c=0;c<=n.length;c++){if(n.charCodeAt(c)===58&&n.charCodeAt(c+1)===58){c++;continue}let l=n.charCodeAt(c)===58&&n.charCodeAt(c+1)!==58,u=n.charCodeAt(c)===42;if(l||u||c===n.length&&c!==o){let A=n.slice(o,c);if(!this.options.caseSensitive)A=A.toLowerCase();A=A.split("::").join(":"),A=A.split("%").join("%25"),s=s.createStaticChild(A)}if(l){let A=!1,p=[],f=c+1;for(let h=f;;h++){let E=n.charCodeAt(h),x=E===40,y=E===45||E===46,I=E===47||h===n.length;if(x||y||I){let S=n.slice(f,h);if(i.push(S),A=A||x||y,x){let D=sze(n,h),q=n.slice(h,D+1);p.push(ize(q)),h=D+1}else p.push("(.*?)");let b=h;for(;h<n.length;h++){let D=n.charCodeAt(h);if(D===47)break;if(D===58)if(n.charCodeAt(h+1)===58)h++;else break}let R=n.slice(b,h);if(R)R=R.split("::").join(":"),R=R.split("%").join("%25"),p.push(aze(R));if(f=h+1,I||n.charCodeAt(h)===47||h===n.length){let D=A?"()"+R:R,q=n.slice(c,h);n=n.slice(0,c+1)+D+n.slice(h),c+=D.length;let k=A?new RegExp("^"+p.join("")+"$"):void 0;s=s.createParametricChild(k,R,q),o=c+1;break}}}}else if(u){if(i.push("*"),s=s.createWildcardChild(),o=c+1,c!==n.length-1)throw Error("Wildcard must be the last character in the route")}}if(!this.options.caseSensitive)n=n.toLowerCase();if(n==="*")n="/*";for(let c of this.routes)if(c.method===e&&c.pattern===n)throw Error(`Method '${e}' already declared for route '${n}'`);let a={method:e,path:t,pattern:n,params:i,handler:r};this.routes.push(a),s.addRoute(a)}has(e,t){let r=this.trees[e];if(r===void 0)return!1;let n=r.getStaticChild(t);if(n===void 0)return!1;return n.isLeafNode}find(e,t){let r=this.trees[e];if(r===void 0)return;if(t.charCodeAt(0)!==47)t=t.replace(rze,"/");if(this.options.ignoreDuplicateSlashes)t=Ife(t);let n,o,s;try{n=cze(t),t=n.path,o=n.querystring,s=n.shouldDecodeParam}catch(p){return}if(this.options.ignoreTrailingSlash)t=Sfe(t);let i=t;if(this.options.caseSensitive===!1)t=t.toLowerCase();let a=this.options.maxParamLength,c=r.prefix.length,l=[],u=t.length,A=[];while(!0){if(c===u&&r.isLeafNode){let f=r.handlerStorage?.find();if(f!==void 0)return{handler:f.handler,params:f.createParams(l),searchParams:xfe(o)}}let p=r.getNextNode(t,c,A,l.length);if(p===void 0){if(A.length===0)return;let f=A.pop();c=f.brotherPathIndex,l.splice(f.paramsCount),p=f.brotherNode}if(r=p,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let f=i.slice(c);if(s)f=Bfe(f);l.push(f),c=u;continue}if(r._tag==="ParametricNode"){let f=i.indexOf("/",c);if(f===-1)f=u;let h=i.slice(c,f);if(s)h=Bfe(h);if(r.regex!==void 0){let E=r.regex.exec(h);if(E===null)continue;for(let x=1;x<E.length;x++){let y=E[x];if(y.length>a)return;l.push(y)}}else{if(h.length>a)return;l.push(h)}c=f}}}}class wfe{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:oze(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class WW{isLeafNode=!1;routes;handlerStorage;addRoute(e){if(this.routes===void 0)this.routes=[e];else this.routes.push(e);if(this.handlerStorage===void 0)this.handlerStorage=new wfe;this.isLeafNode=!0,this.handlerStorage.add(e)}}class qW extends WW{staticChildren={};findStaticMatchingChild(e,t){let r=this.staticChildren[e.charAt(t)];if(r===void 0||!r.matchPrefix(e,t))return;return r}getStaticChild(e,t=0){if(e.length===t)return this;let r=this.findStaticMatchingChild(e,t);if(r===void 0)return;return r.getStaticChild(e,t+r.prefix.length)}createStaticChild(e){if(e.length===0)return this;let t=this.staticChildren[e.charAt(0)];if(t){let n=1;for(;n<t.prefix.length;n++)if(e.charCodeAt(n)!==t.prefix.charCodeAt(n)){t=t.split(this,n);break}return t.createStaticChild(e.slice(n))}let r=e.charAt(0);return this.staticChildren[r]=new eS(e),this.staticChildren[r]}}class eS extends qW{_tag="StaticNode";constructor(e){super();this.setPrefix(e)}prefix;matchPrefix;parametricChildren=[];wildcardChild;setPrefix(e){if(this.prefix=e,e.length===1)this.matchPrefix=(t,r)=>!0;else{let t=e.length;this.matchPrefix=function(r,n){for(let o=1;o<t;o++)if(r.charCodeAt(n+o)!==this.prefix.charCodeAt(o))return!1;return!0}}}getParametricChild(e){if(e===void 0)return this.parametricChildren.find((r)=>r.isRegex===!1);let t=e.source;return this.parametricChildren.find((r)=>{if(r.regex===void 0)return!1;return r.regex.source===t})}createParametricChild(e,t,r){let n=this.getParametricChild(e);if(n!==void 0)return n.nodePaths.add(r),n;return n=new Rfe(e,t,r),this.parametricChildren.push(n),this.parametricChildren.sort((o,s)=>{if(!o.isRegex)return 1;if(!s.isRegex)return-1;if(o.staticSuffix===void 0)return 1;if(s.staticSuffix===void 0)return-1;if(s.staticSuffix.endsWith(o.staticSuffix))return 1;if(o.staticSuffix.endsWith(s.staticSuffix))return-1;return 0}),n}createWildcardChild(){if(this.wildcardChild===void 0)this.wildcardChild=new Dfe;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new eS(r);return o.staticChildren[n.charAt(0)]=this,e.staticChildren[r.charAt(0)]=o,o}getNextNode(e,t,r,n){let o=this.findStaticMatchingChild(e,t),s=0;if(o===void 0){if(this.parametricChildren.length===0)return this.wildcardChild;o=this.parametricChildren[0],s=1}if(this.wildcardChild!==void 0)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.wildcardChild});for(let i=this.parametricChildren.length-1;i>=s;i--)r.push({paramsCount:n,brotherPathIndex:t,brotherNode:this.parametricChildren[i]});return o}}class Rfe extends qW{regex;staticSuffix;_tag="ParametricNode";constructor(e,t,r){super();this.regex=e,this.staticSuffix=t,this.isRegex=!!e,this.nodePaths=new Set([r])}isRegex;nodePaths;getNextNode(e,t){return this.findStaticMatchingChild(e,t)}}class Dfe extends WW{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var nze=(e,t)=>{if(!e)throw Error(t)};function Ife(e){return e.replace(/\/\/+/g,"/")}function Sfe(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function oze(e){let t=e.length;return function(r){let n={};for(let o=0;o<t;o++)n[e[o]]=r[o];return n}}function sze(e,t){let r=1;while(t<e.length){if(t++,e[t]==="\\"){t++;continue}if(e[t]===")")r--;else if(e[t]==="(")r++;if(!r)return t}throw TypeError('Invalid regexp expression in "'+e+'"')}function ize(e){if(e.charCodeAt(1)===94)e=e.slice(0,1)+e.slice(2);if(e.charCodeAt(e.length-2)===36)e=e.slice(0,e.length-2)+e.slice(e.length-1);return e}function aze(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kfe(e,t){if(e===50){if(t===53)return"%";if(t===51)return"#";if(t===52)return"$";if(t===54)return"&";if(t===66)return"+";if(t===98)return"+";if(t===67)return",";if(t===99)return",";if(t===70)return"/";if(t===102)return"/";return}if(e===51){if(t===65)return":";if(t===97)return":";if(t===66)return";";if(t===98)return";";if(t===68)return"=";if(t===100)return"=";if(t===70)return"?";if(t===102)return"?";return}if(e===52&&t===48)return"@";return}function cze(e){let t=!1,r=!1,n="";for(let s=1;s<e.length;s++){let i=e.charCodeAt(s);if(i===37){let a=e.charCodeAt(s+1),c=e.charCodeAt(s+2);if(kfe(a,c)===void 0)t=!0;else{if(r=!0,a===50&&c===53)t=!0,e=e.slice(0,s+1)+"25"+e.slice(s+1),s+=2;s+=2}}else if(i===63||i===59||i===35){n=e.slice(s+1),e=e.slice(0,s);break}}return{path:t?decodeURI(e):e,querystring:n,shouldDecodeParam:r}}function Bfe(e){let t=e.indexOf("%");if(t===-1)return e;let r="",n=t;for(let o=t;o<e.length;o++)if(e.charCodeAt(o)===37){let s=e.charCodeAt(o+1),i=e.charCodeAt(o+2),a=kfe(s,i);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var lze=["ACL","BIND","CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LINK","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCALENDAR","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REBIND","REPORT","SEARCH","SOURCE","SUBSCRIBE","TRACE","UNBIND","UNLINK","UNLOCK","UNSUBSCRIBE"];var Tfe=Qfe;var Mfe=(e,t)=>{let r=t.definitionPath??"#/$defs/",n=(a)=>r+a,o=t.target??"jsonSchema7",s=t.topLevelReferenceStrategy??"keep",i=t.additionalPropertiesStrategy??"strict";return rn(e,t.definitions,"handle-identifier",[],{getRef:n,target:o,topLevelReferenceStrategy:s,additionalPropertiesStrategy:i},"handle-annotation","handle-errors")},tS={$id:"/schemas/never",not:{}},Vd={$id:"/schemas/any"},_fe={$id:"/schemas/unknown"},Ufe={$id:"/schemas/void"},pze={$id:"/schemas/object",anyOf:[{type:"object"},{type:"array"}]},fze={$id:"/schemas/%7B%7D",anyOf:[{type:"object"},{type:"array"}]};function vfe(e){if(e!==void 0)return Bt(Zu(e))}function Lfe(e){if(e!==void 0)return Bt(Ly(e))}function Pfe(e){if(e!==void 0)return e9(e);return U()}function dze(e,t){return aR(e,!1)(t)}function Hfe(e){if(e!==void 0)return Bt(X5(e))}function hze(e,t){let r=aR(e,!1),n=tu(t,(o)=>r(o).pipe(xs(iT)));return n.length>0?n:void 0}function Ofe(e,t,r){if(t!==void 0)switch(e._tag){case"StringKeyword":return t!==Vm.annotations[r]?t:void 0;case"NumberKeyword":return t!==Jm.annotations[r]?t:void 0;case"BooleanKeyword":return t!==zm.annotations[r]?t:void 0}return t}function iT(e,t=new Set){if(e===null||typeof e==="string"||typeof e==="number"||typeof e==="boolean")return!0;if(Array.isArray(e)||typeof e==="object"){if(t.has(e))return!1;t.add(e);try{if(Array.isArray(e))return e.every((n)=>iT(n,t));let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return!1;if(Object.getOwnPropertySymbols(e).length>0)return!1;return Object.values(e).every((n)=>iT(n,t))}finally{t.delete(e)}}return!1}function Wfe(e,t,r,n,o){let s={};if(t!==void 0)s.description=t;if(r!==void 0)s.title=r;if(fe(n)){let i=dze(e,n.value);if(fe(i)&&iT(i.value))s.default=i.value}if(o!==void 0){let i=hze(e,o);if(i!==void 0)s.examples=i}if(Object.keys(s).length===0)return;return s}function GW(e,t){return Wfe(e,vfe(t),Lfe(t),Pfe(t),Hfe(t))}function qfe(e){return Wfe(e,Ofe(e,vfe(e),ui),Ofe(e,Lfe(e),zn),Pfe(e),Hfe(e))}function YW(e,t){if(t){if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}return e}var aT=(e)=>{if(ot(wv(e)))return Pv(e,aT,(t)=>aT(t.from))},mze=(e)=>e.annotations[Df]===Jw,gze=(e,t)=>{if(Za(e)){if(e.annotations[Df]===Hw)return"type"in t&&t.type!=="integer"}return"type"in t||"oneOf"in t||"anyOf"in t||"$ref"in t},Eze=(e,t,r)=>{let n={...e,...qfe(r),...t};n.allOf??=[];let o=(s,i)=>{if(s in t&&s in e)n.allOf.unshift({[s]:e[s]}),n.allOf=n.allOf.filter(i)};if(o("minLength",(s)=>s.minLength>t.minLength),o("maxLength",(s)=>s.maxLength<t.maxLength),o("pattern",(s)=>s.pattern!==t.pattern),o("minItems",(s)=>s.minItems>t.minItems),o("maxItems",(s)=>s.maxItems<t.maxItems),o("minimum",(s)=>s.minimum>t.minimum),o("maximum",(s)=>s.maximum<t.maximum),o("exclusiveMinimum",(s)=>s.exclusiveMinimum>t.exclusiveMinimum),o("exclusiveMaximum",(s)=>s.exclusiveMaximum<t.exclusiveMaximum),o("multipleOf",(s)=>s.multipleOf!==t.multipleOf),n.allOf.length===0)delete n.allOf;return n};function Cze(e){switch(e.target){case"jsonSchema7":return!1;case"jsonSchema2019-09":case"jsonSchema2020-12":case"openApi3.1":return!0}}function yze(e){switch(e.additionalPropertiesStrategy){case"allow":return!0;case"strict":return!1}}function Zt(e,t){return Gfe(e,qfe(t))}function Gfe(e,t){if(t===void 0||Object.keys(t).length===0)return e;if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}function VW(e){let t=Bt(Dv(e));if(t===void 0){if(Nv(e))return VW(e.f());if(eR(e)&&Wy(e.from)&&i9(e.to)){let r=e.to,n=il(r);if(fe(n))return VW(r)}}return t}function rn(e,t,r,n,o,s,i){if(r==="handle-identifier"&&(o.topLevelReferenceStrategy!=="skip"||Nv(e))){let c=VW(e);if(c!==void 0){let l=c.replace(/~/ig,"~0").replace(/\//ig,"~1"),u={$ref:o.getRef(l)};if(!jO(t,c))t[c]=u,t[c]=rn(e,t,"ignore-identifier",n,o,"handle-annotation",i);return u}}if(s==="handle-annotation"){let c=wv(e);if(fe(c)){let l=c.value;if(gze(e,l))switch(e._tag){case"Declaration":return Zt(l,e);default:return l}else switch(e._tag){case"Refinement":{let u=My(e);if(u===void 0)return Eze(rn(e.from,t,r,n,o,"handle-annotation",i),l,e);else return rn(u,t,r,n,o,"handle-annotation",i)}default:return{...rn(e,t,r,n,o,"ignore-annotation",i),...l}}}}let a=il(e);if(fe(a))return rn(a.value,t,r,n,o,"handle-annotation",i);switch(e._tag){case"Declaration":case"UndefinedKeyword":case"BigIntKeyword":case"UniqueSymbol":case"SymbolKeyword":{if(i==="ignore-errors")return Zt(Vd,e);throw Error(cv(n,e))}case"Suspend":{if(r==="handle-identifier"){if(i==="ignore-errors")return Zt(Vd,e);throw Error(O5(n,e))}return rn(e.f(),t,"ignore-identifier",n,o,"handle-annotation",i)}case"NeverKeyword":return Zt(tS,e);case"VoidKeyword":return Zt(Ufe,e);case"UnknownKeyword":return Zt(_fe,e);case"AnyKeyword":return Zt(Vd,e);case"ObjectKeyword":return Zt(pze,e);case"StringKeyword":return Zt({type:"string"},e);case"NumberKeyword":return Zt({type:"number"},e);case"BooleanKeyword":return Zt({type:"boolean"},e);case"Literal":{let c=e.literal;if(c===null)return Zt({type:"null"},e);else if(Ut(c))return Zt({type:"string",enum:[c]},e);else if(On(c))return Zt({type:"number",enum:[c]},e);else if(gs(c))return Zt({type:"boolean",enum:[c]},e);if(i==="ignore-errors")return Zt(Vd,e);throw Error(cv(n,e))}case"Enums":{let c=e.enums.map((l)=>({type:On(l[1])?"number":"string",title:l[0],enum:[l[1]]}));return c.length>=1?Zt({$comment:"/schemas/enums",anyOf:c},e):Zt(tS,e)}case"TupleType":{let c=e.elements.map((f,h)=>YW(rn(f.type,t,"handle-identifier",n.concat(h),o,"handle-annotation",i),GW(f.type,f))),l=e.rest.map((f)=>YW(rn(f.type,t,"handle-identifier",n,o,"handle-annotation",i),GW(f.type,f))),u={type:"array"},A=e.elements.length;if(A>0)if(u.minItems=A-e.elements.filter((f)=>f.isOptional).length,o.target==="jsonSchema7")u.items=c;else u.prefixItems=c;let p=l.length;if(p>0){let f=l[0];if(p===1&&e.elements.every((E)=>E.type===e.rest[0].type))if(o.target==="jsonSchema7")u.items=f;else u.items=f,delete u.prefixItems;else if(o.target==="jsonSchema7")u.additionalItems=f;else u.items=f;if(p>1){if(i==="ignore-errors")return Zt(Vd,e);throw Error(F5(n))}}else if(A>0)if(o.target==="jsonSchema7")u.additionalItems=!1;else u.items=!1;else u.maxItems=0;return Zt(u,e)}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return Zt(fze,e);let c={type:"object",required:[],properties:{},additionalProperties:yze(o)},l=void 0,u=void 0;for(let A of e.indexSignatures){let p=aT(A.type)??A.type,f=A.parameter;switch(f._tag){case"StringKeyword":{c.additionalProperties=rn(p,t,"handle-identifier",n,o,"handle-annotation",i);break}case"TemplateLiteral":{l=rn(p,t,"handle-identifier",n,o,"handle-annotation",i),u={type:"string",pattern:Zm(f).source};break}case"Refinement":{l=rn(p,t,"handle-identifier",n,o,"handle-annotation",i),u=rn(f,t,"handle-identifier",n,o,"handle-annotation",i);break}case"SymbolKeyword":{let h=n.concat("[symbol]");c.additionalProperties=rn(p,t,"handle-identifier",h,o,"handle-annotation",i),u=rn(f,t,"handle-identifier",h,o,"handle-annotation",i);break}}}for(let A=0;A<e.propertySignatures.length;A++){let p=e.propertySignatures[A],f=p.name;if(Ut(f)){let h=aT(p.type),E=h??p.type;if(c.properties[f]=YW(rn(E,t,"handle-identifier",n.concat(p.name),o,"handle-annotation",i),GW(E,p)),!p.isOptional&&h===void 0)c.required.push(f)}else{if(i==="ignore-errors")return Zt(Vd,e);throw Error(N5(f,n))}}if(l!==void 0)delete c.additionalProperties,c.patternProperties={"":l};if(u!==void 0)c.propertyNames=u;return Zt(c,e)}case"Union":{let c=e.types.map((u)=>rn(u,t,"handle-identifier",n,o,"handle-annotation",i)),l=Qze(c);switch(l.length){case 0:return tS;case 1:return Zt(l[0],e);default:return Zt({anyOf:l},e)}}case"Refinement":return rn(e.from,t,r,n,o,"handle-annotation",i);case"TemplateLiteral":{let c=Zm(e);return Zt({type:"string",title:String(e),description:"a template literal",pattern:c.source},e)}case"Transformation":{if(mze(e.from)){let l={type:"string",contentMediaType:"application/json"};if(Cze(o))l.contentSchema=rn(e.to,t,r,n,o,"handle-annotation",i);return l}let c=rn(e.from,t,r,n,o,"handle-annotation",i);if(e.transformation._tag==="TypeLiteralTransformation"&&Ffe(c)){let l=rn(e.to,{},"ignore-identifier",n,o,"handle-annotation","ignore-errors");if(Ffe(l))for(let u of e.transformation.propertySignatureTransformations){let{to:A,from:p}=u;if(Ut(A)&&Ut(p)){let f=l.properties[A];if(zl(f)){let h=c.properties[p];if(zl(h)){let E={};if(Ut(f.title))E.title=f.title;if(Ut(f.description))E.description=f.description;if(Array.isArray(f.examples))E.examples=f.examples;if(Object.hasOwn(f,"default")&&f.default!==void 0)E.default=f.default;c.properties[p]=Gfe(h,E)}}}}}return Zt(c,e)}}}function Ffe(e){return zl(e)&&e.type==="object"&&zl(e.properties)}function xze(e){return e===tS||te(e,"$id")&&e.$id===tS.$id&&Object.keys(e).length===3&&e.title===Ff.annotations[zn]}function Ize(e){return"$id"in e&&e.$id===Vd.$id}function Sze(e){return"$id"in e&&e.$id===_fe.$id}function Bze(e){return"$id"in e&&e.$id===Ufe.$id}function Nfe(e){return te(e,"enum")&&"type"in e&&Object.keys(e).length===2}function Qze(e){let t=[];for(let r of e){if(xze(r))continue;if(Ize(r)||Sze(r)||Bze(r))return[r];if(Nfe(r)&&t.length>0){let n=t[t.length-1];if(Nfe(n)&&n.type===r.type){t[t.length-1]={type:n.type,enum:[...n.enum,...r.enum]};continue}}t.push(r)}return t}var wze={add(...e){return VA({requests:Yfe(...this.requests.values(),...e),annotations:this.annotations})},merge(...e){let t=new Map(this.requests),r=new Map(this.annotations.unsafeMap);for(let n of e){for(let[o,s]of n.requests)t.set(o,s);for(let[o,s]of n.annotations.unsafeMap)r.set(o,s)}return VA({requests:t,annotations:Rh(r)})},middleware(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.middleware(e));return VA({requests:t,annotations:this.annotations})},toHandlersContext(e){return Ze(this,function*(){let t=yield*Rn(),r=Qn(e)?yield*e:e,n=new Map;for(let[o,s]of Object.entries(r)){let i=this.requests.get(o);n.set(i.key,{handler:s,context:t})}return Rh(n)})},prefix(e){let t=new Map;for(let r of this.requests.values()){let n=r.prefix(e);t.set(n._tag,n)}return VA({requests:t,annotations:this.annotations})},toLayer(e){return Dy(this.toHandlersContext(e))},of:Z,toLayerHandler(e,t){return Dy(Ze(this,function*(){let r=yield*Rn(),n=Qn(t)?yield*t:t,o=new Map,s=this.requests.get(e);return o.set(s.key,{handler:n,context:r}),Rh(o)}))},accessHandler(e){return vU((t)=>{let r=this.requests.get(e),{context:n,handler:o}=t.unsafeMap.get(r.key);return(s,i)=>{let a=o(s,i),c=hfe(a)?a.value:a;return Qn(c)?Xo(c,n):ID(c,n)}})},annotate(e,t){return VA({requests:this.requests,annotations:Ar(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsContext(Oc(e,t))},annotateContext(e){return VA({requests:this.requests,annotations:Jr(this.annotations,e)})},annotateRpcsContext(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.annotateContext(Jr(e,n.annotations)));return VA({requests:t,annotations:this.annotations})}},VA=(e)=>Object.assign(function(){},wze,{requests:e.requests,annotations:e.annotations}),Yfe=(...e)=>{let t=new Map;for(let r of e)t.set(r._tag,dn(r)?dfe(r):r);return t},Vfe=(...e)=>VA({requests:Yfe(...e),annotations:Mr()});var Dze=Ie(m,K),Jfe=Ie(m,K);class _l extends B({_meta:M(B({progressToken:M(Jfe)}))}){}class JA extends B({_meta:M(hn({key:m,value:bt}))}){}class zA extends B({_meta:M(hn({key:m,value:bt}))}){}var zfe=m;class kze extends B({..._l.fields,cursor:M(zfe)}){}class rS extends B({...JA.fields,nextCursor:M(zfe)}){}var jfe=N("user","assistant");class Jd extends B({audience:M(be(jfe)),priority:M(K.pipe(gR(0,1)))}){}class JW extends B({name:m,title:M(m),version:m}){}class $fe extends we("@effect/ai/McpSchema/ClientCapabilities")({experimental:M(hn({key:m,value:B({})})),roots:M(B({listChanged:M(se)})),sampling:M(B({})),elicitation:M(B({}))}){}class Kfe extends B({experimental:M(hn({key:m,value:B({})})),logging:M(B({})),completions:M(B({})),prompts:M(B({listChanged:M(se)})),resources:M(B({subscribe:M(se),listChanged:M(se)})),tools:M(B({listChanged:M(se)}))}){}class hs extends we("@effect/ai/McpSchema/McpError")({code:K,message:m,data:M(bt)}){}var Tze=-32600,Oze=-32601,Fze=-32602,Nze=-32603,Mze=-32700;class _ze extends at()("ParseError",{...hs.fields,code:di(Mze)}){}class Uze extends at()("InvalidRequest",{...hs.fields,code:di(Tze)}){}class vze extends at()("MethodNotFound",{...hs.fields,code:di(Oze)}){}class nS extends at()("InvalidParams",{...hs.fields,code:di(Fze)}){}class yE extends at()("InternalError",{...hs.fields,code:di(Nze)}){static notImplemented=new yE({message:"Not implemented"})}class Zfe extends we("@effect/ai/McpSchema/InitializeResult")({...JA.fields,protocolVersion:m,capabilities:Kfe,serverInfo:JW,instructions:M(m)}){}class Lze extends mo("initialize",{success:Zfe,error:hs,payload:{..._l.fields,protocolVersion:m,capabilities:$fe,clientInfo:JW}}){}class Xfe extends mo("notifications/cancelled",{payload:{...zA.fields,requestId:Dze,reason:M(m)}}){}class ede extends mo("notifications/progress",{payload:{...zA.fields,progressToken:Jfe,progress:M(K),total:M(K),message:M(m)}}){}class oS extends we("@effect/ai/McpSchema/Resource")({uri:m,name:m,title:M(m),description:M(m),mimeType:M(m),annotations:M(Jd),size:M(K)}){}class cT extends we("@effect/ai/McpSchema/ResourceTemplate")({uriTemplate:m,name:m,title:M(m),description:M(m),mimeType:M(m),annotations:M(Jd)}){}class zW extends B({uri:m,mimeType:M(m)}){}class jW extends B({...zW.fields,text:m}){}class $W extends B({...zW.fields,blob:yR}){}class tde extends we("@effect/ai/McpSchema/ListResourcesResult")({...rS.fields,resources:be(oS)}){}class rde extends we("@effect/ai/McpSchema/ListResourceTemplatesResult")({...rS.fields,resourceTemplates:be(cT)}){}class nde extends B({...JA.fields,contents:be(Ie(jW,$W))}){}class Pze extends mo("resources/read",{success:nde,error:hs,payload:{..._l.fields,uri:m}}){}class ode extends mo("notifications/resources/list_changed",{payload:Al(zA)}){}class Hze extends mo("resources/subscribe",{error:hs,payload:{..._l.fields,uri:m}}){}class Wze extends mo("resources/unsubscribe",{error:hs,payload:{..._l.fields,uri:m}}){}class sde extends mo("notifications/resources/updated",{payload:{...zA.fields,uri:m}}){}class ide extends B({name:m,title:M(m),description:M(m),required:M(se)}){}class KW extends we("@effect/ai/McpSchema/Prompt")({name:m,title:M(m),description:M(m),arguments:M(be(ide))}){}class ZW extends B({type:di("text"),text:m,annotations:M(Jd)}){}class ade extends B({type:di("image"),data:yR,mimeType:m,annotations:M(Jd)}){}class cde extends B({type:di("audio"),data:yR,mimeType:m,annotations:M(Jd)}){}class lde extends B({type:di("resource"),resource:Ie(jW,$W),annotations:M(Jd)}){}class ude extends B({...oS.fields,type:di("resource_link")}){}class XW extends Ie(ZW,ade,cde,lde,ude){}class Ade extends B({role:jfe,content:XW}){}class pde extends we("@effect/ai/McpSchema/ListPromptsResult")({...rS.fields,prompts:be(KW)}){}class eq extends we("@effect/ai/McpSchema/GetPromptResult")({...JA.fields,messages:be(Ade),description:M(m)}){}class qze extends mo("prompts/get",{success:eq,error:hs,payload:{..._l.fields,name:m,title:M(m),arguments:M(hn({key:m,value:m}))}}){}class fde extends mo("notifications/prompts/list_changed",{payload:Al(zA)}){}class lT extends we("@effect/ai/McpSchema/ToolAnnotations")({title:M(m),readOnlyHint:C(se,{default:()=>!1}),destructiveHint:C(se,{default:()=>!0}),idempotentHint:C(se,{default:()=>!1}),openWorldHint:C(se,{default:()=>!0})}){}class uT extends we("@effect/ai/McpSchema/Tool")({name:m,title:M(m),description:M(m),inputSchema:bt,annotations:M(lT)}){}class dde extends we("@effect/ai/McpSchema/ListToolsResult")({...rS.fields,tools:be(uT)}){}class sS extends we("@effect/ai/McpSchema/CallToolResult")({...JA.fields,content:be(XW),structuredContent:M(bt),isError:M(se)}){}class Gze extends mo("tools/call",{success:sS,error:hs,payload:{..._l.fields,name:m,arguments:hn({key:m,value:bt})}}){}class hde extends mo("notifications/tools/list_changed",{payload:Al(zA)}){}var mde=N("debug","info","notice","warning","error","critical","alert","emergency");class Yze extends mo("logging/setLevel",{payload:{..._l.fields,level:mde},error:hs}){}class gde extends mo("notifications/message",{payload:B({...zA.fields,level:mde,logger:M(m),data:bt})}){}class iS extends we("@effect/ai/McpSchema/CompleteResult")({completion:B({values:be(m),total:M(K),hasMore:M(se)})}){static empty=iS.make({completion:{values:[],total:0,hasMore:!1}})}class Ede extends we("@effect/ai/McpSchema/ElicitAcceptResult")({...JA.fields,action:N("accept"),content:bt}){}class Cde extends we("@effect/ai/McpSchema/ElicitDeclineResult")({...JA.fields,action:N("cancel","decline")}){}var Vze=Ie(Ede,Cde);class tq extends mo("elicitation/create",{success:Vze,error:hs,payload:{message:m,requestedSchema:bt}}){}class yde extends at("@effect/ai/McpSchema/ElicitationDeclined")("ElicitationDeclined",{request:tq.payloadSchema,cause:M(Pt)}){}class rq extends Vfe(Xfe,ede,gde,sde,ode,hde,fde){}var xde=Symbol.for("@effect/ai/McpSchema/ParamNameId");var Jze="~@effect/ai/Tool",Ide="~@effect/ai/Tool/ProviderDefined";var Sde={[Jze]:{_Requirements:Z},pipe(){return v(this,arguments)},addDependency(){return jA({...this})},setParameters(e){return jA({...this,parametersSchema:dn(e)?e:B(e)})},setSuccess(e){return jA({...this,successSchema:e})},setFailure(e){return jA({...this,failureSchema:e})},annotate(e,t){return jA({...this,annotations:Ar(this.annotations,e,t)})},annotateContext(e){return jA({...this,annotations:Jr(this.annotations,e)})}},_wt={...Sde,[Ide]:Ide},jA=(e)=>{let t=Object.assign(Object.create(Sde),e);return t.id=`@effect/ai/Tool/${e.name}`,t};var zze=B({}),nq=(e,t)=>{let r=t?.success??ag,n=t?.failure??nA;return jA({name:e,description:t?.description,parametersSchema:t?.parameters?B(t?.parameters):zze,successSchema:r,failureSchema:n,failureMode:t?.failureMode??"error",annotations:Mr()})};var Bde=(e)=>jA({name:e._tag,description:Bt(Zu(e.ast.to)),parametersSchema:e,successSchema:e.success,failureSchema:e.failure,failureMode:"error",annotations:Mr()});class oq extends ba("@effect/ai/Tool/Title")(){}class xE extends Mn()("@effect/ai/Tool/Readonly",{defaultValue:Or}){}class IE extends Mn()("@effect/ai/Tool/Destructive",{defaultValue:Zn}){}class sq extends Mn()("@effect/ai/Tool/Idempotent",{defaultValue:Or}){}class iq extends Mn()("@effect/ai/Tool/OpenWorld",{defaultValue:Zn}){}class Ec extends ba("@effect/ai/McpServer")(){static make=Ze(function*(){let e=Kze(),t=Vr(),r=new Map,n=[],o=[],s=[],i=new Map,a=new Map,c=yield*hA(),l=new Map,u=yield*Efe(rq,{spanPrefix:"McpServer/Notifications",onFromClient(A){let p=A.message;if(p._tag!=="Request")return oe;if(p.tag.includes("list_changed")){if(!l.has(p.tag))l.set(p.tag,setTimeout(()=>{c.unsafeOffer(p),l.delete(p.tag)},0))}else c.unsafeOffer(p);return u.write({clientId:0,requestId:p.id,_tag:"Exit",exit:oi})}});return Ec.of({notifications:u.client,notificationsMailbox:c,initializedClients:new Set,get tools(){return t},addTool:(A)=>Me(()=>(t.push(A.tool),r.set(A.tool.name,A.handle),u.client["notifications/tools/list_changed"]({}))),callTool:(A)=>Me(()=>{let p=r.get(A.name);if(!p)return xe(new nS({message:`Tool '${A.name}' not found`}));return p(A.arguments)}),get resources(){return n},get resourceTemplates(){return o},addResource:(A,p)=>Me(()=>(n.push(A),e.add(A.uri,{_tag:"Resource",effect:p}),u.client["notifications/resources/list_changed"]({}))),addResourceTemplate:({completions:A,handle:p,routerPath:f,template:h})=>Me(()=>{o.push(h),e.add(f,{_tag:"ResourceTemplate",handle:p});for(let[E,x]of Object.entries(A))a.set(`ref/resource/${h.uriTemplate}/${E}`,x);return u.client["notifications/resources/list_changed"]({})}),findResource:(A)=>Me(()=>{let p=e.find(A);if(!p)return le({contents:[]});else if(p.handler._tag==="Resource")return p.handler.effect;let f=[];for(let h of Object.keys(p.params))f[Number(h)]=p.params[h];return p.handler.handle(A,f)}),get prompts(){return s},addPrompt:(A)=>Me(()=>{s.push(A.prompt),i.set(A.prompt.name,A.handle);for(let[p,f]of Object.entries(A.completions))a.set(`ref/prompt/${A.prompt.name}/${p}`,f);return u.client["notifications/prompts/list_changed"]({})}),getPromptResult:tr(function*({arguments:A,name:p}){let f=i.get(p);if(!f)return yield*new nS({message:`Prompt '${p}' not found`});return yield*f(A??{})}),completion:tr(function*(A){let p=A.ref,f=p.type==="ref/resource"?`ref/resource/${p.uri}/${A.argument.name}`:`ref/prompt/${p.name}/${A.argument.name}`,h=a.get(f);return h?yield*h(A.argument.value):iS.empty})})});static layer=zu(Ec,Ec.make)}var jze=tr(function*(e){let t=yield*Ec,r=yield*e,n=yield*Rn();for(let o of Object.values(r.tools)){let s=new uT({name:o.name,description:o.description,inputSchema:Xze(o.parametersSchema.ast),annotations:new lT({...yo(o.annotations,oq).pipe(Xt((i)=>({title:i})),Bt),readOnlyHint:pr(o.annotations,xE),destructiveHint:pr(o.annotations,IE),idempotentHint:pr(o.annotations,sq),openWorldHint:pr(o.annotations,iq)})});yield*t.addTool({tool:s,handle(i){return r.handle(o.name,i).pipe(Xo(n),bw({onFailure:(a)=>new sS({isError:!0,structuredContent:typeof a==="object"?a:void 0,content:[{type:"text",text:JSON.stringify(a)}]}),onSuccess:(a)=>new sS({isError:!1,structuredContent:typeof a.encodedResult==="object"?a.encodedResult:void 0,content:[{type:"text",text:JSON.stringify(a.encodedResult)}]})}))}})}}),$ze=(e)=>Dw(jze(e)).pipe(rs(Ec.layer)),Qde=function(){if(arguments.length===1){let o=arguments[0];return Ze(function*(){let s=yield*Rn();yield*(yield*Ec).addResource(new oS({...o,annotations:o}),o.content.pipe(Xo(s),re((a)=>bde(o.uri,a)),ao((a)=>{let c=Gb(a)[0];return new yE({message:c.message})})))})}let{params:e,routerPath:t,schema:r,uriPath:n}=Zze(...arguments);return tr(function*(o){let s=yield*Rn(),i=yield*Ec,a=os(r),c=new cT({...o,uriTemplate:n,annotations:o}),l={};for(let[u,A]of Object.entries(o.completion??{})){let p=Wf(be(e[u])),f=(h)=>A(h).pipe(T(p),re((E)=>new iS({completion:{values:E,total:E.length,hasMore:!1}})),ao((E)=>{let x=Gb(E)[0];return new yE({message:x.message})}),Xo(s));l[u]=f}yield*i.addResourceTemplate({template:c,routerPath:t,completions:l,handle:(u,A)=>a(A).pipe(_e((p)=>new nS({message:p.message})),T((p)=>o.content(u,...p).pipe(re((f)=>bde(u,f)),ao((f)=>{let h=Gb(f)[0];return new yE({message:h.message})}))),Xo(s))})})},wde=function(){if(arguments.length===1)return Dw(Qde(arguments[0])).pipe(rs(Ec.layer));let e=Qde(...arguments);return(t)=>Dw(e(t)).pipe(rs(Ec.layer))};var Kze=()=>{let e=Tfe({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(n,o)=>{e.on("GET",n,o)},find:(n)=>e.find("GET",n)}},Zze=(e,...t)=>{let r=e[0].replace(":","::"),n=e[0],o={},s=dR();if(t.length>0){let i=[];for(let a=0;a<t.length;a++){let c=t[a],l=e[a+1],u=String(a);i.push(c),r+=`:${u}${l.replace(":","::")}`;let A=Xr(xde)(c.ast).pipe(Ve(()=>`param${u}`));o[A]=c,n+=`{${A}}${l}`}s=dR(...i)}return{routerPath:r,uriPath:n,schema:s,params:o}};var Xze=(e)=>{if(Ny(e).length===0)return{type:"object",properties:{},required:[],additionalProperties:!1};let r={},n=Mfe(e,{definitions:r,topLevelReferenceStrategy:"skip"});if(Object.keys(r).length===0)return n;return n.$defs=r,n},bde=(e,t)=>{if(typeof t==="string")return{contents:[{uri:e,text:t}]};else if(t instanceof Uint8Array)return{contents:[{uri:e,blob:t}]};return t};var AT="~@effect/ai/AiError";class pT extends at("@effect/ai/AiError/MalformedInput")("MalformedInput",{module:m,method:m,description:M(m),cause:M(Pt)}){[AT]=AT}class cS extends at("@effect/ai/AiError/MalformedOutput")("MalformedOutput",{module:m,method:m,description:M(m),cause:M(Pt)}){[AT]=AT;static fromParseError({error:e,...t}){return new cS({...t,cause:e})}}var tje={...um,...Cs,of:Z,toContext(e){return Ze(this,function*(){let t=yield*Rn(),r=Qn(e)?yield*e:e,n=new Map;for(let[o,s]of Object.entries(r)){let i=this.tools[o];n.set(i.id,{handler:s,context:t})}return Rh(n)})},toLayer(e){return Dy(this.toContext(e))},commit(){return Ze(this,function*(){let e=this.tools,t=yield*Rn(),r=new WeakMap,n=(s)=>{let i=r.get(s);if(WE(i)){let a=t.unsafeMap.get(s.id),c=os(s.parametersSchema),l=Ie(s.successSchema,s.failureSchema),u=lX(l),A=Wf(l);i={context:a.context,handler:a.handler,decodeParameters:c,validateResult:u,encodeResult:A},r.set(s,i)}return i},o=Pe("Toolkit.handle",{captureStackTrace:!1})(function*(s,i){yield*z3({tool:s,parameters:i});let a=e[s];if(WE(a)){let f=Object.keys(e).join(",");return yield*new cS({module:"Toolkit",method:`${s}.handle`,description:`Failed to find tool with name '${s}' in toolkit - available tools: ${f}`})}let c=n(a),l=yield*_e(c.decodeParameters(i),(f)=>new cS({module:"Toolkit",method:`${s}.handle`,description:`Failed to decode tool call parameters for tool '${s}' from:
176
176
  '${JSON.stringify(i,void 0,2)}'`,cause:f})),{isFailure:u,result:A}=yield*c.handler(l).pipe(re((f)=>({result:f,isFailure:!1})),Un((f)=>a.failureMode==="error"?xe(f):le({result:f,isFailure:!0})),Ur(({result:f})=>c.validateResult(f)),xw((f)=>Jr(c.context,f)),_e((f)=>sR(f)?new pT({module:"Toolkit",method:`${s}.handle`,description:`Failed to validate tool call result for tool '${s}'`,cause:f}):f)),p=yield*_e(c.encodeResult(A),(f)=>new pT({module:"Toolkit",method:`${s}.handle`,description:`Failed to encode tool call result for tool '${s}'`,cause:f}));return{isFailure:u,result:A,encodedResult:p}});return{tools:e,handle:o}})},toJSON(){return{_id:"@effect/ai/Toolkit",tools:Array.from(Object.values(this.tools)).map((e)=>e.name)}},pipe(){return v(this,arguments)}},rje=(e)=>Object.assign(function(){},tje,{tools:e}),nje=(...e)=>{let t={};for(let r of e){let n=dn(r)?Bde(r):r;t[r.name]=n}return t};var oje=(...e)=>rje(nje(...e));import{homedir as zje}from"node:os";var zd="https://expand.land";function sje(e){return e.replace(/\/+$/,"")}function kde(e){return e!==null&&e!==void 0&&Number.isInteger(e)&&e>0&&e<=2147483647?e:void 0}function Dde(e){return e!==null&&e!==void 0&&Number.isInteger(e)&&e>=0&&e<=4294967295?e:void 0}function lS(e,t="https://expand.land"){return`${sje(t)}/s/${encodeURIComponent(e)}`}function Tde(e,t="https://expand.land"){return`${lS(e,t)}/appendix`}function Ode(e,t,r="https://expand.land"){let n=`${lS(e,r)}/content`,o=kde(t);return o===void 0?n:`${n}?id=${o}`}var ije=/^[A-Za-z0-9._~-]+$/u;function Fde(e){let t=e.trim();if(t.length===0)return;if(ije.test(t))return{snapshotId:t};try{let r=new URL(t),n=/^\/s\/([^/]+)/u.exec(r.pathname);if(!n?.[1])return;return{snapshotId:decodeURIComponent(n[1]),host:r.origin}}catch{return}}function aje(e){return new URL(e).origin}function SE(e,t){if(e==null)return t;try{return aje(e)}catch{return t}}function BE(e,t,r,n="https://expand.land"){let o=typeof t==="string",s=o?t:void 0,i=o?typeof r==="string"?void 0:r:t,c=lS(e,o?n:typeof r==="string"?r:"https://expand.land"),l=kde(i?.evidenceId);if(l!==void 0)return`${c}?id=${l}`;if(s==="statejson"){let u=Dde(i?.stateJsonSourceId);return u===void 0?c:`${c}?id=${u}`}if(s==="markdown"||s==="appendix"){let u=Dde(i?.nodeIds?.[0]);return u===void 0?c:`${c}/playground#focus=${u}`}return c}var lhe=DO(ihe(),1);class Bq extends at()("CredentialStorageLockError",{error:Pt}){get message(){return"Could not lock credential storage. Try again shortly."}}var ahe=$u(new Set);function che(e,t){if(typeof e!=="object"||e===null||!("code"in e))return!1;return e.code===t}function Vje(e){return che(e.error,"ERELEASED")||che(e.error,"ENOTACQUIRED")}var vl=tr(function*(e,t,r=`${e}.lock`){let n=yield*Zbe(ahe);if(n.has(e))return yield*t;return yield*Yu(Zo({try:()=>lhe.lock(e,{realpath:!1,lockfilePath:r,onCompromised:()=>{return}}),catch:(o)=>new Bq({error:o})}).pipe(Ey({schedule:ov("25 millis"),times:400,while:({error:o})=>o instanceof Error&&("code"in o)&&o.code==="ELOCKED"})),()=>PU(t,ahe,new Set([...n,e])),(o)=>Zo({try:()=>o(),catch:(s)=>new Bq({error:s})}).pipe(Un((s)=>Vje(s)?oe:Ko(s))))});var Qq=Pe("runNonInteractiveCommand")(function*(e){let t=yield*e.pipe(bD(L0e),J0e("pipe"),V0e("inherit"),Y0e),[r]=yield*Gu([t.exitCode,P0e(t.stdout)],{concurrency:"unbounded"});return r},wo);function uhe(e,t,r,n){return wo(Ze(function*(){let o=yield*e.open(t,{flag:"wx",mode:n}),s=yield*o.stat,i={dev:s.dev,ino:Bt(s.ino),mode:s.mode,type:s.type},a=yield*Zr(o.writeAll(new TextEncoder().encode(r)).pipe(Ue(o.sync)));if(Jo(a))return{identity:i,writeExit:a,pathMatchesHandle:!1};let c=yield*e.stat(t),l=RE(i,{exists:!0,dev:c.dev,ino:Bt(c.ino),type:c.type});return{identity:i,writeExit:a,pathMatchesHandle:l}}))}function RE(e,t){return t.exists&&t.dev===e.dev&&t.ino===e.ino&&t.type===e.type}import{homedir as Jje}from"node:os";var Ahe=Ze(function*(){let e=yield*Fo;return yield*Bo("XDG_CONFIG_HOME").pipe(rf(""),cm((t)=>t.trim()===""?e.join(Jje(),".config"):t))});var bT="https://api.expand.ai",jje="https://expand.ai",hS=(e)=>Bo(e).pipe(Ru,cm(Ge({onNone:()=>!1,onSome:(t)=>t!==""&&t!=="0"&&t!=="false"}))),hhe=(e,t)=>Bo(e).pipe(Ru,cm(an(rg(t)))),wT=3;function $je(e,t){if(e===0)return"accepted";if(e===wT)return"refused";return t?"tolerated":"refused"}function bq(e){let t=e.replace(/\//g,"\\");if(!t.startsWith("\\\\"))return!1;return!/^\\\\[?.]\\[a-z]:/i.test(t)}function Kje(e,t,r){if(bq(e))return!1;return t.filter((n)=>!bq(n)).some((n)=>e===n||e.startsWith(`${n}${r}`))}var mhe=CR(fL.pipe(oRe("ApiKey"))),eh="Re-authenticate in this shell with `expandai login --json`. When an agent is handling the task, it must run that command itself and only ask the user to approve the returned URL and code in a browser.",Zje=CX("ApiKey",{apiKey:mhe}),wq=CX("OAuth",{accessToken:CR(m),refreshToken:M(CR(m)),expiresAt:xR,clientId:M(m)}),Xje=B({enabled:M(se),distinctId:M(m),noticeShown:M(se)}),Rq=B({sessionToken:CR(m),mintedAt:xR});class Ll extends we("ExpandCliConfig")({apiUrl:M(mR),authMethod:M(Ie(Zje,wq)),telemetry:M(Xje),anonymousSession:M(Rq)}){static Json=Aa(Ll)}function e$e(e,t){if(e._tag==="ApiKey")return"healthy";if(t5(t,e.expiresAt))return Jn(e.accessToken).trim().length>0?"healthy":"unusable";let r=e.refreshToken;return r!==void 0&&Jn(r).trim().length>0?"refresh_required":"unusable"}function t$e(e,t){return e$e(e,t)!=="unusable"}var r$e=Aa(B({alg:qf})),n$e=Aa(B({iss:mR}));function o$e(e,t){if(e._tag!=="OAuth")return!1;let r=Jn(e.accessToken).split(".");if(r.length!==3||r.some((o)=>!/^[A-Za-z0-9_-]+$/u.test(o)||Ht(YU(o))))return!1;let n=st(r[0]).pipe(an((o)=>XE(VU(o))),an(rg(r$e)));if(ot(n))return!1;return st(r[1]).pipe(an((o)=>XE(VU(o))),an(rg(n$e)),eB(({iss:o})=>(o.protocol==="https:"||o.protocol==="http:")&&o.origin!==t.origin))}var s$e=hn({key:m,value:bt}),QT=Aa(s$e);function i$e(e,t){return{...e,...t}}function a$e(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function c$e(e){return`'${e.replaceAll("'","''")}'`}function phe(e,t){return`$PSModuleAutoLoadingPreference = 'None'
177
177
  $targetPaths = @(${t.map((r)=>c$e(r)).join(", ")})
178
178
  function Get-CredentialItem($targetPath) {
package/build/esm/main.js CHANGED
@@ -290,7 +290,7 @@ foreach ($targetPath in $targetPaths) {
290
290
  }
291
291
  }
292
292
  'SECURE'
293
- `,m=[process.env.USERPROFILE,bmt()].filter((ie)=>typeof ie==="string"&&ie.trim()!==""&&!g8(ie)),E=(ie)=>r.resolve(ie).toLowerCase().replace(/\\+$/,""),x=Ce(function*(ie){let De=(Wt)=>t.realPath(Wt).pipe(Ft(()=>v(Wt)),ee(E)),Ne=yield*De(ie),it=yield*ot(m,De);return Qmt(Ne,it,r.sep)}),B=Ce(function*(ie,De,Ne){if(ie===0)return;let it=yield*x(o);return yield*vmt(o,ie,it,De,Ne)}),b=(ie,De)=>B(1,ie,De),k=Ce(function*(ie){let De=yield*lw("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",kMe(d,ie)).pipe(m8,Zn(gg,e),Ft((Ne)=>b("could not run the Windows ACL allowlist script",String(Ne)).pipe(hn(0))));yield*B(De,"the Windows ACL allowlist script did not complete",`PowerShell exited with status ${De}`)}),D=Ce(function*(ie){let De=yield*lw("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",kMe(A,ie)).pipe(m8,Zn(gg,e),Ft((Ne)=>b("could not inspect the Windows ACL allowlist",String(Ne)).pipe(hn(0))));yield*B(De,"the Windows ACL allowlist could not be verified",`PowerShell exited with status ${De}`)}),R=W("ConfigManager.inspectSecureStorage")(function*(){let ie=yield*a(o);if(!ie.exists)return yield*ne;if(ie.type!=="Directory")return yield*s(o,"config directory is not a regular directory",Error("Invalid config directory"));let De=yield*a(n);if(De.exists&&De.type!=="File")return yield*s(n,"credential path is not a regular file",Error("Invalid file"));if(process.platform==="win32"){let it=De.exists?[o,n]:[o],Wt=yield*ot(it,a);yield*D(it);let jt=yield*ot(it,a);return yield*ot(it,(Jn,cs)=>c(Jn,Wt[cs]??{exists:!1},jt[cs]??{exists:!1}),{discard:!0}),yield*ne}if(((yield*t.stat(o).pipe(fe((it)=>s(o,"could not inspect directory mode",it)))).mode&4095)!==448)return yield*s(o,"config directory mode is not 700",Error("Invalid directory mode"));if(De.exists){if(((yield*t.stat(n).pipe(fe((Wt)=>s(n,"could not inspect credential file mode",Wt)))).mode&4095)!==384)return yield*s(n,"credential file mode is not 600",Error("Invalid file mode"))}return yield*ne}),S=W("ConfigManager.ensureSecureStorage")(function*(){yield*t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((Ne)=>s(o,"could not create the config directory",Ne)));let ie=yield*a(o);if(!ie.exists||ie.type!=="Directory")return yield*s(o,"config directory is not a regular directory",Error("Invalid config directory"));if(!(yield*t.exists(n).pipe(fe((Ne)=>s(n,"could not inspect the credential file",Ne))))){let Ne=yield*qt(t.writeFileString(n,"{}",{flag:"wx",mode:384}));if(Ut(Ne)&&(!(Ne.left instanceof Ds)||Ne.left.reason!=="AlreadyExists"))return yield*s(n,"could not create the credential file",Ne.left)}if(yield*l(n),process.platform==="win32"){let Ne=[o,n],it=yield*ot(Ne,(jt)=>a(jt));yield*k(Ne);let Wt=yield*ot(Ne,(jt)=>a(jt));yield*ot(Ne,(jt,Jn)=>c(jt,it[Jn]??{exists:!1},Wt[Jn]??{exists:!1}),{discard:!0})}else yield*f(o,448,"Directory"),yield*f(n,384,"File");return yield*ne});function w(){return t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((ie)=>s(o,"could not create the config directory",ie)),we(process.platform==="win32"?k([o]):f(o,448,"Directory")),we(rh(n,S())))}let I=Ce(function*(ie){yield*w();let De=yield*l(n),Ne=yield*Gze(0,2147483647),it=r.join(o,`.config.json.${process.pid}.${Ne.toString(16)}.tmp`),Wt=Ce(function*(oi,vi){let si=yield*qt(l(it));if(Ut(si))return yield*new FC({path:n,temporaryPath:it,error:si.left,operationError:vi});if(!TMe(De.parent,si.right.parent))return yield*new FC({path:n,temporaryPath:it,error:Error("Config temp parent identity changed; refusing cleanup"),operationError:vi});if(!AB(oi,si.right.file))return yield*new FC({path:n,temporaryPath:it,error:Error("Config temp identity changed or disappeared; refusing cleanup"),operationError:vi});let pS=yield*qt(t.remove(it));if(Ut(pS))return yield*new FC({path:n,temporaryPath:it,error:pS.left,operationError:vi})}),jt=yield*RMe(t,it,ie,384).pipe(fe(()=>new iE({path:it})));if(ps(jt.writeExit)){let oi=new iE({path:it});return yield*Wt(jt.identity,oi),yield*oi}if(!jt.pathMatchesHandle){let oi=new iE({path:it});return yield*Wt(jt.identity,oi),yield*oi}let Jn=yield*qt(j(function*(){let oi=yield*l(it);if(yield*c(De.parentPath,De.parent,oi.parent),!AB(jt.identity,oi.file))return yield*s(it,"config temp identity differs from its creating handle",Error("Config temp replacement detected"));if(process.platform==="win32"){yield*k([it]);let si=yield*l(it);if(yield*c(De.parentPath,De.parent,si.parent),!AB(jt.identity,si.file))return yield*s(it,"config temp changed while applying its ACL",Error("Config temp replacement detected"))}else if(((yield*t.stat(it).pipe(fe((pS)=>s(it,"could not verify config temp mode",pS)))).mode&4095)!==384)return yield*s(it,"config temp mode is not 600",Error("Invalid config temp mode"));let vi=yield*l(n);yield*c(De.parentPath,De.parent,vi.parent),yield*c(n,De.file,vi.file),yield*t.rename(it,n).pipe(fe(()=>new iE({path:n})))}));if(Ut(Jn))return yield*Wt(jt.identity,Jn.left),yield*Jn.left;let cs=yield*l(n);if(yield*c(De.parentPath,De.parent,cs.parent),!AB(jt.identity,cs.file))return yield*s(n,"atomic credential installation identity could not be verified",Error("Installed file identity mismatch"))});function M(ie){return w().pipe(we(rh(n,I(ie))))}let T=j(function*(){if(!(yield*t.exists(n)))return{config:nh.make({}),raw:{}};let De=yield*p(n),Ne=yield*Zl(I2)(De).pipe(fe((jt)=>new aE({path:n,error:jt})));return{config:yield*er(nh)(Ne).pipe(fe((jt)=>new aE({path:n,error:jt}))),raw:Ne}}),O=T.pipe(ee(({config:ie})=>ie)),C=W("loadConfig")(function*(){let{config:ie,noAnonymous:De}=yield*OMe,Ne=yield*O,it={env:Ot(ie.apiUrl),file:Ot(Ne.apiUrl)},Wt={env:Ot(ie.authMethod),file:Ot(Ne.authMethod)};yield*_c(`EXPAND_API_URL overrides apiUrl from ${n}`).pipe(Si(()=>k1e(it.env,it.file,(si,pS)=>si.toString()!==pS.toString()).pipe(Ue(()=>!1))));let jt=yield*Ya,Jn=dQ([it.env,it.file]).pipe(Ue(()=>new URL(b2))),cs=Wt.file.pipe(_s((si)=>Tmt(si,Jn))),oi=Wt.file.pipe(_s((si)=>si._tag==="OAuth"&&cT(si,jt)),_s(()=>tt(Wt.env)||tt(cs))),vi=dQ([oi,Wt.env,Wt.file]);return yield*_c(`EXPAND_API_KEY is set but ${n} holds credentials from \`expandai login\` or agent setup, which take precedence. Unset EXPAND_API_KEY to silence this, or run \`expandai logout\` to use the API key.`).pipe(Si(()=>re(Wt.env)&&re(oi))),yield*_c(`Using EXPAND_API_KEY for ${Jn.origin} because the stored login was issued by a different API origin.`).pipe(Si(()=>re(Wt.env)&&re(cs))),yield*_c(`EXPAND_API_KEY overrides the API key stored in ${n}`).pipe(Si(()=>re(Wt.env)&&AQ(Wt.file,(si)=>si._tag==="ApiKey"))),{apiUrl:Jn,authMethod:vi,anonymousSession:Ot(Ne.anonymousSession),noAnonymous:De}}),U=W("saveConfig")(function*(ie){let De=yield*Eo(nh.Json)(ie);yield*M(De)}),_=W("updateConfig")(function*(ie){let De=yield*T,Ne=nh.make({...De.config,...ie}),it=yield*Eo(nh.Json)(Ne).pipe(L(Zl(I2))),Wt={...Mmt(De.raw,it)};if(Object.hasOwn(ie,"anonymousSession")&&ie.anonymousSession===void 0)delete Wt.anonymousSession;let jt=yield*Eo(I2)(Wt);yield*M(jt)});function Q(ie){return w().pipe(we(rh(n,_(ie))))}let F=W("readConfigFile")(function*(){return yield*T.pipe(ee(({config:ie})=>({config:ie,parseFailed:!1})),Ll(()=>({config:nh.make({}),parseFailed:!0})))}),Y=W("clearConfig")(function*(){let ie=yield*qt(T);if(Ut(ie)){if(!(ie.left instanceof aE))return yield*ie.left;yield*_c(`Could not parse ${n}; removing it. Telemetry preferences and apiUrl were not preserved.`),yield*t.remove(n).pipe(fe(()=>new iE({path:n})));return}let De={...ie.right.raw};delete De.authMethod,delete De.anonymousSession;let Ne=yield*Eo(I2)(De);yield*M(Ne)});function J(){return w().pipe(we(rh(n,Y())))}let le=W("getApiUrl")(function*(){let{config:ie}=yield*OMe,De=yield*O,Ne={env:Ot(ie.apiUrl),file:Ot(De.apiUrl)};return dQ([Ne.env,Ne.file]).pipe(Ue(()=>new URL(b2)))}),We=W("getAppUrl")(function*(){return yield*Lt("EXPAND_APP_URL").pipe(dr(wmt))}),Ke=W("getPlaygroundHost")(function*(){return yield*Lt("EXPAND_PLAYGROUND_HOST").pipe(dr(RC))});return{configPath:n,inspectSecureStorage:R,ensureSecureStorage:w,loadConfig:C,saveConfig:U,updateConfig:Q,clearConfig:J,readConfigFile:F,getApiUrl:le,getAppUrl:We,getPlaygroundHost:Ke}})}){}var vC="Open the approval page in your browser, type in the code shown here, and approve. Only enter this code on the Expand approval page your terminal named — never a code someone sent you, and never on a page from a link you did not expect. When you have approved, say so, and the same command will pick the authorization up.",R2="Authorization complete. That setup code has been consumed and cannot be reused.",k2="Expand is already authorized. Agent setup is complete.",x8="Expand is authorized, but not every harness could be configured. The harnesses that failed are listed under `failures`; the ones under `installations` are ready to use.",C8="Show these harnesses to the user and ask which to configure. Pass the chosen ones to `expandai init --harnesses`. Harnesses that are not chosen are left untouched.",S8="No supported agent harness was found on this machine. Do not ask the user to choose from an empty list. Tell them Expand supports claude-code, cursor, opencode, codex, and fx, and that setup cannot continue until one of them is installed.",Wo=G("claude-code","cursor","opencode","codex","fx");class T2 extends ve("InitDetectionResult")({schemaVersion:G(1),status:G("detected"),harnesses:Te(Wo),current:V(Wo),userMessage:G(C8,S8)}){}var I8=Tb(Wo),Qa=G("project","global"),_mt=G("webfetch-hook","runtime-skill","mcp"),Umt=G("unverified","observed","reload_required","blocked"),Cnr=G("authorization_required","completed"),Lmt=g.pipe(sn(20),yU(256)),Pmt=jm(Lmt,gA(g),{strict:!0,decode:(e)=>e,encode:()=>"<redacted-redacted-setup-token>"});class O2 extends ve("InitRequest")({harnesses:I8,scope:Qa,setupToken:V(Pmt)}){}var Hmt=P({schemaVersion:G(1),status:G("authorization_required"),harnesses:I8,scope:Qa,userMessage:G(vC),authorization:P({url:Km,userCode:g,approvalExpiresAt:Sf})}),Wmt=P({runtimeState:Umt,nextAction:g}),qmt=P({harness:Wo,configured:xe,changed:xe,components:Te(_mt),version:g,verification:Wmt}),Gmt=P({harness:Wo,code:g,recoverable:xe}),Vmt=P({schemaVersion:G(1),status:G("completed"),harnesses:I8,scope:Qa,userMessage:G(R2,k2,x8),auth:P({healthy:xe}),projectPath:V(g),installations:Tb(qmt),failures:V(Te(Gmt))}),lT=ze(Hmt,Vmt);class cE extends ve("InitErrorEnvelope")({schemaVersion:G(1),status:G("error"),code:g,message:g,recoverable:xe}){}var yu="expandai-cli-browser",Ymt=P({apiOrigin:g,clientId:G(yu),purpose:V(G("login","agent-setup")),harness:G("agent-harnesses"),scope:G("project","global"),canonicalScopeRoot:g});class mB extends ve("PendingInitRecord")({key:Ymt,deviceCode:gA(g),userCode:g,verificationUri:g,intervalSeconds:pe,nextPollAt:Sf,approvalExpiresAt:Sf}){}class sh extends nt()("PendingInitCorrupt",{path:g,error:Kt}){recoverable=!0;get message(){return`Pending authorization state at ${this.path} is corrupt and was left unchanged.`}}class b8 extends nt()("PendingInitStorageError",{path:g,error:Kt}){recoverable=!0;get message(){return`Could not access pending authorization state at ${this.path}.`}}class w8 extends ve("DeviceAuthorizationCreated")({deviceCode:gA($s),userCode:$s,verificationUri:Km,expiresIn:cr.pipe(xj()),interval:cr.pipe(N4e())}){}var zmt=P({access_token:gA($s),refresh_token:gA($s),token_type:$s,expires_in:pe.pipe(xj()),scope:V(g)}),Jmt=G("create","poll");class xu extends nt()("DeviceAuthorizationApiError",{operation:Jmt,kind:G("request_failed","rejected","invalid_response"),status:V(pe),recoverable:xe}){get message(){return this.kind==="rejected"?`Device authorization ${this.operation} was rejected. Restart authorization if the problem persists.`:`Device authorization ${this.operation} could not be completed safely. Try again.`}}class M2 extends xt()("@expandai/cli/Auth/DeviceAuthorizationClient",{dependencies:[td,bt.Default],effect:j(function*(){let e=yield*xg,t=yield*bt;function r(a,c,l){return new xu({operation:a,kind:c,status:l,recoverable:c!=="invalid_response"})}let n=W("DeviceAuthorizationClient.create")(function*(a){let c=yield*t.getApiUrl(),l=yield*fw(new URL("/v1/cli-authorization/device",c)).pipe(jc(a),fe(()=>r("create","request_failed")));return yield*e.execute(l).pipe(L((u)=>Pt(u.status).pipe(Be((p)=>p>=200&&p<300,()=>ki(w8)(u).pipe(fe(()=>r("create","invalid_response")))),bA(()=>u.text.pipe($r,we(r("create","rejected",u.status)))))),Ft((u)=>u instanceof xu?u:r("create","request_failed")))}),o=P({error:g,error_description:V(g)}),s=new Set(["invalid_target","invalid_client","invalid_scope","unsupported_grant_type","unauthorized_client","invalid_request"]),i=W("DeviceAuthorizationClient.poll")(function*(a){let c=yield*t.getApiUrl(),l=fw(new URL("/api/auth/oauth2/token",c)).pipe(zxe({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:Js(a),client_id:yu,resource:c.toString()}));return yield*e.execute(l).pipe(L(Ce(function*(u){return yield*Pt(u.status).pipe(Be((p)=>p>=200&&p<300,()=>ki(zmt)(u).pipe(fe(()=>r("poll","invalid_response")),ee((p)=>({_tag:"Tokens",token:p})))),Be((p)=>p>=500,()=>u.text.pipe($r,we(r("poll","rejected",u.status)))),bA(()=>ki(o)(u).pipe(fe(()=>r("poll","invalid_response")),ee((p)=>Pt(p.error).pipe(Be("authorization_pending",()=>({_tag:"Pending"})),Be("slow_down",()=>({_tag:"SlowDown"})),Be("access_denied",()=>({_tag:"Denied"})),Be("expired_token",()=>({_tag:"Expired"})),bA(()=>s.has(p.error)?{_tag:"Refused",error:p.error,...p.error_description===void 0?{}:{description:p.error_description}}:{_tag:"Invalid"}))))))})),Ft((u)=>u instanceof xu?u:r("poll","request_failed")))});return{create:n,poll:i}})}){}var ss="0.1.1";class FMe extends mx()("DeviceAuthorizationTokensSaved",{}){}class NMe extends mx()("DeviceAuthorizationPending",{}){}class vMe extends mx()("DeviceAuthorizationSlowDown",{}){}class _Me extends mx()("DeviceAuthorizationExpired",{}){}class UMe extends mx()("DeviceAuthorizationInvalid",{}){}class Tp extends nt()("DeviceAuthorizationDenied",{recoverable:G(!0)}){get message(){return"The authorization request was denied in the browser. Run the same command again to start a new one."}}class ih extends nt()("DeviceAuthorizationRefused",{error:g,description:V(g),recoverable:G(!1)}){get message(){let e=this.description===void 0?"":` — ${this.description}`;return`Expand refused to complete this authorization: ${this.error}${e}. This is a server-side configuration problem, not something a new code can fix. Do not start authorization again; report this error.`}}class ah extends nt()("DeviceAuthorizationCredentialSaveFailed",{recoverable:G(!1)}){get message(){return"Authorization succeeded, but credentials could not be saved. Start authorization again."}}function MMe(e){return e.platform??process.platform}class _C extends xt()("@expandai/cli/Auth/DeviceAuthorization",{dependencies:[bt.Default,M2.Default],effect:j(function*(){let e=yield*bt,t=yield*M2,r=W("DeviceAuthorization.create")(function*(s){yield*e.ensureSecureStorage();let i={platform:MMe(s),machineLabel:`${MMe(s)}-${process.arch}`,cliVersion:ss};return yield*s.purpose==="login"?t.create({purpose:"login",harness:"agent-harnesses",scope:"global",...i}):t.create({purpose:"agent-setup",harness:s.harness,scope:s.scope,...i})}),n=Ce(function*(s){let i=yield*Ya,a=yield*qt(e.updateConfig({authMethod:aT.make({accessToken:s.access_token,refreshToken:s.refresh_token,expiresAt:Sb(i,yl(s.expires_in)),clientId:yu})}));return yield*Qn(a,{onLeft:()=>new ah({recoverable:!1}),onRight:()=>ne})}),o=W("DeviceAuthorization.poll")(function*(s){let i=yield*t.poll(s);return yield*Pt(i).pipe(xr("Tokens",({token:a})=>n(a).pipe(hn(new FMe))),xr("Pending",()=>v(new NMe)),xr("SlowDown",()=>v(new vMe)),xr("Denied",()=>new Tp({recoverable:!0})),xr("Expired",()=>v(new _Me)),xr("Invalid",()=>v(new UMe)),xr("Refused",({error:a,description:c})=>new ih({error:a,...c===void 0?{}:{description:c},recoverable:!1})),Ar)});return{create:r,poll:o}})}){}import{createHash as $mt}from"node:crypto";var B8=zt(mB),jmt=300000,LMe=zt(ze(kb(g,G(yu),G("agent-harnesses"),G("project","global"),g),kb(g,G(yu),G("login"))));function Q8(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function Kmt(e){return e instanceof Ds&&(e.reason==="AlreadyExists"||Q8(e.cause,"EEXIST"))}function Zmt(e){return e instanceof Ds&&(e.reason==="NotFound"||Q8(e.cause,"ENOENT"))}function Xmt(e){return e.purpose==="login"?ts(LMe)([e.apiOrigin,e.clientId,e.purpose]):ts(LMe)([e.apiOrigin,e.clientId,e.harness,e.scope,e.canonicalScopeRoot])}function PMe(e,t){let r=e.dirname(t);return r===t?[t]:[t,...PMe(e,r)]}class ch extends xt()("@expandai/cli/Auth/PendingInitStore",{dependencies:[y3],effect:j(function*(){let e=yield*Lr,t=yield*Nr,r=t.join(yield*hB,"expandai"),n=t.join(r,"pending-init"),o=(S,w)=>new b8({path:S,error:w}),s=(S,w)=>w.pipe(fe((I)=>o(S,I))),i=Ce(function*(S){let w=yield*qt(e.readLink(S));if(xn(w))return yield*o(S,Error("Symbolic links are not allowed for pending authorization"));let I=w.left;if(I instanceof Ds&&(I.reason==="InvalidData"||I.reason==="NotFound"||I.method==="readLink"&&Q8(I.cause,"EINVAL")))return;return yield*o(S,I)}),a=Ce(function*(){if(yield*i(r),yield*i(n),yield*s(n,e.makeDirectory(n,{recursive:!0,mode:448})),yield*i(r),yield*i(n),(yield*s(n,e.stat(n))).type!=="Directory")return yield*o(n,Error("Pending authorization path is not a directory"));if(process.platform!=="win32")yield*s(r,e.chmod(r,448)),yield*s(n,e.chmod(n,448))}),c=(S)=>{let w=$mt("sha256").update(Xmt(S)).digest("hex");return t.join(n,`${w}.json`)},l=Ce(function*(S,w){let I=yield*Zl(B8)(w).pipe(fe(()=>new sh({path:S,error:Error("Stored pending authorization did not match the expected schema")})));if(c(I.key)!==S)return yield*new sh({path:S,error:Error("Stored pending authorization key did not match its file")});return I}),u=Ce(function*(S){if(yield*i(S),!(yield*s(S,e.exists(S))))return q();let I=yield*s(S,e.stat(S));if(I.type!=="File")return yield*o(S,Error("Pending state is not a regular file"));if(process.platform!=="win32"&&(I.mode&511)!==384)return yield*o(S,Error("Pending state file mode is not 600"));let M=yield*s(S,e.readFileString(S));return H(yield*l(S,M))}),p=(S)=>u(c(S)),f=Ce(function*(S){let w=PD(yield*Ya);return PD(S.approvalExpiresAt)+jmt<=w}),d=Ce(function*(S){yield*a();let w=c(S.key),I=yield*Eo(B8)(S).pipe(fe((T)=>o(w,T))),M=yield*qt(Ur(j(function*(){let T=yield*e.open(w,{flag:"wx",mode:384});yield*T.writeAll(new TextEncoder().encode(I)),yield*T.sync})));if(Ut(M)){if(Kmt(M.left))return!1;return yield*e.remove(w).pipe($r),yield*o(w,M.left)}if(process.platform!=="win32"){let T=yield*qt(e.chmod(w,384));if(Ut(T))return yield*e.remove(w).pipe($r),yield*o(w,T.left)}return!0}),A=W("PendingInitStore.replaceIfMatch")(function*(S,w){yield*a();let I=c(w.key);if(c(S.key)!==I)return yield*o(I,Error("Pending authorization replacement changed its key"));let M=yield*u(I);if(tt(M)||M.value.userCode!==S.userCode)return!1;let T=yield*Eo(B8)(w).pipe(fe((U)=>o(I,U))),O=`${I}.${process.pid}.${Math.random().toString(36).slice(2,10)}.tmp`,C=yield*Ur(Tn(v(O),()=>e.remove(O).pipe($r)).pipe(we(j(function*(){yield*i(O),yield*Ur(j(function*(){let U=yield*e.open(O,{flag:"wx",mode:384});yield*U.writeAll(new TextEncoder().encode(T)),yield*U.sync})),yield*e.rename(O,I)})))).pipe(qt);if(Ut(C))return yield*o(I,C.left);return!0}),m=Ce(function*(S){let w=c(S.key),I=yield*u(w);if(tt(I)||I.value.userCode!==S.userCode)return!1;return yield*s(w,e.remove(w)),!0}),E=W("PendingInitStore.get")(function*(S){let w=yield*p(S);if(tt(w)||!(yield*f(w.value)))return w;return yield*m(w.value),q()}),x=W("PendingInitStore.peek")(function*(S){return yield*p(S)}),B=W("PendingInitStore.putIfAbsent")(function*(S){let w=yield*p(S.key);if(re(w)&&!(yield*f(w.value)))return w.value;if(re(w))yield*m(w.value);if(yield*d(S))return S;let I=yield*p(S.key);return yield*Me(I,{onNone:()=>o(c(S.key),Error("Pending record creation lost without a winner")),onSome:v})}),b=W("PendingInitStore.removeIfMatch")((S)=>m(S)),k=W("PendingInitStore.removeCorrupt")(function*(S){let w=c(S),I=yield*qt(u(w));if(xn(I))return!1;if(!(I.left instanceof sh))return yield*I.left;let M=yield*qt(e.remove(w));if(Ut(M)&&Zmt(M.left))return!1;if(Ut(M))return yield*o(w,M.left);return!0}),D=W("PendingInitStore.pruneExpired")(function*(){if(yield*i(n),!(yield*s(n,e.exists(n))))return 0;let w=yield*s(n,e.readDirectory(n));return(yield*ot(w.filter((M)=>M.endsWith(".json")),(M)=>j(function*(){let T=yield*u(t.join(n,M));if(tt(T)||!(yield*f(T.value)))return 0;return(yield*m(T.value))?1:0}).pipe(Ll(()=>0)))).reduce((M,T)=>M+T,0)}),R=W("PendingInitStore.canonicalScopeRoot")(function*(S,w=process.cwd()){if(S==="global")return"global";let I=yield*s(w,e.realPath(w)),T=(yield*ot(PMe(t,I),(O)=>s(O,e.exists(t.join(O,".git"))).pipe(ee((C)=>({candidate:O,exists:C}))))).find(({exists:O})=>O)?.candidate;return T===void 0?I:yield*s(T,e.realPath(T))});return{pendingPath:n,get:E,peek:x,putIfAbsent:B,replaceIfMatch:A,removeIfMatch:b,removeCorrupt:k,pruneExpired:D,canonicalScopeRoot:R}})}){}var egt=yu,tgt=5;class uT extends ve("ManualAuthorizationInput")({purpose:N(G("login","agent-setup"),{default:()=>"agent-setup"}),harness:G("agent-harnesses"),scope:Qa,cwd:V(g),platform:V(g)}){}class D8 extends ve("ManualAuthorizationRequired")({verificationUri:g,userCode:$s,approvalExpiresAt:Sf}){}class R8 extends mx()("TokensSaved",{}){}class lE extends mx()("AuthorizationPending",{pending:D8}){}var Xnr=ze(R8,lE);function gB(e){return new D8({verificationUri:e.verificationUri,userCode:e.userCode,approvalExpiresAt:e.approvalExpiresAt})}class Cu extends xt()("@expandai/cli/Auth/ManualAuthorization",{dependencies:[bt.Default,ch.Default,_C.Default],effect:j(function*(){let e=yield*bt,t=yield*ch,r=yield*_C,n=Ce(function*(l){yield*e.ensureSecureStorage(),yield*t.pruneExpired();let u=yield*e.getApiUrl(),p=yield*t.canonicalScopeRoot(l.scope,l.cwd);return{apiOrigin:u.origin,clientId:egt,purpose:l.purpose,harness:l.harness,scope:l.scope,canonicalScopeRoot:p}}),o=Ce(function*(l,u){let p=l.platform===void 0?{}:{platform:l.platform},f=yield*r.create(l.purpose==="login"?{purpose:"login",...p}:{purpose:"agent-setup",harness:l.harness,scope:l.scope,...p}),d=yield*Ya,A=new mB({key:u,deviceCode:f.deviceCode,userCode:f.userCode,verificationUri:f.verificationUri.toString(),intervalSeconds:f.interval,nextPollAt:Sb(d,yl(f.interval)),approvalExpiresAt:Sb(d,yl(f.expiresIn))}),m=yield*qt(t.putIfAbsent(A));if(Ut(m))return yield*m.left;return m.right}),s=Ce(function*(l,u){let p=yield*Ya,f=l.intervalSeconds+(u?tgt:0),d=new mB({...l,intervalSeconds:f,nextPollAt:Sb(p,yl(f))}),A=yield*qt(t.replaceIfMatch(l,d));if(Ut(A))return l;return A.right?d:l}),i=Ce(function*(l,u){let p=yield*qt(t.get(u));if(xn(p))return p.right;if(l.purpose!=="login"||!(p.left instanceof sh))return yield*p.left;return yield*t.removeCorrupt(u),yield*t.get(u)}),a=W("ManualAuthorization.advance")(function*(l){let u=yield*n(l),p=yield*i(l,u);if(tt(p)){let E=yield*o(l,u);return new lE({pending:gB(E)})}let f=p.value,d=yield*Ya;if(o4e(d,f.approvalExpiresAt)){yield*t.removeIfMatch(f);let E=yield*o(l,u);return new lE({pending:gB(E)})}if(lU(d,f.nextPollAt))return new lE({pending:gB(f)});let A=yield*qt(r.poll(f.deviceCode)),m=Ce(function*(){yield*t.removeIfMatch(f);let E=yield*o(l,u);return new lE({pending:gB(E)})});return yield*Qn(A,{onLeft:(E)=>t.removeIfMatch(f).pipe(Si(()=>E instanceof Tp),we(ce(E))),onRight:(E)=>Pt(E).pipe(xr("DeviceAuthorizationTokensSaved",()=>t.removeIfMatch(f).pipe(hn(new R8))),xr("DeviceAuthorizationPending",()=>s(f,!1).pipe(ee((x)=>new lE({pending:gB(x)})))),xr("DeviceAuthorizationSlowDown",()=>s(f,!0).pipe(ee((x)=>new lE({pending:gB(x)})))),xr("DeviceAuthorizationExpired",m),xr("DeviceAuthorizationInvalid",m),Ar)})}),c=W("ManualAuthorization.redeemPreApproved")(function*(l){let u=yield*r.poll(l);function p(){return new xu({operation:"poll",kind:"rejected",status:400,recoverable:!1})}return yield*Pt(u).pipe(xr("DeviceAuthorizationTokensSaved",()=>ne),xr("DeviceAuthorizationPending",p),xr("DeviceAuthorizationSlowDown",p),xr("DeviceAuthorizationExpired",p),xr("DeviceAuthorizationInvalid",p),Ar)});return{advance:a,redeemPreApproved:c}})}){}var HMe="Authorization complete. Expand is ready to use; retry the command that required authentication.",rgt=G("authorization_internal_error","authorization_unreachable","authorization_rejected","authorization_service_unavailable","authorization_invalid_response","authorization_denied","authorization_refused","credential_save_failed","credential_storage_insecure");class pc extends nt()("DeviceLoginError",{code:rgt,recoverable:xe,httpStatus:V(pe)}){get message(){switch(this.code){case"authorization_internal_error":return"Authorization failed for an unexpected internal reason. Do not retry in a loop; report this error.";case"authorization_unreachable":return"Could not reach the Expand API. Nothing was changed: any pending authorization is still pending, and if none existed, none was started. Do not retry until the connection is fixed; then run the same command again.";case"authorization_rejected":return"The Expand API rejected the device authorization request. Retry later; if this persists, the CLI and API versions may be incompatible.";case"authorization_service_unavailable":return`The Expand device authorization service is unavailable${this.httpStatus===void 0?"":` (HTTP ${this.httpStatus})`}. Retry later or use the staging API for an isolated test.`;case"authorization_invalid_response":return"The Expand API returned an invalid device authorization response. Do not continue with a URL or code from this response; update the CLI or report the problem.";case"authorization_denied":return"The authorization was denied in the browser. If that was unintended, run the same command again for a fresh approval code.";case"authorization_refused":return"Expand refused to complete the authorization for a reason a new code cannot fix. Do not start another authorization; report the error.";case"credential_save_failed":return"Authorization completed, but credentials could not be saved. Fix credential storage before starting again.";case"credential_storage_insecure":return"Credential storage is not secure enough to continue."}}}class N2 extends ve("DeviceLoginErrorEnvelope")({schemaVersion:G(1),status:G("error"),code:g,message:g,recoverable:xe}){}var ngt=P({schemaVersion:G(1),status:G("authorization_required"),userMessage:G(vC),authorization:P({url:Km,userCode:$s,approvalExpiresAt:Sf})}),ogt=P({schemaVersion:G(1),status:G("completed"),userMessage:G(HMe),auth:P({healthy:G(!0)})}),F2=ze(ngt,ogt);function sgt(e){if(e instanceof uc)return new pc({code:"credential_storage_insecure",recoverable:!1});if(e instanceof Tp)return new pc({code:"authorization_denied",recoverable:!0});if(e instanceof ih)return new pc({code:"authorization_refused",recoverable:!1});if(e instanceof ah)return new pc({code:"credential_save_failed",recoverable:!1});if(e instanceof xu)switch(e.kind){case"request_failed":return new pc({code:"authorization_unreachable",recoverable:!0});case"rejected":if(e.status!==void 0&&e.status>=500)return new pc({code:"authorization_service_unavailable",recoverable:!0,httpStatus:e.status});return new pc({code:"authorization_rejected",recoverable:e.recoverable});case"invalid_response":return new pc({code:"authorization_invalid_response",recoverable:!1})}return new pc({code:"authorization_internal_error",recoverable:!1})}class pT extends xt()("@expandai/cli/Auth/DeviceLogin",{dependencies:[Cu.Default],effect:j(function*(){let e=yield*Cu;return{run:W("DeviceLogin.run")(function*(){let r=yield*e.advance(new uT({purpose:"login",harness:"agent-harnesses",scope:"global"})).pipe(fe(sgt));return yield*Pt(r).pipe(xr("TokensSaved",()=>er(F2)({schemaVersion:1,status:"completed",userMessage:HMe,auth:{healthy:!0}}).pipe(fe(()=>new pc({code:"authorization_internal_error",recoverable:!1})))),xr("AuthorizationPending",({pending:n})=>er(F2)({schemaVersion:1,status:"authorization_required",userMessage:vC,authorization:{url:n.verificationUri,userCode:n.userCode,approvalExpiresAt:lx(n.approvalExpiresAt)}}).pipe(fe(()=>new pc({code:"authorization_internal_error",recoverable:!1})))),Ar)})}})}){}class v2 extends nt()("SetupGrantAuthorizationError",{code:G("invalid_or_expired","stored_credential_conflict","request_failed","denied","credential_save_failed","refused","config_unreadable"),recoverable:xe}){get message(){switch(this.code){case"stored_credential_conflict":return"An Expand API key is already stored on this machine, and completing this setup would replace it with no way to recover it. Nothing was changed and your setup prompt is still valid. Run `expandai logout` to clear the stored key, then run this setup command again.";case"request_failed":return"Could not reach Expand to redeem the setup token. Nothing was sent, so the same token is still good — check the network and try again.";case"denied":return"This setup authorization was denied. Copy a fresh setup prompt from the Expand dashboard.";case"config_unreadable":return"The Expand config file on this machine could not be read, so setup cannot tell whether completing it would overwrite an existing API key. Nothing was redeemed and your setup prompt is still valid. Run `expandai whoami` to see which file it is, fix or delete it, then run this setup command again.";case"refused":return"Expand refused to redeem this setup token for a reason a fresh prompt cannot fix — most likely an OAuth client, resource, or scope misconfiguration on the server. Do not request another prompt; report this.";case"credential_save_failed":return"The setup token was redeemed, but the credentials could not be saved on this machine. Fix credential storage — run `expandai whoami` to see the path it uses, and check its permissions — then copy a fresh setup prompt from the Expand dashboard.";default:return"The setup token is invalid, expired, or already used. Copy a fresh setup prompt from the Expand dashboard."}}}function UC(e){return new v2({code:e,recoverable:e!=="denied"&&e!=="credential_save_failed"&&e!=="refused"})}class EB extends xt()("@expandai/cli/Auth/SetupGrantAuthorization",{dependencies:[bt.Default,Cu.Default],effect:j(function*(){let e=yield*bt,t=yield*Cu;return{authorize:W("SetupGrantAuthorization.authorize")(function*(n){let o=yield*e.readConfigFile();if(o.parseFailed)return yield*UC("config_unreadable");if(o.config.authMethod?._tag==="ApiKey")return yield*UC("stored_credential_conflict");yield*Hy({harness:n.harness,scope:n.scope}),yield*t.redeemPreApproved(n.setupToken).pipe(fe((s)=>{if(s instanceof Tp)return UC("denied");if(s instanceof ah)return UC("credential_save_failed");if(s instanceof ih)return UC("refused");if(s instanceof xu&&s.kind==="request_failed")return UC("request_failed");return UC("invalid_or_expired")}))})}})}){}import lFe from"node:process";import G8 from"node:path";import{fileURLToPath as Wgt}from"node:url";import qgt from"node:child_process";import Ggt,{constants as Vgt}from"node:fs/promises";import ggt from"node:path";import{promisify as Egt}from"node:util";import ygt from"node:child_process";import N8,{constants as KMe}from"node:fs/promises";import GMe from"node:process";import ugt from"node:os";import M8 from"node:fs";import cgt from"node:fs";import WMe from"node:fs";var k8;function igt(){try{return WMe.statSync("/.dockerenv"),!0}catch{return!1}}function agt(){try{return WMe.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function T8(){if(k8===void 0)k8=igt()||agt();return k8}var O8,lgt=()=>{try{return cgt.statSync("/run/.containerenv"),!0}catch{return!1}};function LC(){if(O8===void 0)O8=lgt()||T8();return O8}var qMe=()=>{if(GMe.platform!=="linux")return!1;if(ugt.release().toLowerCase().includes("microsoft")){if(LC())return!1;return!0}try{if(M8.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!LC()}catch{}if(M8.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||M8.existsSync("/run/WSL"))return!LC();return!1},rd=GMe.env.__IS_WSL_TEST__?qMe:qMe();import VMe from"node:process";import{Buffer as pgt}from"node:buffer";import{promisify as fgt}from"node:util";import dgt from"node:child_process";var Agt=fgt(dgt.execFile),F8=()=>`${VMe.env.SYSTEMROOT||VMe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var YMe=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],zMe=(e)=>pgt.from(e,"utf16le").toString("base64"),hgt=(e)=>`'${String(e).replaceAll(/['‘’‚‛]/g,(t)=>t+t)}'`,JMe=(e)=>[...YMe,zMe(e)],mgt=(e)=>({encoding:"utf8",...e,shell:!1}),Su=async(e,t={})=>{let{powerShellPath:r,...n}=t;return Agt(r??F8(),JMe(e),mgt(n))};Su.argumentsPrefix=YMe;Su.encodeCommand=zMe;Su.escapeArgument=hgt;Su.createArguments=JMe;function $Me(e){for(let t of e.split(`
293
+ `,m=[process.env.USERPROFILE,bmt()].filter((ie)=>typeof ie==="string"&&ie.trim()!==""&&!g8(ie)),E=(ie)=>r.resolve(ie).toLowerCase().replace(/\\+$/,""),x=Ce(function*(ie){let De=(Wt)=>t.realPath(Wt).pipe(Ft(()=>v(Wt)),ee(E)),Ne=yield*De(ie),it=yield*ot(m,De);return Qmt(Ne,it,r.sep)}),B=Ce(function*(ie,De,Ne){if(ie===0)return;let it=yield*x(o);return yield*vmt(o,ie,it,De,Ne)}),b=(ie,De)=>B(1,ie,De),k=Ce(function*(ie){let De=yield*lw("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",kMe(d,ie)).pipe(m8,Zn(gg,e),Ft((Ne)=>b("could not run the Windows ACL allowlist script",String(Ne)).pipe(hn(0))));yield*B(De,"the Windows ACL allowlist script did not complete",`PowerShell exited with status ${De}`)}),D=Ce(function*(ie){let De=yield*lw("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",kMe(A,ie)).pipe(m8,Zn(gg,e),Ft((Ne)=>b("could not inspect the Windows ACL allowlist",String(Ne)).pipe(hn(0))));yield*B(De,"the Windows ACL allowlist could not be verified",`PowerShell exited with status ${De}`)}),R=W("ConfigManager.inspectSecureStorage")(function*(){let ie=yield*a(o);if(!ie.exists)return yield*ne;if(ie.type!=="Directory")return yield*s(o,"config directory is not a regular directory",Error("Invalid config directory"));let De=yield*a(n);if(De.exists&&De.type!=="File")return yield*s(n,"credential path is not a regular file",Error("Invalid file"));if(process.platform==="win32"){let it=De.exists?[o,n]:[o],Wt=yield*ot(it,a);yield*D(it);let jt=yield*ot(it,a);return yield*ot(it,(Jn,cs)=>c(Jn,Wt[cs]??{exists:!1},jt[cs]??{exists:!1}),{discard:!0}),yield*ne}if(((yield*t.stat(o).pipe(fe((it)=>s(o,"could not inspect directory mode",it)))).mode&4095)!==448)return yield*s(o,"config directory mode is not 700",Error("Invalid directory mode"));if(De.exists){if(((yield*t.stat(n).pipe(fe((Wt)=>s(n,"could not inspect credential file mode",Wt)))).mode&4095)!==384)return yield*s(n,"credential file mode is not 600",Error("Invalid file mode"))}return yield*ne}),S=W("ConfigManager.ensureSecureStorage")(function*(){yield*t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((Ne)=>s(o,"could not create the config directory",Ne)));let ie=yield*a(o);if(!ie.exists||ie.type!=="Directory")return yield*s(o,"config directory is not a regular directory",Error("Invalid config directory"));if(!(yield*t.exists(n).pipe(fe((Ne)=>s(n,"could not inspect the credential file",Ne))))){let Ne=yield*qt(t.writeFileString(n,"{}",{flag:"wx",mode:384}));if(Ut(Ne)&&(!(Ne.left instanceof Ds)||Ne.left.reason!=="AlreadyExists"))return yield*s(n,"could not create the credential file",Ne.left)}if(yield*l(n),process.platform==="win32"){let Ne=[o,n],it=yield*ot(Ne,(jt)=>a(jt));yield*k(Ne);let Wt=yield*ot(Ne,(jt)=>a(jt));yield*ot(Ne,(jt,Jn)=>c(jt,it[Jn]??{exists:!1},Wt[Jn]??{exists:!1}),{discard:!0})}else yield*f(o,448,"Directory"),yield*f(n,384,"File");return yield*ne});function w(){return t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((ie)=>s(o,"could not create the config directory",ie)),we(process.platform==="win32"?k([o]):f(o,448,"Directory")),we(rh(n,S())))}let I=Ce(function*(ie){yield*w();let De=yield*l(n),Ne=yield*Gze(0,2147483647),it=r.join(o,`.config.json.${process.pid}.${Ne.toString(16)}.tmp`),Wt=Ce(function*(oi,vi){let si=yield*qt(l(it));if(Ut(si))return yield*new FC({path:n,temporaryPath:it,error:si.left,operationError:vi});if(!TMe(De.parent,si.right.parent))return yield*new FC({path:n,temporaryPath:it,error:Error("Config temp parent identity changed; refusing cleanup"),operationError:vi});if(!AB(oi,si.right.file))return yield*new FC({path:n,temporaryPath:it,error:Error("Config temp identity changed or disappeared; refusing cleanup"),operationError:vi});let pS=yield*qt(t.remove(it));if(Ut(pS))return yield*new FC({path:n,temporaryPath:it,error:pS.left,operationError:vi})}),jt=yield*RMe(t,it,ie,384).pipe(fe(()=>new iE({path:it})));if(ps(jt.writeExit)){let oi=new iE({path:it});return yield*Wt(jt.identity,oi),yield*oi}if(!jt.pathMatchesHandle){let oi=new iE({path:it});return yield*Wt(jt.identity,oi),yield*oi}let Jn=yield*qt(j(function*(){let oi=yield*l(it);if(yield*c(De.parentPath,De.parent,oi.parent),!AB(jt.identity,oi.file))return yield*s(it,"config temp identity differs from its creating handle",Error("Config temp replacement detected"));if(process.platform==="win32"){yield*k([it]);let si=yield*l(it);if(yield*c(De.parentPath,De.parent,si.parent),!AB(jt.identity,si.file))return yield*s(it,"config temp changed while applying its ACL",Error("Config temp replacement detected"))}else if(((yield*t.stat(it).pipe(fe((pS)=>s(it,"could not verify config temp mode",pS)))).mode&4095)!==384)return yield*s(it,"config temp mode is not 600",Error("Invalid config temp mode"));let vi=yield*l(n);yield*c(De.parentPath,De.parent,vi.parent),yield*c(n,De.file,vi.file),yield*t.rename(it,n).pipe(fe(()=>new iE({path:n})))}));if(Ut(Jn))return yield*Wt(jt.identity,Jn.left),yield*Jn.left;let cs=yield*l(n);if(yield*c(De.parentPath,De.parent,cs.parent),!AB(jt.identity,cs.file))return yield*s(n,"atomic credential installation identity could not be verified",Error("Installed file identity mismatch"))});function M(ie){return w().pipe(we(rh(n,I(ie))))}let T=j(function*(){if(!(yield*t.exists(n)))return{config:nh.make({}),raw:{}};let De=yield*p(n),Ne=yield*Zl(I2)(De).pipe(fe((jt)=>new aE({path:n,error:jt})));return{config:yield*er(nh)(Ne).pipe(fe((jt)=>new aE({path:n,error:jt}))),raw:Ne}}),O=T.pipe(ee(({config:ie})=>ie)),C=W("loadConfig")(function*(){let{config:ie,noAnonymous:De}=yield*OMe,Ne=yield*O,it={env:Ot(ie.apiUrl),file:Ot(Ne.apiUrl)},Wt={env:Ot(ie.authMethod),file:Ot(Ne.authMethod)};yield*_c(`EXPAND_API_URL overrides apiUrl from ${n}`).pipe(Si(()=>k1e(it.env,it.file,(si,pS)=>si.toString()!==pS.toString()).pipe(Ue(()=>!1))));let jt=yield*Ya,Jn=dQ([it.env,it.file]).pipe(Ue(()=>new URL(b2))),cs=Wt.file.pipe(_s((si)=>Tmt(si,Jn))),oi=Wt.file.pipe(_s((si)=>si._tag==="OAuth"&&cT(si,jt)),_s(()=>tt(Wt.env)||tt(cs))),vi=dQ([oi,Wt.env,Wt.file]);return yield*_c(`EXPAND_API_KEY is set but ${n} holds credentials from \`expandai login\` or agent setup, which take precedence. Unset EXPAND_API_KEY to silence this, or run \`expandai logout\` to use the API key.`).pipe(Si(()=>re(Wt.env)&&re(oi))),yield*_c(`Using EXPAND_API_KEY for ${Jn.origin} because the stored login was issued by a different API origin.`).pipe(Si(()=>re(Wt.env)&&re(cs))),yield*_c(`EXPAND_API_KEY overrides the API key stored in ${n}`).pipe(Si(()=>re(Wt.env)&&AQ(Wt.file,(si)=>si._tag==="ApiKey"))),{apiUrl:Jn,authMethod:vi,anonymousSession:Ot(Ne.anonymousSession),noAnonymous:De}}),U=W("saveConfig")(function*(ie){let De=yield*Eo(nh.Json)(ie);yield*M(De)}),_=W("updateConfig")(function*(ie){let De=yield*T,Ne=nh.make({...De.config,...ie}),it=yield*Eo(nh.Json)(Ne).pipe(L(Zl(I2))),Wt={...Mmt(De.raw,it)};if(Object.hasOwn(ie,"anonymousSession")&&ie.anonymousSession===void 0)delete Wt.anonymousSession;let jt=yield*Eo(I2)(Wt);yield*M(jt)});function Q(ie){return w().pipe(we(rh(n,_(ie))))}let F=W("readConfigFile")(function*(){return yield*T.pipe(ee(({config:ie})=>({config:ie,parseFailed:!1})),Ll(()=>({config:nh.make({}),parseFailed:!0})))}),Y=W("clearConfig")(function*(){let ie=yield*qt(T);if(Ut(ie)){if(!(ie.left instanceof aE))return yield*ie.left;yield*_c(`Could not parse ${n}; removing it. Telemetry preferences and apiUrl were not preserved.`),yield*t.remove(n).pipe(fe(()=>new iE({path:n})));return}let De={...ie.right.raw};delete De.authMethod,delete De.anonymousSession;let Ne=yield*Eo(I2)(De);yield*M(Ne)});function J(){return w().pipe(we(rh(n,Y())))}let le=W("getApiUrl")(function*(){let{config:ie}=yield*OMe,De=yield*O,Ne={env:Ot(ie.apiUrl),file:Ot(De.apiUrl)};return dQ([Ne.env,Ne.file]).pipe(Ue(()=>new URL(b2)))}),We=W("getAppUrl")(function*(){return yield*Lt("EXPAND_APP_URL").pipe(dr(wmt))}),Ke=W("getPlaygroundHost")(function*(){return yield*Lt("EXPAND_PLAYGROUND_HOST").pipe(dr(RC))});return{configPath:n,inspectSecureStorage:R,ensureSecureStorage:w,loadConfig:C,saveConfig:U,updateConfig:Q,clearConfig:J,readConfigFile:F,getApiUrl:le,getAppUrl:We,getPlaygroundHost:Ke}})}){}var vC="Open the approval page in your browser, type in the code shown here, and approve. Only enter this code on the Expand approval page your terminal named — never a code someone sent you, and never on a page from a link you did not expect. When you have approved, say so, and the same command will pick the authorization up.",R2="Authorization complete. That setup code has been consumed and cannot be reused.",k2="Expand is already authorized. Agent setup is complete.",x8="Expand is authorized, but not every harness could be configured. The harnesses that failed are listed under `failures`; the ones under `installations` are ready to use.",C8="Show these harnesses to the user and ask which to configure. Pass the chosen ones to `expandai init --harnesses`. Harnesses that are not chosen are left untouched.",S8="No supported agent harness was found on this machine. Do not ask the user to choose from an empty list. Tell them Expand supports claude-code, cursor, opencode, codex, and fx, and that setup cannot continue until one of them is installed.",Wo=G("claude-code","cursor","opencode","codex","fx");class T2 extends ve("InitDetectionResult")({schemaVersion:G(1),status:G("detected"),harnesses:Te(Wo),current:V(Wo),userMessage:G(C8,S8)}){}var I8=Tb(Wo),Qa=G("project","global"),_mt=G("webfetch-hook","runtime-skill","mcp"),Umt=G("unverified","observed","reload_required","blocked"),Cnr=G("authorization_required","completed"),Lmt=g.pipe(sn(20),yU(256)),Pmt=jm(Lmt,gA(g),{strict:!0,decode:(e)=>e,encode:()=>"<redacted-redacted-setup-token>"});class O2 extends ve("InitRequest")({harnesses:I8,scope:Qa,setupToken:V(Pmt)}){}var Hmt=P({schemaVersion:G(1),status:G("authorization_required"),harnesses:I8,scope:Qa,userMessage:G(vC),authorization:P({url:Km,userCode:g,approvalExpiresAt:Sf})}),Wmt=P({runtimeState:Umt,nextAction:g}),qmt=P({harness:Wo,configured:xe,changed:xe,components:Te(_mt),version:g,verification:Wmt}),Gmt=P({harness:Wo,code:g,recoverable:xe}),Vmt=P({schemaVersion:G(1),status:G("completed"),harnesses:I8,scope:Qa,userMessage:G(R2,k2,x8),auth:P({healthy:xe}),projectPath:V(g),installations:Tb(qmt),failures:V(Te(Gmt))}),lT=ze(Hmt,Vmt);class cE extends ve("InitErrorEnvelope")({schemaVersion:G(1),status:G("error"),code:g,message:g,recoverable:xe}){}var yu="expandai-cli-browser",Ymt=P({apiOrigin:g,clientId:G(yu),purpose:V(G("login","agent-setup")),harness:G("agent-harnesses"),scope:G("project","global"),canonicalScopeRoot:g});class mB extends ve("PendingInitRecord")({key:Ymt,deviceCode:gA(g),userCode:g,verificationUri:g,intervalSeconds:pe,nextPollAt:Sf,approvalExpiresAt:Sf}){}class sh extends nt()("PendingInitCorrupt",{path:g,error:Kt}){recoverable=!0;get message(){return`Pending authorization state at ${this.path} is corrupt and was left unchanged.`}}class b8 extends nt()("PendingInitStorageError",{path:g,error:Kt}){recoverable=!0;get message(){return`Could not access pending authorization state at ${this.path}.`}}class w8 extends ve("DeviceAuthorizationCreated")({deviceCode:gA($s),userCode:$s,verificationUri:Km,expiresIn:cr.pipe(xj()),interval:cr.pipe(N4e())}){}var zmt=P({access_token:gA($s),refresh_token:gA($s),token_type:$s,expires_in:pe.pipe(xj()),scope:V(g)}),Jmt=G("create","poll");class xu extends nt()("DeviceAuthorizationApiError",{operation:Jmt,kind:G("request_failed","rejected","invalid_response"),status:V(pe),recoverable:xe}){get message(){return this.kind==="rejected"?`Device authorization ${this.operation} was rejected. Restart authorization if the problem persists.`:`Device authorization ${this.operation} could not be completed safely. Try again.`}}class M2 extends xt()("@expandai/cli/Auth/DeviceAuthorizationClient",{dependencies:[td,bt.Default],effect:j(function*(){let e=yield*xg,t=yield*bt;function r(a,c,l){return new xu({operation:a,kind:c,status:l,recoverable:c!=="invalid_response"})}let n=W("DeviceAuthorizationClient.create")(function*(a){let c=yield*t.getApiUrl(),l=yield*fw(new URL("/v1/cli-authorization/device",c)).pipe(jc(a),fe(()=>r("create","request_failed")));return yield*e.execute(l).pipe(L((u)=>Pt(u.status).pipe(Be((p)=>p>=200&&p<300,()=>ki(w8)(u).pipe(fe(()=>r("create","invalid_response")))),bA(()=>u.text.pipe($r,we(r("create","rejected",u.status)))))),Ft((u)=>u instanceof xu?u:r("create","request_failed")))}),o=P({error:g,error_description:V(g)}),s=new Set(["invalid_target","invalid_client","invalid_scope","unsupported_grant_type","unauthorized_client","invalid_request"]),i=W("DeviceAuthorizationClient.poll")(function*(a){let c=yield*t.getApiUrl(),l=fw(new URL("/api/auth/oauth2/token",c)).pipe(zxe({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:Js(a),client_id:yu,resource:c.toString()}));return yield*e.execute(l).pipe(L(Ce(function*(u){return yield*Pt(u.status).pipe(Be((p)=>p>=200&&p<300,()=>ki(zmt)(u).pipe(fe(()=>r("poll","invalid_response")),ee((p)=>({_tag:"Tokens",token:p})))),Be((p)=>p>=500,()=>u.text.pipe($r,we(r("poll","rejected",u.status)))),bA(()=>ki(o)(u).pipe(fe(()=>r("poll","invalid_response")),ee((p)=>Pt(p.error).pipe(Be("authorization_pending",()=>({_tag:"Pending"})),Be("slow_down",()=>({_tag:"SlowDown"})),Be("access_denied",()=>({_tag:"Denied"})),Be("expired_token",()=>({_tag:"Expired"})),bA(()=>s.has(p.error)?{_tag:"Refused",error:p.error,...p.error_description===void 0?{}:{description:p.error_description}}:{_tag:"Invalid"}))))))})),Ft((u)=>u instanceof xu?u:r("poll","request_failed")))});return{create:n,poll:i}})}){}var ss="0.1.2";class FMe extends mx()("DeviceAuthorizationTokensSaved",{}){}class NMe extends mx()("DeviceAuthorizationPending",{}){}class vMe extends mx()("DeviceAuthorizationSlowDown",{}){}class _Me extends mx()("DeviceAuthorizationExpired",{}){}class UMe extends mx()("DeviceAuthorizationInvalid",{}){}class Tp extends nt()("DeviceAuthorizationDenied",{recoverable:G(!0)}){get message(){return"The authorization request was denied in the browser. Run the same command again to start a new one."}}class ih extends nt()("DeviceAuthorizationRefused",{error:g,description:V(g),recoverable:G(!1)}){get message(){let e=this.description===void 0?"":` — ${this.description}`;return`Expand refused to complete this authorization: ${this.error}${e}. This is a server-side configuration problem, not something a new code can fix. Do not start authorization again; report this error.`}}class ah extends nt()("DeviceAuthorizationCredentialSaveFailed",{recoverable:G(!1)}){get message(){return"Authorization succeeded, but credentials could not be saved. Start authorization again."}}function MMe(e){return e.platform??process.platform}class _C extends xt()("@expandai/cli/Auth/DeviceAuthorization",{dependencies:[bt.Default,M2.Default],effect:j(function*(){let e=yield*bt,t=yield*M2,r=W("DeviceAuthorization.create")(function*(s){yield*e.ensureSecureStorage();let i={platform:MMe(s),machineLabel:`${MMe(s)}-${process.arch}`,cliVersion:ss};return yield*s.purpose==="login"?t.create({purpose:"login",harness:"agent-harnesses",scope:"global",...i}):t.create({purpose:"agent-setup",harness:s.harness,scope:s.scope,...i})}),n=Ce(function*(s){let i=yield*Ya,a=yield*qt(e.updateConfig({authMethod:aT.make({accessToken:s.access_token,refreshToken:s.refresh_token,expiresAt:Sb(i,yl(s.expires_in)),clientId:yu})}));return yield*Qn(a,{onLeft:()=>new ah({recoverable:!1}),onRight:()=>ne})}),o=W("DeviceAuthorization.poll")(function*(s){let i=yield*t.poll(s);return yield*Pt(i).pipe(xr("Tokens",({token:a})=>n(a).pipe(hn(new FMe))),xr("Pending",()=>v(new NMe)),xr("SlowDown",()=>v(new vMe)),xr("Denied",()=>new Tp({recoverable:!0})),xr("Expired",()=>v(new _Me)),xr("Invalid",()=>v(new UMe)),xr("Refused",({error:a,description:c})=>new ih({error:a,...c===void 0?{}:{description:c},recoverable:!1})),Ar)});return{create:r,poll:o}})}){}import{createHash as $mt}from"node:crypto";var B8=zt(mB),jmt=300000,LMe=zt(ze(kb(g,G(yu),G("agent-harnesses"),G("project","global"),g),kb(g,G(yu),G("login"))));function Q8(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function Kmt(e){return e instanceof Ds&&(e.reason==="AlreadyExists"||Q8(e.cause,"EEXIST"))}function Zmt(e){return e instanceof Ds&&(e.reason==="NotFound"||Q8(e.cause,"ENOENT"))}function Xmt(e){return e.purpose==="login"?ts(LMe)([e.apiOrigin,e.clientId,e.purpose]):ts(LMe)([e.apiOrigin,e.clientId,e.harness,e.scope,e.canonicalScopeRoot])}function PMe(e,t){let r=e.dirname(t);return r===t?[t]:[t,...PMe(e,r)]}class ch extends xt()("@expandai/cli/Auth/PendingInitStore",{dependencies:[y3],effect:j(function*(){let e=yield*Lr,t=yield*Nr,r=t.join(yield*hB,"expandai"),n=t.join(r,"pending-init"),o=(S,w)=>new b8({path:S,error:w}),s=(S,w)=>w.pipe(fe((I)=>o(S,I))),i=Ce(function*(S){let w=yield*qt(e.readLink(S));if(xn(w))return yield*o(S,Error("Symbolic links are not allowed for pending authorization"));let I=w.left;if(I instanceof Ds&&(I.reason==="InvalidData"||I.reason==="NotFound"||I.method==="readLink"&&Q8(I.cause,"EINVAL")))return;return yield*o(S,I)}),a=Ce(function*(){if(yield*i(r),yield*i(n),yield*s(n,e.makeDirectory(n,{recursive:!0,mode:448})),yield*i(r),yield*i(n),(yield*s(n,e.stat(n))).type!=="Directory")return yield*o(n,Error("Pending authorization path is not a directory"));if(process.platform!=="win32")yield*s(r,e.chmod(r,448)),yield*s(n,e.chmod(n,448))}),c=(S)=>{let w=$mt("sha256").update(Xmt(S)).digest("hex");return t.join(n,`${w}.json`)},l=Ce(function*(S,w){let I=yield*Zl(B8)(w).pipe(fe(()=>new sh({path:S,error:Error("Stored pending authorization did not match the expected schema")})));if(c(I.key)!==S)return yield*new sh({path:S,error:Error("Stored pending authorization key did not match its file")});return I}),u=Ce(function*(S){if(yield*i(S),!(yield*s(S,e.exists(S))))return q();let I=yield*s(S,e.stat(S));if(I.type!=="File")return yield*o(S,Error("Pending state is not a regular file"));if(process.platform!=="win32"&&(I.mode&511)!==384)return yield*o(S,Error("Pending state file mode is not 600"));let M=yield*s(S,e.readFileString(S));return H(yield*l(S,M))}),p=(S)=>u(c(S)),f=Ce(function*(S){let w=PD(yield*Ya);return PD(S.approvalExpiresAt)+jmt<=w}),d=Ce(function*(S){yield*a();let w=c(S.key),I=yield*Eo(B8)(S).pipe(fe((T)=>o(w,T))),M=yield*qt(Ur(j(function*(){let T=yield*e.open(w,{flag:"wx",mode:384});yield*T.writeAll(new TextEncoder().encode(I)),yield*T.sync})));if(Ut(M)){if(Kmt(M.left))return!1;return yield*e.remove(w).pipe($r),yield*o(w,M.left)}if(process.platform!=="win32"){let T=yield*qt(e.chmod(w,384));if(Ut(T))return yield*e.remove(w).pipe($r),yield*o(w,T.left)}return!0}),A=W("PendingInitStore.replaceIfMatch")(function*(S,w){yield*a();let I=c(w.key);if(c(S.key)!==I)return yield*o(I,Error("Pending authorization replacement changed its key"));let M=yield*u(I);if(tt(M)||M.value.userCode!==S.userCode)return!1;let T=yield*Eo(B8)(w).pipe(fe((U)=>o(I,U))),O=`${I}.${process.pid}.${Math.random().toString(36).slice(2,10)}.tmp`,C=yield*Ur(Tn(v(O),()=>e.remove(O).pipe($r)).pipe(we(j(function*(){yield*i(O),yield*Ur(j(function*(){let U=yield*e.open(O,{flag:"wx",mode:384});yield*U.writeAll(new TextEncoder().encode(T)),yield*U.sync})),yield*e.rename(O,I)})))).pipe(qt);if(Ut(C))return yield*o(I,C.left);return!0}),m=Ce(function*(S){let w=c(S.key),I=yield*u(w);if(tt(I)||I.value.userCode!==S.userCode)return!1;return yield*s(w,e.remove(w)),!0}),E=W("PendingInitStore.get")(function*(S){let w=yield*p(S);if(tt(w)||!(yield*f(w.value)))return w;return yield*m(w.value),q()}),x=W("PendingInitStore.peek")(function*(S){return yield*p(S)}),B=W("PendingInitStore.putIfAbsent")(function*(S){let w=yield*p(S.key);if(re(w)&&!(yield*f(w.value)))return w.value;if(re(w))yield*m(w.value);if(yield*d(S))return S;let I=yield*p(S.key);return yield*Me(I,{onNone:()=>o(c(S.key),Error("Pending record creation lost without a winner")),onSome:v})}),b=W("PendingInitStore.removeIfMatch")((S)=>m(S)),k=W("PendingInitStore.removeCorrupt")(function*(S){let w=c(S),I=yield*qt(u(w));if(xn(I))return!1;if(!(I.left instanceof sh))return yield*I.left;let M=yield*qt(e.remove(w));if(Ut(M)&&Zmt(M.left))return!1;if(Ut(M))return yield*o(w,M.left);return!0}),D=W("PendingInitStore.pruneExpired")(function*(){if(yield*i(n),!(yield*s(n,e.exists(n))))return 0;let w=yield*s(n,e.readDirectory(n));return(yield*ot(w.filter((M)=>M.endsWith(".json")),(M)=>j(function*(){let T=yield*u(t.join(n,M));if(tt(T)||!(yield*f(T.value)))return 0;return(yield*m(T.value))?1:0}).pipe(Ll(()=>0)))).reduce((M,T)=>M+T,0)}),R=W("PendingInitStore.canonicalScopeRoot")(function*(S,w=process.cwd()){if(S==="global")return"global";let I=yield*s(w,e.realPath(w)),T=(yield*ot(PMe(t,I),(O)=>s(O,e.exists(t.join(O,".git"))).pipe(ee((C)=>({candidate:O,exists:C}))))).find(({exists:O})=>O)?.candidate;return T===void 0?I:yield*s(T,e.realPath(T))});return{pendingPath:n,get:E,peek:x,putIfAbsent:B,replaceIfMatch:A,removeIfMatch:b,removeCorrupt:k,pruneExpired:D,canonicalScopeRoot:R}})}){}var egt=yu,tgt=5;class uT extends ve("ManualAuthorizationInput")({purpose:N(G("login","agent-setup"),{default:()=>"agent-setup"}),harness:G("agent-harnesses"),scope:Qa,cwd:V(g),platform:V(g)}){}class D8 extends ve("ManualAuthorizationRequired")({verificationUri:g,userCode:$s,approvalExpiresAt:Sf}){}class R8 extends mx()("TokensSaved",{}){}class lE extends mx()("AuthorizationPending",{pending:D8}){}var Xnr=ze(R8,lE);function gB(e){return new D8({verificationUri:e.verificationUri,userCode:e.userCode,approvalExpiresAt:e.approvalExpiresAt})}class Cu extends xt()("@expandai/cli/Auth/ManualAuthorization",{dependencies:[bt.Default,ch.Default,_C.Default],effect:j(function*(){let e=yield*bt,t=yield*ch,r=yield*_C,n=Ce(function*(l){yield*e.ensureSecureStorage(),yield*t.pruneExpired();let u=yield*e.getApiUrl(),p=yield*t.canonicalScopeRoot(l.scope,l.cwd);return{apiOrigin:u.origin,clientId:egt,purpose:l.purpose,harness:l.harness,scope:l.scope,canonicalScopeRoot:p}}),o=Ce(function*(l,u){let p=l.platform===void 0?{}:{platform:l.platform},f=yield*r.create(l.purpose==="login"?{purpose:"login",...p}:{purpose:"agent-setup",harness:l.harness,scope:l.scope,...p}),d=yield*Ya,A=new mB({key:u,deviceCode:f.deviceCode,userCode:f.userCode,verificationUri:f.verificationUri.toString(),intervalSeconds:f.interval,nextPollAt:Sb(d,yl(f.interval)),approvalExpiresAt:Sb(d,yl(f.expiresIn))}),m=yield*qt(t.putIfAbsent(A));if(Ut(m))return yield*m.left;return m.right}),s=Ce(function*(l,u){let p=yield*Ya,f=l.intervalSeconds+(u?tgt:0),d=new mB({...l,intervalSeconds:f,nextPollAt:Sb(p,yl(f))}),A=yield*qt(t.replaceIfMatch(l,d));if(Ut(A))return l;return A.right?d:l}),i=Ce(function*(l,u){let p=yield*qt(t.get(u));if(xn(p))return p.right;if(l.purpose!=="login"||!(p.left instanceof sh))return yield*p.left;return yield*t.removeCorrupt(u),yield*t.get(u)}),a=W("ManualAuthorization.advance")(function*(l){let u=yield*n(l),p=yield*i(l,u);if(tt(p)){let E=yield*o(l,u);return new lE({pending:gB(E)})}let f=p.value,d=yield*Ya;if(o4e(d,f.approvalExpiresAt)){yield*t.removeIfMatch(f);let E=yield*o(l,u);return new lE({pending:gB(E)})}if(lU(d,f.nextPollAt))return new lE({pending:gB(f)});let A=yield*qt(r.poll(f.deviceCode)),m=Ce(function*(){yield*t.removeIfMatch(f);let E=yield*o(l,u);return new lE({pending:gB(E)})});return yield*Qn(A,{onLeft:(E)=>t.removeIfMatch(f).pipe(Si(()=>E instanceof Tp),we(ce(E))),onRight:(E)=>Pt(E).pipe(xr("DeviceAuthorizationTokensSaved",()=>t.removeIfMatch(f).pipe(hn(new R8))),xr("DeviceAuthorizationPending",()=>s(f,!1).pipe(ee((x)=>new lE({pending:gB(x)})))),xr("DeviceAuthorizationSlowDown",()=>s(f,!0).pipe(ee((x)=>new lE({pending:gB(x)})))),xr("DeviceAuthorizationExpired",m),xr("DeviceAuthorizationInvalid",m),Ar)})}),c=W("ManualAuthorization.redeemPreApproved")(function*(l){let u=yield*r.poll(l);function p(){return new xu({operation:"poll",kind:"rejected",status:400,recoverable:!1})}return yield*Pt(u).pipe(xr("DeviceAuthorizationTokensSaved",()=>ne),xr("DeviceAuthorizationPending",p),xr("DeviceAuthorizationSlowDown",p),xr("DeviceAuthorizationExpired",p),xr("DeviceAuthorizationInvalid",p),Ar)});return{advance:a,redeemPreApproved:c}})}){}var HMe="Authorization complete. Expand is ready to use; retry the command that required authentication.",rgt=G("authorization_internal_error","authorization_unreachable","authorization_rejected","authorization_service_unavailable","authorization_invalid_response","authorization_denied","authorization_refused","credential_save_failed","credential_storage_insecure");class pc extends nt()("DeviceLoginError",{code:rgt,recoverable:xe,httpStatus:V(pe)}){get message(){switch(this.code){case"authorization_internal_error":return"Authorization failed for an unexpected internal reason. Do not retry in a loop; report this error.";case"authorization_unreachable":return"Could not reach the Expand API. Nothing was changed: any pending authorization is still pending, and if none existed, none was started. Do not retry until the connection is fixed; then run the same command again.";case"authorization_rejected":return"The Expand API rejected the device authorization request. Retry later; if this persists, the CLI and API versions may be incompatible.";case"authorization_service_unavailable":return`The Expand device authorization service is unavailable${this.httpStatus===void 0?"":` (HTTP ${this.httpStatus})`}. Retry later or use the staging API for an isolated test.`;case"authorization_invalid_response":return"The Expand API returned an invalid device authorization response. Do not continue with a URL or code from this response; update the CLI or report the problem.";case"authorization_denied":return"The authorization was denied in the browser. If that was unintended, run the same command again for a fresh approval code.";case"authorization_refused":return"Expand refused to complete the authorization for a reason a new code cannot fix. Do not start another authorization; report the error.";case"credential_save_failed":return"Authorization completed, but credentials could not be saved. Fix credential storage before starting again.";case"credential_storage_insecure":return"Credential storage is not secure enough to continue."}}}class N2 extends ve("DeviceLoginErrorEnvelope")({schemaVersion:G(1),status:G("error"),code:g,message:g,recoverable:xe}){}var ngt=P({schemaVersion:G(1),status:G("authorization_required"),userMessage:G(vC),authorization:P({url:Km,userCode:$s,approvalExpiresAt:Sf})}),ogt=P({schemaVersion:G(1),status:G("completed"),userMessage:G(HMe),auth:P({healthy:G(!0)})}),F2=ze(ngt,ogt);function sgt(e){if(e instanceof uc)return new pc({code:"credential_storage_insecure",recoverable:!1});if(e instanceof Tp)return new pc({code:"authorization_denied",recoverable:!0});if(e instanceof ih)return new pc({code:"authorization_refused",recoverable:!1});if(e instanceof ah)return new pc({code:"credential_save_failed",recoverable:!1});if(e instanceof xu)switch(e.kind){case"request_failed":return new pc({code:"authorization_unreachable",recoverable:!0});case"rejected":if(e.status!==void 0&&e.status>=500)return new pc({code:"authorization_service_unavailable",recoverable:!0,httpStatus:e.status});return new pc({code:"authorization_rejected",recoverable:e.recoverable});case"invalid_response":return new pc({code:"authorization_invalid_response",recoverable:!1})}return new pc({code:"authorization_internal_error",recoverable:!1})}class pT extends xt()("@expandai/cli/Auth/DeviceLogin",{dependencies:[Cu.Default],effect:j(function*(){let e=yield*Cu;return{run:W("DeviceLogin.run")(function*(){let r=yield*e.advance(new uT({purpose:"login",harness:"agent-harnesses",scope:"global"})).pipe(fe(sgt));return yield*Pt(r).pipe(xr("TokensSaved",()=>er(F2)({schemaVersion:1,status:"completed",userMessage:HMe,auth:{healthy:!0}}).pipe(fe(()=>new pc({code:"authorization_internal_error",recoverable:!1})))),xr("AuthorizationPending",({pending:n})=>er(F2)({schemaVersion:1,status:"authorization_required",userMessage:vC,authorization:{url:n.verificationUri,userCode:n.userCode,approvalExpiresAt:lx(n.approvalExpiresAt)}}).pipe(fe(()=>new pc({code:"authorization_internal_error",recoverable:!1})))),Ar)})}})}){}class v2 extends nt()("SetupGrantAuthorizationError",{code:G("invalid_or_expired","stored_credential_conflict","request_failed","denied","credential_save_failed","refused","config_unreadable"),recoverable:xe}){get message(){switch(this.code){case"stored_credential_conflict":return"An Expand API key is already stored on this machine, and completing this setup would replace it with no way to recover it. Nothing was changed and your setup prompt is still valid. Run `expandai logout` to clear the stored key, then run this setup command again.";case"request_failed":return"Could not reach Expand to redeem the setup token. Nothing was sent, so the same token is still good — check the network and try again.";case"denied":return"This setup authorization was denied. Copy a fresh setup prompt from the Expand dashboard.";case"config_unreadable":return"The Expand config file on this machine could not be read, so setup cannot tell whether completing it would overwrite an existing API key. Nothing was redeemed and your setup prompt is still valid. Run `expandai whoami` to see which file it is, fix or delete it, then run this setup command again.";case"refused":return"Expand refused to redeem this setup token for a reason a fresh prompt cannot fix — most likely an OAuth client, resource, or scope misconfiguration on the server. Do not request another prompt; report this.";case"credential_save_failed":return"The setup token was redeemed, but the credentials could not be saved on this machine. Fix credential storage — run `expandai whoami` to see the path it uses, and check its permissions — then copy a fresh setup prompt from the Expand dashboard.";default:return"The setup token is invalid, expired, or already used. Copy a fresh setup prompt from the Expand dashboard."}}}function UC(e){return new v2({code:e,recoverable:e!=="denied"&&e!=="credential_save_failed"&&e!=="refused"})}class EB extends xt()("@expandai/cli/Auth/SetupGrantAuthorization",{dependencies:[bt.Default,Cu.Default],effect:j(function*(){let e=yield*bt,t=yield*Cu;return{authorize:W("SetupGrantAuthorization.authorize")(function*(n){let o=yield*e.readConfigFile();if(o.parseFailed)return yield*UC("config_unreadable");if(o.config.authMethod?._tag==="ApiKey")return yield*UC("stored_credential_conflict");yield*Hy({harness:n.harness,scope:n.scope}),yield*t.redeemPreApproved(n.setupToken).pipe(fe((s)=>{if(s instanceof Tp)return UC("denied");if(s instanceof ah)return UC("credential_save_failed");if(s instanceof ih)return UC("refused");if(s instanceof xu&&s.kind==="request_failed")return UC("request_failed");return UC("invalid_or_expired")}))})}})}){}import lFe from"node:process";import G8 from"node:path";import{fileURLToPath as Wgt}from"node:url";import qgt from"node:child_process";import Ggt,{constants as Vgt}from"node:fs/promises";import ggt from"node:path";import{promisify as Egt}from"node:util";import ygt from"node:child_process";import N8,{constants as KMe}from"node:fs/promises";import GMe from"node:process";import ugt from"node:os";import M8 from"node:fs";import cgt from"node:fs";import WMe from"node:fs";var k8;function igt(){try{return WMe.statSync("/.dockerenv"),!0}catch{return!1}}function agt(){try{return WMe.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function T8(){if(k8===void 0)k8=igt()||agt();return k8}var O8,lgt=()=>{try{return cgt.statSync("/run/.containerenv"),!0}catch{return!1}};function LC(){if(O8===void 0)O8=lgt()||T8();return O8}var qMe=()=>{if(GMe.platform!=="linux")return!1;if(ugt.release().toLowerCase().includes("microsoft")){if(LC())return!1;return!0}try{if(M8.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!LC()}catch{}if(M8.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||M8.existsSync("/run/WSL"))return!LC();return!1},rd=GMe.env.__IS_WSL_TEST__?qMe:qMe();import VMe from"node:process";import{Buffer as pgt}from"node:buffer";import{promisify as fgt}from"node:util";import dgt from"node:child_process";var Agt=fgt(dgt.execFile),F8=()=>`${VMe.env.SYSTEMROOT||VMe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var YMe=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],zMe=(e)=>pgt.from(e,"utf16le").toString("base64"),hgt=(e)=>`'${String(e).replaceAll(/['‘’‚‛]/g,(t)=>t+t)}'`,JMe=(e)=>[...YMe,zMe(e)],mgt=(e)=>({encoding:"utf8",...e,shell:!1}),Su=async(e,t={})=>{let{powerShellPath:r,...n}=t;return Agt(r??F8(),JMe(e),mgt(n))};Su.argumentsPrefix=YMe;Su.encodeCommand=zMe;Su.escapeArgument=hgt;Su.createArguments=JMe;function $Me(e){for(let t of e.split(`
294
294
  `)){if(/^\s*#/.test(t))continue;let r=/^\s*root\s*=\s*(?<mountPoint>"[^"]*"|'[^']*'|[^#]*)/.exec(t);if(!r)continue;return r.groups.mountPoint.trim().replaceAll(/^["']|["']$/g,"")}}var xgt=Egt(ygt.execFile),Cgt=(()=>{let t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await N8.access(r,KMe.F_OK),n=!0}catch{}if(!n)return"/mnt/";let o=await N8.readFile(r,{encoding:"utf8"}),s=$Me(o);if(s===void 0)return"/mnt/";return t=s,t=t.endsWith("/")?t:`${t}/`,t}})(),Sgt=async()=>`${await Cgt()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,_2=rd?Sgt:F8,jMe,ZMe=async()=>(jMe??=(async()=>{try{let e=await _2();return await N8.access(e,KMe.X_OK),!0}catch{return!1}})(),jMe),XMe=async()=>{let e=await _2(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await Su(t,{powerShellPath:e,cwd:ggt.dirname(e)});return r.trim()},Igt=(e)=>/^[a-z]+:\/\//i.test(e),bgt=async(e,t)=>{let r=t.startsWith("-")?[e,"--",t]:[e,t];try{let{stdout:n}=await xgt("wslpath",r,{encoding:"utf8"});return n.replace(/\r?\n$/,"")||t}catch{return t}},eFe=async(e)=>{let t=Array.isArray(e),n=await Promise.all((t?e:[e]).map((o)=>Igt(o)?o:bgt("-aw",o)));return t?n:n[0]};function PC(e,t,r){let n=(o)=>Object.defineProperty(e,t,{value:o,enumerable:!0,writable:!0});return Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){let o=r();return n(o),o},set(o){n(o)}}),e}import{promisify as _gt}from"node:util";import P8 from"node:process";import{execFile as Ugt}from"node:child_process";import{promisify as wgt}from"node:util";import Bgt from"node:process";import{execFile as Qgt}from"node:child_process";var Dgt=wgt(Qgt);async function v8(){if(Bgt.platform!=="darwin")throw Error("macOS only");let{stdout:e}=await Dgt("defaults",["read","com.apple.LaunchServices/com.apple.launchservices.secure","LSHandlers"]),r=/LSHandlerRoleAll = "(?!-)(?<id>[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(e)?.groups.id??"com.apple.Safari";if(r==="com.apple.safari")return"com.apple.Safari";return r}import Rgt from"node:process";import{promisify as kgt}from"node:util";import{execFile as Tgt,execFileSync as $or}from"node:child_process";var Ogt=kgt(Tgt);async function tFe(e,{humanReadableOutput:t=!0,signal:r}={}){if(Rgt.platform!=="darwin")throw Error("macOS only");let n=t?[]:["-ss"],o={};if(r)o.signal=r;let{stdout:s}=await Ogt("osascript",["-e",e,n],o);return s.trim()}var Mgt=/^[^\n\r"\\]+$/u;async function _8(e){if(typeof e!=="string")throw TypeError("Expected a string bundle identifier");if(!Mgt.test(e))throw TypeError(`Invalid bundle identifier: ${JSON.stringify(e)}`);return tFe(`tell application "Finder" to set app_path to application file id "${e}" as string
295
295
  tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import rFe from"node:process";import{promisify as Fgt}from"node:util";import{execFile as Ngt}from"node:child_process";var vgt=Fgt(Ngt),U2={MSEdgeHTM:{name:"Edge",id:"com.microsoft.edge"},MSEdgeBHTML:{name:"Edge Beta",id:"com.microsoft.edge.beta"},MSEdgeDHTML:{name:"Edge Dev",id:"com.microsoft.edge.dev"},AppXq0fevzme2pys62n3e0fbqa7peapykr8v:{name:"Edge",id:"com.microsoft.edge.old"},ChromeHTML:{name:"Chrome",id:"com.google.chrome"},ChromeBHTML:{name:"Chrome Beta",id:"com.google.chrome.beta"},ChromeDHTML:{name:"Chrome Dev",id:"com.google.chrome.dev"},ChromiumHTM:{name:"Chromium",id:"org.chromium.Chromium"},BraveHTML:{name:"Brave",id:"com.brave.Browser"},BraveBHTML:{name:"Brave Beta",id:"com.brave.Browser.beta"},BraveDHTML:{name:"Brave Dev",id:"com.brave.Browser.dev"},BraveSSHTM:{name:"Brave Nightly",id:"com.brave.Browser.nightly"},FirefoxURL:{name:"Firefox",id:"org.mozilla.firefox"},OperaStable:{name:"Opera",id:"com.operasoftware.Opera"},VivaldiHTM:{name:"Vivaldi",id:"com.vivaldi.Vivaldi"},"IE.HTTP":{name:"Internet Explorer",id:"com.microsoft.ie"}},U8=new Map(Object.entries(U2));class nFe extends Error{}async function L8(e=vgt){let t=`${rFe.env.SYSTEMROOT??rFe.env.windir??"C:\\Windows"}\\System32\\reg.exe`,{stdout:r}=await e(t,["QUERY"," HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice","/v","ProgId"]),n=/ProgId\s*REG_SZ\s*(?<id>\S+)/.exec(r);if(!n)throw new nFe(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:o}=n.groups,s=o.lastIndexOf("."),i=o.lastIndexOf("-"),a=s===-1?void 0:o.slice(0,s),c=i===-1?void 0:o.slice(0,i);return U2[o]??U2[a]??U2[c]??{name:o,id:o}}var Lgt=_gt(Ugt),Pgt=(e)=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(t)=>t.toUpperCase());async function H8(){if(P8.platform==="darwin"){let e=await v8();return{name:await _8(e),id:e}}if(P8.platform==="linux"){let{stdout:e}=await Lgt("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:Pgt(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(P8.platform==="win32")return L8();throw Error("Only macOS, Linux, and Windows are supported")}import W8 from"node:process";var Hgt=Boolean(W8.env.SSH_CONNECTION||W8.env.SSH_CLIENT||W8.env.SSH_TTY),oFe=Hgt;var L2=Symbol("fallbackAttempt"),q8=import.meta.url?G8.dirname(Wgt(import.meta.url)):"",sFe=G8.join(q8,"xdg-open"),{platform:HC,arch:iFe}=lFe,aFe=async(e,t)=>{if(e.length===0)return;let r=[];for(let n of e)try{return await t(n)}catch(o){r.push(o)}throw AggregateError(r,"Failed to open in all supported apps")},P2=async(e)=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[L2]===!0;if(delete e[L2],Array.isArray(e.app))return aFe(e.app,(l)=>P2({...e,app:l,[L2]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return aFe(r,(l)=>P2({...e,app:{name:l,arguments:n},[L2]:!0}));if(r==="browser"||r==="browserPrivate"){let l={"com.google.chrome":"chrome","google-chrome.desktop":"chrome","com.brave.browser":"brave","org.mozilla.firefox":"firefox","firefox.desktop":"firefox","com.microsoft.msedge":"edge","com.microsoft.edge":"edge","com.microsoft.edgemac":"edge","microsoft-edge.desktop":"edge","com.apple.safari":"safari"},u={chrome:"--incognito",brave:"--incognito",firefox:"--private-window",edge:"--inPrivate"},p;if(rd){let d=await XMe();p=U8.get(d)??{}}else p=await H8();let f=p.id?.toLowerCase();if(Object.hasOwn(l,f)){let d=l[f];if(r==="browserPrivate"){if(d==="safari")throw Error("Safari doesn't support opening in private mode via command line");n.push(u[d])}return P2({...e,app:{name:yB[d],arguments:n}})}throw Error(`${p.name} is not supported as a default browser`)}let o,s=[],i={},a=!1;if(rd&&!LC()&&!oFe&&!r)a=await ZMe();if(HC==="darwin"){if(o="open",e.wait)s.push("--wait-apps");if(e.background)s.push("--background");if(e.newInstance)s.push("--new");if(r)s.push("-a",r)}else if(HC==="win32"||a){if(o=await _2(),s.push(...Su.argumentsPrefix),!rd)i.windowsVerbatimArguments=!0;if(rd&&e.target)e.target=await eFe(e.target);let l=["$ProgressPreference = 'SilentlyContinue';","Start"];if(e.wait)l.push("-Wait");if(r){if(l.push(Su.escapeArgument(r)),e.target)n.push(e.target)}else if(e.target)l.push(Su.escapeArgument(e.target));if(n.length>0)n=n.map((u)=>Su.escapeArgument(u)),l.push("-ArgumentList",n.join(","));if(e.target=Su.encodeCommand(l.join(" ")),!e.wait)i.stdio="ignore";if(rd)i.cwd=G8.dirname(o)}else{if(r)o=r;else{let l=!q8||q8==="/",u=!1;try{await Ggt.access(sFe,Vgt.X_OK),u=!0}catch{}o=lFe.versions.electron??(HC==="android"||l||!u)?"xdg-open":sFe}if(n.length>0)s.push(...n);if(!e.wait)i.stdio="ignore",i.detached=!0}if(HC==="darwin"&&n.length>0)s.push("--args",...n);if(e.target)s.push(e.target);let c=qgt.spawn(o,s,i);if(e.wait)return new Promise((l,u)=>{c.once("error",u),c.once("close",(p)=>{if(!e.allowNonzeroExitCode&&p!==0){u(Error(`Exited with code ${p}`));return}l(c)})});if(t||HC==="win32"||a)return new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.once("close",(p)=>{if(c.off("error",u),t&&p!==0){u(Error(`Exited with code ${p}`));return}c.unref(),l(c)})})});return c.unref(),new Promise((l,u)=>{c.once("error",u),c.once("spawn",()=>{c.off("error",u),l(c)})})},Ygt=(e,t)=>{if(typeof e!=="string")throw TypeError("Expected a `target`");return P2({...t,target:e})};function cFe(e){if(typeof e==="string"||Array.isArray(e))return e;let{[iFe]:t}=e;if(!t)throw Error(`${iFe} is not supported`);return t}function fT({[HC]:e},{wsl:t}={}){if(t&&rd)return cFe(t);if(!e)throw Error(`${HC} is not supported`);return cFe(e)}var yB={browser:"browser",browserPrivate:"browserPrivate"};PC(yB,"chrome",()=>fT({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium","chromium-browser"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));PC(yB,"brave",()=>fT({darwin:"brave browser",win32:"brave",linux:["brave-browser","brave"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe",x64:["/mnt/c/Program Files/BraveSoftware/Brave-Browser/Application/brave.exe","/mnt/c/Program Files (x86)/BraveSoftware/Brave-Browser/Application/brave.exe"]}}));PC(yB,"firefox",()=>fT({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));PC(yB,"edge",()=>fT({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));PC(yB,"safari",()=>fT({darwin:"Safari"}));var uFe=Ygt;class pFe extends G("off","compact","detailed"){}class zgt extends P({include:N(g,{nullable:!0}),appendixMarkers:N(pFe,{nullable:!0})}){}class fFe extends G("off","compact","detailed"){}class dFe extends G("auto","never","always"){}class Jgt extends ve("FetchFetchRequest")({url:g,include:N(P({html:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),markdown:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),screenshot:N(ze(xe,P({fullPage:N(xe,{nullable:!0})})),{nullable:!0}),links:N(ze(xe,P({sameDomainOnly:N(xe,{nullable:!0,default:()=>!0}),includePatterns:N(Te(g),{nullable:!0}),excludePatterns:N(Te(g),{nullable:!0})})),{nullable:!0}),meta:N(xe,{nullable:!0,default:()=>!0}),response:N(P({includeHeaders:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:N(xe,{nullable:!0,default:()=>!1}),appendix:N(xe,{nullable:!0}),appendixMarkers:N(fFe,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),highlights:N(P({query:g,maxResults:N(cr.pipe(kr(1),Vi(50)),{nullable:!0,default:()=>5}),minScore:N(pe.pipe(kr(0),Vi(1)),{nullable:!0,default:()=>0.6})}),{nullable:!0}),browserConfig:N(P({scrollFullPage:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:N(P({maxPages:N(cr.pipe(kr(1)),{nullable:!0}),maxAudioSeconds:N(cr.pipe(kr(1),Vi(14400)),{nullable:!0,default:()=>3600}),ocr:N(dFe,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class AFe extends G("Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"){}class hFe extends G("symbol"){}class mFe extends ze(g,pe,P({_tag:hFe,key:g})){}class gFe extends P({_tag:AFe,path:Te(mFe),message:g}){}class EFe extends G("HttpApiDecodeError"){}class pE extends P({issues:Te(gFe),message:g,_tag:EFe}){}class yFe extends G("BadRequest"){}class hT extends P({message:g,_tag:yFe}){}class H2 extends ze(pE,hT){}class xFe extends G("InvalidApiKey","InvalidToken","InvalidSession","InvalidTenant"){}class CFe extends G("AuthFailed"){}class Iu extends ve("AuthFailed")({reason:xFe,description:N(ze(g,P({message:g})),{nullable:!0}),_tag:CFe}){}class mT extends g{}class SFe extends G("FetchBlocked"){}class W2 extends P({url:g,blockedType:N(g,{nullable:!0}),_tag:SFe}){}class q2 extends ze(P({organizationId:g.pipe(sn(1)),blockedUntil:N(ze(mT,$m),{nullable:!0}),_tag:G("AccessBlocked")}),W2){}class IFe extends G("FetchOriginHttpError"){}class bFe extends G(404){}class dT extends ve("FetchOriginNotFound")({_tag:IFe,url:g,statusCode:bFe,contentType:N(g,{nullable:!0})}){}class wFe extends G("FetchOriginHttpError"){}class BFe extends G(410){}class AT extends ve("FetchOriginGone")({_tag:wFe,url:g,statusCode:BFe,contentType:N(g,{nullable:!0})}){}class QFe extends G("PayloadTooLarge"){}class bu extends P({_tag:QFe}){}class DFe extends G("transfer_bytes","domsnapshot_bytes","ast_bytes","document_frame_bytes","document_pages","audio_seconds"){}class RFe extends G("FetchPageTooLarge"){}class G2 extends P({url:g,limitKind:N(DFe,{nullable:!0}),limitBytes:N(pe,{nullable:!0}),measuredBytes:N(pe,{nullable:!0}),limit:N(pe,{nullable:!0}),measured:N(pe,{nullable:!0}),_tag:RFe}){}class kFe extends ze(bu,G2){}class TFe extends G("FetchUnsupportedContentType"){}class xB extends ve("FetchUnsupportedContentType")({url:g,contentType:N(g,{nullable:!0}),_tag:TFe}){}class OFe extends G("private","removed","geoRestricted","ageRestricted","membersOnly","live","upcoming","unknown"){}class MFe extends G("FetchVideoUnavailable"){}class CB extends ve("FetchVideoUnavailable")({url:g,availability:OFe,message:N(g,{nullable:!0}),_tag:MFe}){}class FFe extends G(!0){}class NFe extends G("TooManyRequests"){}class uE extends P({retryable:N(FFe,{default:()=>!0}),retryAfterSeconds:N(pe,{nullable:!0}),_tag:NFe}){}class vFe extends G(!0){}class _Fe extends G("FetchConcurrencyLimitExceeded"){}class V2 extends P({retryable:N(vFe,{default:()=>!0}),retryAfterSeconds:pe,maxConcurrency:pe,message:N(g,{nullable:!0}),requestId:N(g,{nullable:!0}),_tag:_Fe}){}class Y2 extends ze(uE,V2){}class UFe extends G(!0){}class LFe extends G("InternalError"){}class il extends ve("InternalError")({retryable:N(UFe,{default:()=>!0}),_tag:LFe}){}class PFe extends G("pageNeverSettled","capabilityFailed"){}class HFe extends G(!1){}class WFe extends G("FetchCaptureFailed"){}class z2 extends P({url:g,failureType:PFe,retryable:N(HFe,{default:()=>!1}),_tag:WFe}){}class qFe extends G("browserInternalDocument"){}class GFe extends G(!1){}class VFe extends G("FetchNavigationFailed"){}class SB extends P({url:g,failureType:qFe,retryable:N(GFe,{default:()=>!1}),_tag:VFe}){}class YFe extends G("FetchOriginHttpError"){}class J2 extends P({url:g,statusCode:pe,contentType:N(g,{nullable:!0}),_tag:YFe}){}class zFe extends ze(z2,SB,J2){}class JFe extends G("cancelled_before_start","cancelled_after_start","unknown"){}class $Fe extends G(!0){}class jFe extends G("ServiceUnavailable"){}class wu extends P({message:N(g,{nullable:!0}),requestId:N(g,{nullable:!0}),dispatchOutcome:N(JFe,{nullable:!0}),retryable:N($Fe,{default:()=>!0}),_tag:jFe}){}class KFe extends G("ocr","transcription","video"){}class ZFe extends G("FetchDocumentProcessingUnavailable"){}class $2 extends P({url:g,operation:KFe,message:g,_tag:ZFe}){}class XFe extends ze(wu,$2){}class eNe extends G(!1){}class tNe extends G("FetchCaptureTimeout"){}class fE extends ve("FetchCaptureTimeout")({url:g,timeoutMs:N(pe,{nullable:!0}),retryable:N(eNe,{default:()=>!1}),_tag:tNe}){}class rNe extends G(!0){}class nNe extends G("FetchCapacityTimeout"){}class dE extends ve("FetchCapacityTimeout")({url:g,timeoutMs:N(pe,{nullable:!0}),retryable:N(rNe,{default:()=>!0}),_tag:nNe}){}class oNe extends G("off","compact","detailed"){}class $gt extends P({include:N(g,{nullable:!0}),appendixMarkers:N(oNe,{nullable:!0})}){}class sNe extends G("off","compact","detailed"){}class iNe extends G("auto","never","always"){}class jgt extends ve("FetchFetchJsonRequest")({url:g,include:N(P({html:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),markdown:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),screenshot:N(ze(xe,P({fullPage:N(xe,{nullable:!0})})),{nullable:!0}),links:N(ze(xe,P({sameDomainOnly:N(xe,{nullable:!0,default:()=>!0}),includePatterns:N(Te(g),{nullable:!0}),excludePatterns:N(Te(g),{nullable:!0})})),{nullable:!0}),meta:N(xe,{nullable:!0,default:()=>!0}),response:N(P({includeHeaders:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:N(xe,{nullable:!0,default:()=>!1}),appendix:N(xe,{nullable:!0}),appendixMarkers:N(sNe,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),highlights:N(P({query:g,maxResults:N(cr.pipe(kr(1),Vi(50)),{nullable:!0,default:()=>5}),minScore:N(pe.pipe(kr(0),Vi(1)),{nullable:!0,default:()=>0.6})}),{nullable:!0}),browserConfig:N(P({scrollFullPage:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:N(P({maxPages:N(cr.pipe(kr(1)),{nullable:!0}),maxAudioSeconds:N(cr.pipe(kr(1),Vi(14400)),{nullable:!0,default:()=>3600}),ocr:N(iNe,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class aNe extends G(1){}class lh extends cr{}class cNe extends P({sameDomain:pe,external:pe}){}class lNe extends P({blocks:pe,approxTokens:pe}){}class uNe extends P({evidenceId:N(pe,{nullable:!0}),links:pe,approxTokens:pe,label:N(g,{nullable:!0}),preview:N(g,{nullable:!0}),moreBlocks:N(pe,{nullable:!0})}){}class pNe extends P({url:g,links:cNe,omitted:N(lNe,{nullable:!0}),markers:N(Te(uNe),{nullable:!0})}){}class fNe extends P({moreTokens:pe}){}class dNe extends P({url:g,moreTokens:N(pe,{nullable:!0})}){}class ANe extends G(1){}class hNe extends P({version:ANe,snapshotId:g,url:g,markdownUrl:g}){}class j2 extends P({version:aNe,url:g,capturedAt:g,snapshotId:g,lang:g,pageType:g,playground:g,citationEvidenceIds:N(Te(lh).pipe(CU(3)),{nullable:!0}),title:N(g,{nullable:!0}),finalUrl:N(g,{nullable:!0}),contentType:N(g,{nullable:!0}),canonical:N(g,{nullable:!0}),description:N(g,{nullable:!0}),author:N(g,{nullable:!0}),createdAt:N(g,{nullable:!0}),updatedAt:N(g,{nullable:!0}),image:N(g,{nullable:!0}),paginationNext:N(g,{nullable:!0}),appendix:N(pNe,{nullable:!0}),stateJson:N(fNe,{nullable:!0}),markdown:N(dNe,{nullable:!0}),resources:N(hNe,{nullable:!0}),blocked:N(g,{nullable:!0}),loadingStatus:N(g,{nullable:!0})}){}class mNe extends G("inline","network"){}class gNe extends G("ld+json","next-data","nuxt","apollo-state","initial-state","application-json","script-tag","data-attribute","network-json","network-response","other"){}class ENe extends G(!0){}class yNe extends G("invalid","unsafe","too-long"){}class IB extends P({id:pe,kind:mNe,role:gNe,score:pe.pipe(kr(0)),url:N(g,{nullable:!0}),method:N(g,{nullable:!0}),moreTokens:N(pe,{nullable:!0}),keys:N(Te(g),{nullable:!0}),urlRedacted:N(ENe,{nullable:!0}),urlOmitted:N(yNe,{nullable:!0})}){}class xNe extends G("data-url"){}class gT extends P({id:g,kind:xNe,placeholder:g,archiveKey:g,mimeType:g,sha256:g,bytes:pe}){}class CNe extends G("pageTooLarge","modelInputTooLarge"){}class SNe extends G("domsnapshot_bytes","ast_bytes","document_frame_bytes","hfc_tokens"){}class V8 extends P({reason:CNe,skipped:Te(G("hfc")),limitKind:SNe,measuredBytes:N(cr.pipe(kr(0)),{nullable:!0}),thresholdBytes:N(cr.pipe(kr(0)),{nullable:!0}),measuredTokens:N(cr.pipe(kr(0)),{nullable:!0}),thresholdTokens:N(cr.pipe(kr(0)),{nullable:!0})}){}class K2 extends P({evidenceId:N(lh,{nullable:!0}),markdownBlockId:N(g,{nullable:!0}),nodeIds:N(Te(pe),{nullable:!0}),stateJsonSourceId:N(pe,{nullable:!0}),jsonPath:N(g,{nullable:!0})}){}class INe extends G("markdown","appendix","statejson"){}class bNe extends G("zeroentropy","mixedbread","local_lexical"){}class wNe extends G("timeout","error"){}class BNe extends P({source:INe,chunkCount:cr.pipe(kr(0)),batchCount:cr.pipe(kr(0)),ranker:bNe,fallback:xe,fallbackReason:N(wNe,{nullable:!0}),durationMs:pe.pipe(kr(0))}){}class Z2 extends P({durationMs:pe.pipe(kr(0)),sources:Te(BNe)}){}class bB extends P({query:g,snippets:Te(P({type:N(G("text"),{nullable:!0,default:()=>"text"}),source:G("markdown","appendix","statejson"),text:g,score:pe.pipe(kr(0),Vi(1)),location:N(K2,{nullable:!0})})),meta:N(Z2,{nullable:!0})}){}class QNe extends G("youtube"){}class DNe extends G("captions","transcription"){}class RNe extends G("manual","auto"){}class kNe extends G("http"){}class TNe extends G(!1){}class ONe extends G(!0){}class MNe extends G("FetchOriginError"){}class ET extends P({url:g,kind:kNe,contentAvailable:N(TNe,{nullable:!0}),finalUrl:N(g,{nullable:!0}),redirectLimitReached:N(ONe,{nullable:!0}),originStatusCode:pe,retryable:xe,_tag:MNe}){}class yT extends P({meta:j2,markdown:g,json:Te(IB),data:N(P({assets:N(Te(gT),{nullable:!0}),degraded:N(V8,{nullable:!0}),highlights:N(bB,{nullable:!0}),screenshot:N(P({url:g,fullPage:xe}),{nullable:!0}),document:N(P({url:g,contentType:g,sizeBytes:pe}),{nullable:!0}),usage:N(P({documentPages:lh,ocrPages:lh,audioSeconds:pe.pipe(kr(0)),videos:N(lh,{nullable:!0})}),{nullable:!0}),video:N(P({provider:QNe,videoId:g,title:g,channel:N(g,{nullable:!0}),channelUrl:N(g,{nullable:!0}),durationSeconds:N(pe,{nullable:!0}),publishedAt:N(g,{nullable:!0}),viewCount:N(pe,{nullable:!0}),language:N(g,{nullable:!0}),transcript:P({source:DNe,kind:N(RNe,{nullable:!0}),language:N(g,{nullable:!0})}),segments:N(Te(P({startSeconds:pe,text:g})),{nullable:!0}),chapters:N(Te(P({title:g,startSeconds:pe})),{nullable:!0}),storyboard:N(P({frameWidth:cr,frameHeight:cr,rows:cr,columns:cr,sheets:Te(P({url:g,durationSeconds:pe}))}),{nullable:!0})}),{nullable:!0})}),{nullable:!0}),originError:N(ET,{nullable:!0})}){}class FNe extends G("dns","tls","connectionRefused","connectionReset","connectionClosed","addressUnreachable","emptyResponse","connectionTimeout"){}class NNe extends G("FetchOriginError"){}class xT extends P({url:g,kind:FNe,upstreamError:N(g,{nullable:!0}),retryable:xe,_tag:NNe}){}class vNe extends G("FetchOriginError"){}class _Ne extends G("http"){}class UNe extends G(!1){}class LNe extends G(!0){}class CT extends P({_tag:vNe,url:g,kind:_Ne,contentAvailable:UNe,finalUrl:N(g,{nullable:!0}),redirectLimitReached:N(LNe,{nullable:!0}),originStatusCode:pe,retryable:xe}){}class PNe extends ze(yT,xT,CT){}class X2 extends ze(pE,hT){}class e1 extends ze(P({organizationId:g.pipe(sn(1)),blockedUntil:N(ze(mT,$m),{nullable:!0}),_tag:G("AccessBlocked")}),W2){}class t1 extends ze(bu,G2){}class r1 extends ze(uE,V2){}class n1 extends ze(z2,SB,J2){}class o1 extends ze(wu,$2){}class Kgt extends P({"x-idempotency-key":N(g.pipe(sn(1),yU(255)),{nullable:!0})}){}class HNe extends G("off","compact","detailed"){}class WNe extends G("auto","never","always"){}class Zgt extends ve("FetchBatchedRequest")({urls:Tb(g),include:N(P({html:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),markdown:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),screenshot:N(ze(xe,P({fullPage:N(xe,{nullable:!0})})),{nullable:!0}),links:N(ze(xe,P({sameDomainOnly:N(xe,{nullable:!0,default:()=>!0}),includePatterns:N(Te(g),{nullable:!0}),excludePatterns:N(Te(g),{nullable:!0})})),{nullable:!0}),meta:N(xe,{nullable:!0,default:()=>!0}),response:N(P({includeHeaders:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:N(xe,{nullable:!0,default:()=>!1}),appendix:N(xe,{nullable:!0}),appendixMarkers:N(HNe,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),browserConfig:N(P({scrollFullPage:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:N(P({maxPages:N(cr.pipe(kr(1)),{nullable:!0}),maxAudioSeconds:N(cr.pipe(kr(1),Vi(14400)),{nullable:!0,default:()=>3600}),ocr:N(WNe,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class qNe extends ve("BatchedRun")({id:g}){}class GNe extends ze(pE,hT){}class VNe extends G("AccessBlocked"){}class YNe extends P({organizationId:g.pipe(sn(1)),blockedUntil:N(ze(mT,$m),{nullable:!0}),_tag:VNe}){}class zNe extends G("payload_mismatch"){}class JNe extends G("BatchedIdempotencyConflict"){}class $Ne extends ve("BatchedIdempotencyConflict")({existingRunId:g,reason:zNe,_tag:JNe}){}class Xgt extends P({limit:N(g,{nullable:!0}),offset:N(g,{nullable:!0}),include:N(g,{nullable:!0})}){}class jNe extends G("QUEUED","RUNNING","CANCELLING","COMPLETED","FAILED","CANCELLED"){}class KNe extends G("QUEUED","RUNNING","CANCELLING","COMPLETED","FAILED","CANCELLED"){}class ZNe extends G("QUEUED","RUNNING","SUCCEEDED","FAILED","CANCELLED"){}class XNe extends g{}class WC extends P({url:g,requestedUrl:N(XNe,{nullable:!0}),originStatusCode:N(pe,{nullable:!0}),redirectStatusCode:N(pe,{nullable:!0}),contentType:N(g,{nullable:!0}),headers:N(P({}),{nullable:!0})}){}class eve extends P({href:g.pipe(sn(1)),rel:g.pipe(sn(1)),type:N(g.pipe(sn(1)),{nullable:!0}),sizes:N(g.pipe(sn(1)),{nullable:!0})}){}class tve extends P({url:g.pipe(sn(1)),width:N(pe,{nullable:!0}),height:N(pe,{nullable:!0}),alt:N(g,{nullable:!0})}){}class rve extends P({title:N(g,{nullable:!0}),description:N(g,{nullable:!0}),type:N(g.pipe(sn(1)),{nullable:!0}),url:N(g.pipe(sn(1)),{nullable:!0}),siteName:N(g,{nullable:!0}),locale:N(g,{nullable:!0}),images:N(Te(tve),{nullable:!0})}){}class nve extends P({card:N(g.pipe(sn(1)),{nullable:!0}),site:N(g,{nullable:!0}),creator:N(g,{nullable:!0}),title:N(g,{nullable:!0}),description:N(g,{nullable:!0}),image:N(g.pipe(sn(1)),{nullable:!0})}){}class ove extends P({title:N(g,{nullable:!0}),description:N(g,{nullable:!0}),canonicalUrl:N(g.pipe(sn(1)),{nullable:!0}),language:N(g.pipe(sn(1)),{nullable:!0}),charset:N(g.pipe(sn(1)),{nullable:!0}),favicon:N(g.pipe(sn(1)),{nullable:!0}),icons:N(Te(eve),{nullable:!0}),openGraph:N(rve,{nullable:!0}),twitter:N(nve,{nullable:!0})}){}class Y8 extends g.pipe(sn(1)){}class sve extends G("youtube"){}class ive extends G("captions","transcription"){}class ave extends G("manual","auto"){}class cve extends P({url:g,text:N(g,{nullable:!0})}){}class lve extends G("rust"){}class uve extends G("rust"){}class pve extends G("rust"){}class fve extends P({capture:N(lve,{nullable:!0}),markdown:N(uve,{nullable:!0}),tree:N(pve,{nullable:!0})}){}class dve extends P({status:ZNe,data:N(P({response:WC,meta:N(ove,{nullable:!0}),json:N(Te(P({})),{nullable:!0}),snapshotId:N(Y8,{nullable:!0}),html:N(g.pipe(sn(1)),{nullable:!0}),markdown:N(g.pipe(sn(1)),{nullable:!0}),screenshot:N(P({url:g,fullPage:xe}),{nullable:!0}),document:N(P({url:g,contentType:g,sizeBytes:pe}),{nullable:!0}),usage:N(P({documentPages:lh,ocrPages:lh,audioSeconds:pe.pipe(kr(0)),videos:N(lh,{nullable:!0})}),{nullable:!0}),video:N(P({provider:sve,videoId:g,title:g,channel:N(g,{nullable:!0}),channelUrl:N(g,{nullable:!0}),durationSeconds:N(pe,{nullable:!0}),publishedAt:N(g,{nullable:!0}),viewCount:N(pe,{nullable:!0}),language:N(g,{nullable:!0}),transcript:P({source:ive,kind:N(ave,{nullable:!0}),language:N(g,{nullable:!0})}),segments:N(Te(P({startSeconds:pe,text:g})),{nullable:!0}),chapters:N(Te(P({title:g,startSeconds:pe})),{nullable:!0}),storyboard:N(P({frameWidth:cr,frameHeight:cr,rows:cr,columns:cr,sheets:Te(P({url:g,durationSeconds:pe}))}),{nullable:!0})}),{nullable:!0}),links:N(Te(cve),{nullable:!0}),appendix:N(g.pipe(sn(1)),{nullable:!0}),renderEngines:N(fve,{nullable:!0}),assets:N(Te(gT),{nullable:!0}),degraded:N(V8,{nullable:!0})}),{nullable:!0}),error:N(ze(W2,G2,SB,xB,J2,ze(xT,CT),$2,CB,z2,fE,dE),{nullable:!0}),originError:N(ET,{nullable:!0})}){}class Ave extends P({total:pe,limit:pe,offset:pe,hasMore:xe}){}class hve extends ve("BatchedStatus")({id:g,status:jNe,batchedStatus:KNe,totalUrls:pe,results:Te(dve),pagination:Ave}){}class mve extends G("BatchedIncludeUnsupported"){}class gve extends P({unsupportedFields:Te(g),_tag:mve}){}class Eve extends ze(pE,gve){}class yve extends G("CANCELLING","CANCELLED"){}class xve extends ve("BatchedCancellation")({id:g,status:yve}){}class Cve extends G("COMPLETED","FAILED"){}class Sve extends G("BatchedCancellationConflict"){}class Ive extends ve("BatchedCancellationConflict")({id:g,status:Cve,_tag:Sve}){}class bve extends G("off","compact","detailed"){}class eEt extends ve("SnapshotHighlightsInput")({highlights:P({query:g,maxResults:N(cr.pipe(kr(1),Vi(50)),{nullable:!0,default:()=>5}),minScore:N(pe.pipe(kr(0),Vi(1)),{nullable:!0,default:()=>0.6})}),include:N(P({html:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),markdown:N(ze(xe,br({key:g,value:Yt})),{nullable:!0}),screenshot:N(ze(xe,P({fullPage:N(xe,{nullable:!0})})),{nullable:!0}),links:N(ze(xe,P({sameDomainOnly:N(xe,{nullable:!0,default:()=>!0}),includePatterns:N(Te(g),{nullable:!0}),excludePatterns:N(Te(g),{nullable:!0})})),{nullable:!0}),meta:N(xe,{nullable:!0,default:()=>!0}),response:N(P({includeHeaders:N(xe,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:N(xe,{nullable:!0,default:()=>!1}),appendix:N(xe,{nullable:!0}),appendixMarkers:N(bve,{nullable:!0,default:()=>"compact"})}),{nullable:!0})}){}class wve extends ve("FetchSnapshotHighlightsResult")({snapshotId:g.pipe(sn(1)),response:WC,highlights:bB,durationMs:pe.pipe(kr(0)),playground:g}){}class s1 extends ze(pE,hT){}class Bve extends G("AccessBlocked"){}class i1 extends P({organizationId:g.pipe(sn(1)),blockedUntil:N(ze(mT,$m),{nullable:!0}),_tag:Bve}){}class Qve extends G("FetchSnapshotHighlightsNotFound"){}class a1 extends ve("FetchSnapshotHighlightsNotFound")({snapshotId:Y8,_tag:Qve}){}class c1 extends ze(uE,V2){}class Dve extends G("json","markdown"){}class tEt extends P({format:N(Dve,{nullable:!0})}){}class Rve extends G(1){}class wB extends ve("SnapshotCatalog")({version:Rve,snapshotId:g,collections:P({evidence:g,network:g,assets:g,artifacts:g}),artifacts:Te(P({id:g,kind:g,url:g,preview:N(g,{nullable:!0})})),links:P({markdown:g,json:g})}){}class kve extends G("SnapshotNotFound"){}class Tve extends ve("SnapshotNotFound")({snapshotId:g,_tag:kve}){}var l1=(e,t={})=>{let r=(s,i)=>L(Ll(i.text,()=>"Unexpected status code"),(a)=>ce(new rc({request:s,response:i,reason:"StatusCode",description:a}))),n=(s)=>t.transformClient?t.transformClient(s):v(s),o=(s,i)=>L(ki(i)(s),ce);return{fetchFetch:(s)=>iu("POST")("/v1/fetch").pipe(_A({include:s.params.include,appendixMarkers:s.params.appendixMarkers}),(i)=>or(jc(i,s.payload)),L((i)=>L(n(e),(a)=>L(a.execute(i),Kc({"400":(c)=>o(c,H2),"401":(c)=>o(c,Iu),"403":(c)=>o(c,q2),"404":(c)=>o(c,dT),"410":(c)=>o(c,AT),"413":(c)=>o(c,kFe),"415":(c)=>o(c,xB),"422":(c)=>o(c,CB),"429":(c)=>o(c,Y2),"500":(c)=>o(c,il),"502":(c)=>o(c,zFe),"503":(c)=>o(c,XFe),"504":(c)=>o(c,fE),"529":(c)=>o(c,dE),orElse:(c)=>r(i,c)}))))),fetchFetchJson:(s)=>iu("POST")("/v1/fetch/json").pipe(_A({include:s.params.include,appendixMarkers:s.params.appendixMarkers}),(i)=>or(jc(i,s.payload)),L((i)=>L(n(e),(a)=>L(a.execute(i),Kc({"200":(c)=>ki(PNe)(c),"400":(c)=>o(c,X2),"401":(c)=>o(c,Iu),"403":(c)=>o(c,e1),"404":(c)=>o(c,dT),"410":(c)=>o(c,AT),"413":(c)=>o(c,t1),"415":(c)=>o(c,xB),"422":(c)=>o(c,CB),"429":(c)=>o(c,r1),"500":(c)=>o(c,il),"502":(c)=>o(c,n1),"503":(c)=>o(c,o1),"504":(c)=>o(c,fE),"529":(c)=>o(c,dE),orElse:(c)=>r(i,c)}))))),fetchBatched:(s)=>iu("POST")("/v1/fetch/batched").pipe(Yxe({"x-idempotency-key":s.params["x-idempotency-key"]??void 0}),(i)=>or(jc(i,s.payload)),L((i)=>L(n(e),(a)=>L(a.execute(i),Kc({"200":(c)=>ki(qNe)(c),"400":(c)=>o(c,GNe),"401":(c)=>o(c,Iu),"403":(c)=>o(c,YNe),"409":(c)=>o(c,$Ne),"413":(c)=>o(c,bu),"429":(c)=>o(c,uE),"500":(c)=>o(c,il),"503":(c)=>o(c,wu),orElse:(c)=>r(i,c)}))))),fetchGetBatched:(s,i)=>iu("GET")(`/v1/fetch/batched/${s}`).pipe(_A({limit:i.limit,offset:i.offset,include:i.include}),v,L((a)=>L(n(e),(c)=>L(c.execute(a),Kc({"200":(l)=>ki(hve)(l),"400":(l)=>o(l,Eve),"401":(l)=>o(l,Iu),"413":(l)=>o(l,bu),"429":(l)=>o(l,uE),"500":(l)=>o(l,il),"503":(l)=>o(l,wu),orElse:(l)=>r(a,l)}))))),fetchCancelBatched:(s)=>iu("POST")(`/v1/fetch/batched/${s}/cancel`).pipe(v,L((i)=>L(n(e),(a)=>L(a.execute(i),Kc({"200":(c)=>ki(xve)(c),"400":(c)=>o(c,pE),"401":(c)=>o(c,Iu),"409":(c)=>o(c,Ive),"413":(c)=>o(c,bu),"429":(c)=>o(c,uE),"500":(c)=>o(c,il),"503":(c)=>o(c,wu),orElse:(c)=>r(i,c)}))))),snapshotsHighlights:(s,i)=>iu("POST")(`/v1/snapshots/${s}/highlights`).pipe((a)=>or(jc(a,i)),L((a)=>L(n(e),(c)=>L(c.execute(a),Kc({"200":(l)=>ki(wve)(l),"400":(l)=>o(l,s1),"401":(l)=>o(l,Iu),"403":(l)=>o(l,i1),"404":(l)=>o(l,a1),"413":(l)=>o(l,bu),"429":(l)=>o(l,c1),"500":(l)=>o(l,il),"503":(l)=>o(l,wu),orElse:(l)=>r(a,l)}))))),publicSnapshotsGetCatalog:(s,i)=>iu("GET")(`/v1/public/snapshots/${s}`).pipe(_A({format:i.format}),v,L((a)=>L(n(e),(c)=>L(c.execute(a),Kc({"200":(l)=>ki(wB)(l),"400":(l)=>o(l,pE),"404":(l)=>o(l,Tve),"413":(l)=>o(l,bu),"429":(l)=>o(l,uE),"500":(l)=>o(l,il),"503":(l)=>o(l,wu),orElse:(l)=>r(a,l)})))))}};var rEt=Symbol("DecodedErrorStatus");function BB(e,t){return L(Ll(t.text,()=>"Unexpected status code"),(r)=>ce(new rc({request:e,response:t,reason:"StatusCode",description:r})))}function Or(e,t){let r=ki(t)(e),n=e.status===404||e.status===410?r.pipe(Gs("ParseError",()=>BB(e.request,e))):r;return L(n,(o)=>{if(typeof o==="object"&&o!==null)Object.defineProperty(o,rEt,{value:e.status});return ce(o)})}function z8(e,t){return ki(t)(e).pipe(Gs("ParseError",(r)=>new eT({message:"Failed to decode the API response",cause:r})))}var nEt=P({...bB.fields.snippets.value.fields,json:N(Yt,{nullable:!0})}),Ove=P({...bB.fields,snippets:Te(nEt)}),oEt=P({...IB.fields,body:N(Yt,{nullable:!0})});class Mve extends ve("FetchObjectModeResultWithJson")({...yT.fields,json:Te(oEt),data:N(P({...yT.fields.data.from.fields,highlights:N(Ove,{nullable:!0})}),{nullable:!0}),originError:N(ET,{nullable:!0})}){}var sEt=ze(Mve,xT,CT);function AE(e){return"_tag"in e&&e._tag==="FetchOriginError"}class Fve extends ve("FetchSnapshotHighlightsResultWithJson")({snapshotId:g.pipe(sn(1)),response:WC,highlights:Ove,durationMs:pe.pipe(kr(0)),playground:g}){}var J8=(e,t)=>iu("POST")("/v1/fetch/json").pipe(_A(t.params.include!==void 0?{include:t.params.include}:{}),(r)=>or(jc(r,t.payload)),L((r)=>L(e.execute(r),Kc({"200":(n)=>z8(n,sEt),"400":(n)=>Or(n,X2),"401":(n)=>Or(n,Iu),"403":(n)=>Or(n,e1),"404":(n)=>Or(n,dT),"410":(n)=>Or(n,AT),"413":(n)=>Or(n,t1),"415":(n)=>Or(n,xB),"422":(n)=>Or(n,CB),"429":(n)=>Or(n,r1),"500":(n)=>Or(n,il),"502":(n)=>Or(n,n1),"503":(n)=>Or(n,o1),"504":(n)=>Or(n,fE),"529":(n)=>Or(n,dE),orElse:(n)=>BB(r,n)})))),Nve=(e,t,r)=>iu("POST")(`/v1/snapshots/${encodeURIComponent(t)}/highlights`).pipe((n)=>or(jc(n,r)),L((n)=>L(e.execute(n),Kc({"200":(o)=>z8(o,Fve),"400":(o)=>Or(o,s1),"401":(o)=>Or(o,Iu),"403":(o)=>Or(o,i1),"404":(o)=>Or(o,a1),"413":(o)=>Or(o,bu),"429":(o)=>Or(o,c1),"500":(o)=>Or(o,il),"503":(o)=>Or(o,wu),orElse:(o)=>BB(n,o)}))));var $8=class e extends Error{status;text;json;headers;constructor(t,r,n,o,s,i){super(i||`HTTP Error ${t} at ${s}: ${r??JSON.stringify(n)}`);this.url=s,this.name="FetchError",this.status=t,this.text=r,this.json=n,this.headers=o}static async fromResponse(t,r){let n=t.status,o=Object.fromEntries([...t.headers.entries()]),s=void 0,i=void 0,a=t.headers.get("content-type");if(!t.bodyUsed&&t.body!==null)if(a&&a.includes("application/json"))try{i=await t.json()}catch{s=await t.text()}else s=await t.text();return new e(n,s,i,o,r)}},Pve=class extends Error{constructor(){super("Fetch with backoff aborted");this.name="FetchBackoffAbortError"}},ta=class e extends Error{status;code;details;constructor(t,r,n,o){super(t);this.name="DurableStreamError",this.code=r,this.status=n,this.details=o}static async fromResponse(t,r){let n=t.status,o,s=t.headers.get("content-type");if(!t.bodyUsed&&t.body!==null)if(s&&s.includes("application/json"))try{o=await t.json()}catch{o=await t.text()}else o=await t.text();let i=vve(n),a=`Durable stream error at ${r}: ${t.statusText||n}`;return new e(a,i,n,o)}static fromFetchError(t){let r=vve(t.status);return new e(t.message,r,t.status,t.json??t.text)}};function vve(e){switch(e){case 400:return"BAD_REQUEST";case 401:return"UNAUTHORIZED";case 403:return"FORBIDDEN";case 404:return"NOT_FOUND";case 409:return"CONFLICT_SEQ";case 429:return"RATE_LIMITED";case 503:return"BUSY";default:return"UNKNOWN"}}var iEt=class extends ta{code="STREAM_CLOSED";status=409;streamClosed=!0;finalOffset;constructor(e,t){super("Cannot append to closed stream","STREAM_CLOSED",409,e);this.name="StreamClosedError",this.finalOffset=t}};var aEt=[429,503],u1={initialDelay:100,maxDelay:60000,multiplier:1.3,maxRetries:1/0};function cEt(e){if(!e)return 0;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1000;let r=Date.parse(e);if(!isNaN(r)){let n=r-Date.now();return Math.max(0,Math.min(n,3600000))}return 0}function lEt(e,t=u1){let{initialDelay:r,maxDelay:n,multiplier:o,debug:s=!1,onFailedAttempt:i,maxRetries:a=1/0}=t;return async(...c)=>{let l=c[0],u=c[1],p=r,f=0;while(!0)try{let d=await e(...c);if(d.ok)return d;throw await $8.fromResponse(d,l.toString())}catch(d){if(i?.(),u?.signal?.aborted)throw new Pve;else if(d instanceof $8&&!aEt.includes(d.status)&&d.status>=400&&d.status<500)throw d;else{if(f++,f>a){if(s)console.log(`Max retries reached (${f}/${a}), giving up`);throw d}let A=d instanceof $8?cEt(d.headers["retry-after"]):0,m=Math.random()*p,E=Math.min(m,n),x=Math.max(A,E);if(s){let B=A>0?"server+client":"client";console.log(`Retry attempt #${f} after ${x}ms (${B}, serverMin=${A}ms, clientBackoff=${E}ms)`)}await new Promise((B)=>setTimeout(B,x)),p=Math.min(p*o,n)}}}}function uEt(e){return typeof Symbol<"u"&&typeof Symbol.asyncIterator==="symbol"&&typeof e[Symbol.asyncIterator]==="function"}function pEt(e){if(typeof Symbol>"u"||typeof Symbol.asyncIterator!=="symbol")return;if(typeof e[Symbol.asyncIterator]==="function")return;let t=function(){let r=this.getReader(),n=!1,o=0;return{async next(){if(n)return{done:!0,value:void 0};o++;try{let{value:i,done:a}=await r.read();if(a)return n=!0,r.releaseLock(),{done:!0,value:void 0};return{done:!1,value:i}}catch(i){n=!0;try{r.releaseLock()}catch{}throw i}finally{o--}},async return(i){if(o>0)throw TypeError("Cannot close a readable stream reader when it has pending read requests");n=!0;let a=r.cancel(i);return r.releaseLock(),await a,{done:!0,value:void 0}},async throw(i){if(o>0)throw TypeError("Cannot close a readable stream reader when it has pending read requests");n=!0;let a=r.cancel(i);throw r.releaseLock(),await a,i},[Symbol.asyncIterator](){return this}}};try{Object.defineProperty(e,Symbol.asyncIterator,{configurable:!0,writable:!0,value:t})}catch{return}try{Object.defineProperty(e,"values",{configurable:!0,writable:!0,value:t})}catch{}}function j8(e){if(!uEt(e))pEt(e);return e}async function*K8(e,t){let r=e.getReader(),n=new TextDecoder,o="",s={data:[]};try{while(!0){if(t?.aborted)break;let{done:a,value:c}=await r.read();if(a)break;o+=n.decode(c,{stream:!0}),o=o.replace(/\r\n/g,`
296
296
  `).replace(/\r/g,`
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "expandai",
3
3
  "type": "module",
4
- "version": "0.1.1",
4
+ "version": "0.1.2",
5
5
  "private": false,
6
6
  "description": "Unified CLI and MCP server for ExpandAI",
7
7
  "author": "ExpandAI",
@@ -83,5 +83,5 @@
83
83
  "smol-toml": "^1.6.1",
84
84
  "vitest": "4.1.4"
85
85
  },
86
- "expandSourceSha": "cf4c482dcde7d1d91060b8b1811cda6f455723ce"
86
+ "expandSourceSha": "fb8ccf337133978e69c15135096173e1df05e259"
87
87
  }