expandai 0.1.5 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/dts/Mcp/Server.d.ts +1 -1
- package/build/esm/index.js +1 -1
- package/build/esm/main.js +1 -1
- package/package.json +3 -3
|
@@ -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.
|
|
5
|
+
readonly version: "0.1.6";
|
|
6
6
|
};
|
|
7
7
|
export declare const makeServerLayer: (options?: {
|
|
8
8
|
readonly includeDocs?: boolean;
|
package/build/esm/index.js
CHANGED
|
@@ -180,7 +180,7 @@ schema (${n._tag}): ${n}`;return o},i7=(e)=>ei("Invalid Argument",e),mFe=(e,t,r)
|
|
|
180
180
|
`))e=e.replace(sLe,"%0A");if(e.includes("\r"))e=e.replace(iLe,"%0D");if(e.includes("\t"))e=e.replace(aLe,"%09");return e}var gW=EW.of({[RT]:RT,resolve:pse,normalize(e){if(e.length===0)return".";let t=e.charCodeAt(0)===47,r=e.charCodeAt(e.length-1)===47;if(e=use(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 gW.normalize(e)},relative(e,t){if(e===t)return"";if(e=gW.resolve(e),t=gW.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 f=e.charCodeAt(r+u),A=t.charCodeAt(s+u);if(f!==A)break;else if(f===47)l=u}let p="";for(u=r+l+1;u<=n;++u)if(u===n||e.charCodeAt(u)===47)if(p.length===0)p+="..";else p+="/..";if(p.length>0)return p+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 XUe("/",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:eLe,toFileUrl:rLe,toNamespacedPath:X});var xW=Symbol.for("@effect/platform/HttpServer"),fse=Ke("@effect/platform/HttpServer"),uLe={[xW]:xW};var Ase=(e)=>Object.assign(Object.create(uLe),e);var yW=fse,dse=Ase;var SW=HI,kf=fx,fLe=ose;var ALe=sse;var IW=ase;var dLe=ise;var dx=Symbol.for("@effect/platform/HttpServerRespondable"),hse=(e)=>ee(e,dx),hLe=kf({status:400}),mLe=kf({status:404});var mse=(e,t)=>{if(SW(e))return Z(e);else if(hse(e))return rn(e[dx](),()=>Z(t));else if(NE(e))return Z(hLe);else if(D9(e))return Z(mLe);return Z(t)},gse=(e,t)=>{if(SW(e))return Z(e);else if(hse(e))return rn(e[dx](),()=>Z(t));return Z(t)};var yse=Symbol.for("@effect/platform/HttpServerError");var DT=Ae("@effect/platform/HttpServerError/clientAbortFiberId",()=>fw(-499,0)),Cse=(e)=>{let t=Z(kT),r=Ud,n=!1,o=!1;R9(e,void 0,(a,c)=>{let l=pk(r)?Ud:r;switch(c._tag){case"Fail":{t=mse(c.error,kT),r=xse(l,c);break}case"Die":{let u=HI(c.defect);t=gse(c.defect,kT),r=u?l:xse(l,c),o=o||u;break}case"Interrupt":{if(n=n||c.fiberId===DT,Vp(r)&&!o)r=c;break}}return T()});let s=!o&&pk(r)?Z(n?gLe:ELe):t,i=!o&&pk(r)&&n?rE(DT):r;return z(s,(a)=>{if(Vp(i))return[a,Ud];return[a,Ld(i,$s(a))]})},xse=(e,t)=>{if(Vp(e))return t;else if(Vp(t))return e;return Ld(e,t)},Sse=(e)=>{let t,r=w9(e,(n)=>{if(HI(n))return t=n,M(Ud);return T()});return[t??kT,r]},kT=fx({status:500}),gLe=fx({status:499}),ELe=fx({status:503}),Ise=(e)=>{if(e._tag==="Success")return e.value;return Sse(e.cause)[0]};var bW=yse;class WI extends qc(bW,"RequestError"){[dx](){return kf({status:400})}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 TT extends qc(bW,"ResponseError"){[dx](){return kf({status:500})}get methodAndUrl(){return`${this.request.method} ${this.request.url}`}get message(){let e=`${this.response.status} ${this.methodAndUrl}`;return this.description?`${this.description} (${e})`:`${this.reason} error (${e})`}}class vT extends qc(bW,"ServeError"){}var OT=DT,qI=Cse;var bse=Ise;var NT=Symbol.for("effect/Mailbox"),BW=Symbol.for("effect/Mailbox/ReadonlyMailbox");var wh=Lt(),Bse=yt(wh),FT=yt(!1),MT=yt(!0),Qse=[wh,!0];class wse extends Is{scheduler;capacity;strategy;[NT]=NT;[BW]=BW;state={_tag:"Open",takers:new Set,offers:new Set,awaiters:new Set};messages=[];messagesChunk=Lt();constructor(e,t,r){super();this.scheduler=e,this.capacity=t,this.strategy=r}offer(e){return Me(()=>{if(this.state._tag!=="Open")return FT;else if(this.messages.length+this.messagesChunk.length>=this.capacity)switch(this.strategy){case"dropping":return FT;case"suspend":if(this.capacity<=0&&this.state.takers.size>0)return this.messages.push(e),this.releaseTaker(),MT;return this.offerRemainingSingle(e);case"sliding":return this.unsafeTake(),this.messages.push(e),MT}return this.messages.push(e),this.scheduleReleaseTaker(),MT})}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 Me(()=>{if(this.state._tag!=="Open")return te(Ln(e));let t=this.unsafeOfferAllArray(e);if(t.length===0)return Bse;else if(this.strategy==="dropping")return te(Qr(t));return this.offerRemainingArray(t)})}unsafeOfferAll(e){return Qr(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=$t(this.messagesChunk,Qr(this.messages));if(this.strategy==="sliding")this.messagesChunk=this.messagesChunk.pipe($t(Ln(e)),gN(this.capacity));else if(VA(e))this.messagesChunk=$t(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(Ml(e))}failCause(e){return this.done(dt(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=j(()=>{if(this.state._tag==="Done")return!0;this.messages=[],this.messagesChunk=wh;let e=this.state.offers;if(this.finalize(this.state._tag==="Open"?Rr:this.state.exit),e.size>0){for(let t of e)if(t._tag==="Single")t.resume(FT);else t.resume(yt(Qr(t.remaining.slice(t.offset))));e.clear()}return!0});done(e){return j(()=>this.unsafeDone(e))}end=this.done(Rr);clear=Me(()=>{if(this.state._tag==="Done")return kg(this.state.exit,wh);let e=this.unsafeTakeAll();return this.releaseCapacity(),te(e)});takeAll=Me(()=>{if(this.state._tag==="Done")return kg(this.state.exit,Qse);let e=this.unsafeTakeAll();if(e.length===0)return xt(this.awaitTake,this.takeAll);return te([e,this.releaseCapacity()])});takeN(e){return Me(()=>{if(this.state._tag==="Done")return kg(this.state.exit,Qse);else if(e<=0)return te([wh,!1]);e=Math.min(e,this.capacity);let t;if(e<=this.messagesChunk.length)t=Xm(this.messagesChunk,e),this.messagesChunk=Ca(this.messagesChunk,e);else if(e<=this.messages.length+this.messagesChunk.length)this.messagesChunk=$t(this.messagesChunk,Qr(this.messages)),this.messages=[],t=Xm(this.messagesChunk,e),this.messagesChunk=Ca(this.messagesChunk,e);else return xt(this.awaitTake,this.takeN(e));return te([t,this.releaseCapacity()])})}unsafeTake(){if(this.state._tag==="Done")return rR(this.state.exit,Ml(new k9));let e;if(this.messagesChunk.length>0)e=oC(this.messagesChunk),this.messagesChunk=Ca(this.messagesChunk,1);else if(this.messages.length>0)e=this.messages[0],this.messagesChunk=Ca(Qr(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?yt(this.messages.pop()):void 0;else return;return this.releaseCapacity(),yt(e)}take=Me(()=>this.unsafeTake()??xt(this.awaitTake,this.take));await=Ac((e)=>{if(this.state._tag==="Done")return e(this.state.exit);return this.state.awaiters.add(e),j(()=>{if(this.state._tag!=="Done")this.state.awaiters.delete(e)})});unsafeSize(){let e=this.messages.length+this.messagesChunk.length;return this.state._tag==="Done"?T():M(e)}size=j(()=>this.unsafeSize());commit(){return this.takeAll}pipe(){return W(this,arguments)}toJSON(){return{_id:"effect/Mailbox",state:this.state._tag,size:this.unsafeSize().toJSON()}}toString(){return Ve(this)}[ke](){return Ve(this)}offerRemainingSingle(e){return Ac((t)=>{if(this.state._tag!=="Open")return t(FT);let r={_tag:"Single",message:e,resume:t};return this.state.offers.add(r),j(()=>{if(this.state._tag==="Open")this.state.offers.delete(r)})})}offerRemainingArray(e){return Ac((t)=>{if(this.state._tag!=="Open")return t(yt(Qr(e)));let r={_tag:"Array",remaining:e,offset:0,resume:t};return this.state.offers.add(r),j(()=>{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(MT),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(Bse),this.state.offers.delete(t)}return!1}awaitTake=Ac((e)=>{if(this.state._tag==="Done")return e(this.state.exit);return this.state.takers.add(e),j(()=>{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(Rr),this.messages.length+this.messagesChunk.length===0)break};unsafeTakeAll(){if(this.messagesChunk.length>0){let e=this.messages.length>0?$t(this.messagesChunk,Qr(this.messages)):this.messagesChunk;return this.messagesChunk=wh,this.messages=[],e}else if(this.messages.length>0){let e=Qr(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,at(this.messages.pop());return wh}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 Rse=(e)=>rt((t)=>te(new wse(t.currentScheduler,typeof e==="number"?e:e?.capacity??Number.POSITIVE_INFINITY,typeof e==="number"?"suspend":e?.strategy??"suspend")));var QW=(e)=>{let t=Ze(e.takeAll,([r,n])=>n?r.length===0?jn:ht(r):cu(ht(r),t));return t},kse=(e)=>JD(QW(e));var CLe=NT;var Dse=(e)=>ee(e,CLe);var Df=Rse;var Tse=QW,vse=kse;var Ose=/; *([!#$%&'*+.^\w`|~-]+)=("(?:[\v\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u{10ffff}]|\\[\v\u0020-\u{10ffff}])*"|[!#$%&'*+.^\w`|~-]+) */gu,Fse=/\\([\v\u0020-\u{10ffff}])/gu,SLe=/^[!#$%&'*+.^\w|~-]+\/[!#$%&'*+.^\w|~-]+$/u,ILe=/^[!#$%&'*+.^\w|~-]+$/u,UT={value:"",parameters:Object.create(null)};function LT(e,t=!1){if(typeof e!=="string")return UT;let r=e.indexOf(";"),n=r!==-1?e.slice(0,r).trim():e.trim();if((t?ILe:SLe).test(n)===!1)return UT;let s={value:n.toLowerCase(),parameters:Object.create(null)};if(r===-1)return s;let i,a,c;Ose.lastIndex=r;while(a=Ose.exec(e)){if(a.index!==r)return UT;if(r+=a[0].length,i=a[1].toLowerCase(),c=a[2],c[0]==='"')c=c.slice(1,c.length-1),!t&&Fse.test(c)&&(c=c.replace(Fse,"$1"));s.parameters[i]=c}if(r!==e.length)return UT;return s}var Ki;(function(e){e[e.key=0]="key",e[e.whitespace=1]="whitespace",e[e.value=2]="value"})(Ki||(Ki={}));var YI={_tag:"Continue"},BLe=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1],QLe=[0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1];function Mse(){let e=new TextDecoder,t={state:Ki.key,headers:Object.create(null),key:"",value:void 0,crlf:0,previousChunk:void 0,pairs:0,size:0};function r(s){return t.state=Ki.key,t.headers=Object.create(null),t.key="",t.value=void 0,t.crlf=0,t.previousChunk=void 0,t.pairs=0,t.size=0,s}function n(s,i){let a=new Uint8Array(s.length+i.length);return a.set(s),a.set(i,s.length),a}function o(s){return r({_tag:"Failure",reason:s,headers:t.headers})}return function(i,a){let c=0,l;if(t.previousChunk!==void 0){c=t.previousChunk.length,l=c;let p=new Uint8Array(i.length+c);p.set(t.previousChunk),p.set(i,c),t.previousChunk=void 0,i=p}let u=i.length;e:while(a<u){if(t.state===Ki.key){let p=a;for(;p<u;p++){if(t.size++>16384)return o("HeaderTooLarge");if(i[p]===58){if(t.key+=e.decode(i.subarray(a,p)).toLowerCase(),t.key.length===0)return o("InvalidHeaderName");if(i[p+1]===32&&i[p+2]!==32&&i[p+2]!==9)a=p+2,t.state=Ki.value,t.size++;else if(i[p+1]!==32&&i[p+1]!==9)a=p+1,t.state=Ki.value;else a=p+1,t.state=Ki.whitespace;break}else if(BLe[i[p]]!==1)return o("InvalidHeaderName")}if(p===u)return t.key+=e.decode(i.subarray(a,u)).toLowerCase(),YI}if(t.state===Ki.whitespace){for(;a<u;a++){if(t.size++>16384)return o("HeaderTooLarge");if(i[a]!==32&&i[a]!==9){t.state=Ki.value;break}}if(a===u)return YI}if(t.state===Ki.value){let p=a;if(l!==void 0)p=l,l=void 0;for(;p<u;p++){if(t.size++>16384)return o("HeaderTooLarge");if(i[p]===13||t.crlf>0){let f=i[p];if(f===13&&t.crlf===0)t.crlf=1,p++,t.size++,f=i[p];if(f===10&&t.crlf===1)t.crlf=2,p++,t.size++,f=i[p];if(f===13&&t.crlf===2)t.crlf=3,p++,t.size++,f=i[p];if(f===10&&t.crlf===3)t.crlf=4,p++,t.size++;if(t.crlf<4&&p>=u)return t.previousChunk=i.subarray(a),YI;else if(t.crlf>=2){t.value=t.value===void 0?i.subarray(a,p-t.crlf):n(t.value,i.subarray(a,p-t.crlf));let A=e.decode(t.value);if(t.headers[t.key]===void 0)t.headers[t.key]=A;else if(typeof t.headers[t.key]==="string")t.headers[t.key]=[t.headers[t.key],A];else t.headers[t.key].push(A);if(a=p,t.size--,t.crlf!==4&&t.pairs===100)return o("TooManyHeaders");else if(t.crlf===3)return o("InvalidHeaderValue");else if(t.crlf===4)return r({_tag:"Headers",headers:t.headers,endPosition:a-c});t.pairs++,t.key="",t.value=void 0,t.crlf=0,t.state=Ki.key;continue e}}else if(QLe[i[p]]!==1)return o("InvalidHeaderValue")}if(p===u)return t.value=t.value===void 0?i.subarray(a,u):n(t.value,i.subarray(a,u)),YI}}if(a>u)t.size+=u-a;return YI}}function RLe(e){let t=new TextEncoder().encode(e),r=t.length,n={};for(let o=0;o<r;o++){let s=t[o];if(n[s]===void 0)n[s]=[];n[s].push(o)}return{needle:t,needleLength:r,indexes:n,firstByte:t[0],previousChunk:void 0,previousChunkLength:0,matchIndex:0}}function Nse(e,t,r){let n=RLe(e);if(r!==void 0)n.previousChunk=r,n.previousChunkLength=r.length;function o(){if("Buffer"in globalThis&&!(("Bun"in globalThis)||("Deno"in globalThis)))return function(l,u,p){return Buffer.prototype.indexOf.call(l,u,p)};let c=new Uint8Array(256).fill(n.needle.length);for(let l=0,u=n.needle.length-1;l<u;++l)c[n.needle[l]]=u-l;return function(l,u,p){let f=l.length,A=p+n.needleLength-1;while(A<f){for(let d=n.needleLength-1,g=A;d>=0&&l[g]===u[d];d--,g--)if(d===0)return g;A+=c[l[A]]}return-1}}let s=o();function i(c){let l=c.length;if(n.previousChunk!==void 0){let p=new Uint8Array(n.previousChunkLength+l);p.set(n.previousChunk),p.set(c,n.previousChunkLength),c=p,l=n.previousChunkLength+l,n.previousChunk=void 0}if(l<n.needleLength){n.previousChunk=c,n.previousChunkLength=l;return}let u=0;while(u<l){let p=s(c,n.needle,u);if(p>-1){if(p>u)t(n.matchIndex,c.subarray(u,p));n.matchIndex+=1,u=p+n.needleLength;continue}else if(c[l-1]in n.indexes){let f=n.indexes[c[l-1]],A=-1;for(let d=0,g=f.length;d<g;d++){let x=f[d];if(c[l-1-x]===n.firstByte&&d>A)A=x}if(A===-1)if(u===0)t(n.matchIndex,c);else t(n.matchIndex,c.subarray(u));else{if(l-1-A>u)t(n.matchIndex,c.subarray(u,l-1-A));n.previousChunk=c.subarray(l-1-A),n.previousChunkLength=A+1}}else if(u===0)t(n.matchIndex,c);else t(n.matchIndex,c.subarray(u));break}}function a(){if(n.previousChunk!==void 0&&n.previousChunk!==r)t(n.matchIndex,n.previousChunk);n.previousChunk=r,n.previousChunkLength=r?.length??0,n.matchIndex=0}return{write:i,end:a}}var mu;(function(e){e[e.headers=0]="headers",e[e.body=1]="body"})(mu||(mu={}));var DLe={_tag:"InvalidDisposition"},TLe={_tag:"EndNotReached"},vLe={_tag:"ReachedLimit",limit:"MaxParts"},OLe={_tag:"ReachedLimit",limit:"MaxTotalSize"},FLe={_tag:"ReachedLimit",limit:"MaxPartSize"},_se={_tag:"ReachedLimit",limit:"MaxFieldSize"},MLe=new TextEncoder().encode(`\r
|
|
181
181
|
`);function wW(e){return e.filename!==void 0||e.contentType==="application/octet-stream"}function NLe(e){return LT(e["content-type"]).parameters.boundary}function PT(e){}function Lse({headers:e,onFile:t,onField:r,onError:n,onDone:o,isFile:s=wW,maxParts:i=1/0,maxTotalSize:a=1/0,maxPartSize:c=1/0,maxFieldSize:l=1048576}){let u=NLe(e);if(u===void 0)return n({_tag:"InvalidBoundary"}),{write:PT,end(){}};let p={state:mu.headers,index:0,parts:0,onChunk:PT,info:void 0,headerSkip:0,partSize:0,totalSize:0,isFile:!1,fieldChunks:[],fieldSize:0};function f(){p.state=mu.body,p.isFile=!0,p.onChunk=PT}let A=Mse(),d=Nse(`\r
|
|
182
182
|
--${u}`,function(g,x){if(g===0){f();return}else if(g!==p.index){if(p.index>0)if(p.isFile)p.onChunk(null),p.partSize=0;else{if(p.fieldChunks.length===1)r(p.info,p.fieldChunks[0]);else{let y=new Uint8Array(p.fieldSize),S=0;for(let I=0;I<p.fieldChunks.length;I++){let B=p.fieldChunks[I];y.set(B,S),S+=B.length}r(p.info,y)}p.fieldSize=0,p.fieldChunks=[]}if(p.state=mu.headers,p.index=g,p.headerSkip=2,x[0]===45&&x[1]===45)return o();if(p.parts++,p.parts>i)n(vLe)}if((p.partSize+=x.length)>c)n(FLe);if(p.state===mu.headers){let y=A(x,p.headerSkip);if(p.headerSkip=0,y._tag==="Continue")return;else if(y._tag==="Failure")return f(),n({_tag:"BadHeaders",error:y});let S=LT(y.headers["content-type"]),I=LT(y.headers["content-disposition"],!0);if(I.value==="form-data"&&!("name"in I.parameters))return f(),n(DLe);let B;if("filename*"in I.parameters){let R=I.parameters["filename*"].split("''");if(R.length===2)B=decodeURIComponent(R[1])}if(p.info={name:I.parameters.name??"",filename:B??I.parameters.filename,contentType:S.value===""?I.parameters.filename!==void 0?"application/octet-stream":"text/plain":S.value,contentTypeParameters:S.parameters,contentDisposition:I.value,contentDispositionParameters:I.parameters,headers:y.headers},p.state=mu.body,p.isFile=s(p.info),p.isFile)p.onChunk=t(p.info);if(y.endPosition<x.length)if(p.isFile)p.onChunk(x.subarray(y.endPosition));else{let R=x.subarray(y.endPosition);if((p.fieldSize+=R.length)>l)n(_se);p.fieldChunks.push(R)}}else if(p.isFile)p.onChunk(x);else{if((p.fieldSize+=x.length)>l)n(_se);p.fieldChunks.push(x)}},MLe);return{write(g){if((p.totalSize+=g.length)>a)return n(OLe);return d.write(g)},end(){if(d.end(),p.state===mu.body)n(TLe);p.state=mu.headers,p.index=0,p.parts=0,p.onChunk=PT,p.info=void 0,p.totalSize=0,p.partSize=0,p.fieldChunks=[],p.fieldSize=0}}}var Use=new TextDecoder("utf-8");function _Le(e){if(e==="utf-8"||e==="utf8"||e==="")return Use;try{return new TextDecoder(e)}catch(t){return Use}}function Pse(e,t){return _Le(e.contentTypeParameters.charset??"utf-8").decode(t)}var RW=Lse,Hse=wW,kW=Pse;var Rh=RT,Jr=EW;var kh=Symbol.for("@effect/platform/Multipart");var qse=Symbol.for("@effect/platform/Multipart/MultipartError");class ci extends ot()("MultipartError",{reason:_("FileTooLarge","FieldTooLarge","BodyTooLarge","TooManyParts","InternalError","Parse"),cause:bt}){[qse]=qse;get message(){return this.reason}}var Gse=(e)=>mr((t)=>{let r=Ot(t.currentContext,Kse);return Z({headers:e,maxParts:pt(Ot(t.currentContext,zse)),maxFieldSize:Number(Ot(t.currentContext,jse)),maxPartSize:Ot(t.currentContext,$se).pipe(jt(Number),pt),maxTotalSize:Ot(t.currentContext,If).pipe(jt(Number),pt),isFile:r.length===0?void 0:(n)=>!Oj(r,(o)=>n.contentType.includes(o))&&Hse(n)})});class Yse extends ha{[kh];constructor(){super();this[kh]=kh}}var LLe=(e,t)=>w(Cn,(r)=>De(xf(t.content,r.sink(e)),(n)=>new ci({reason:"InternalError",cause:n})));var Vse=(e,t=LLe)=>_e(function*(){let r=yield*Cn,n=yield*Jr,o=yield*r.makeTempDirectoryScoped(),s=Object.create(null);return yield*w1(e,(i)=>{if(i._tag==="Field"){if(!(i.key in s))s[i.key]=i.value;else if(typeof s[i.key]==="string")s[i.key]=[s[i.key],i.value];else s[i.key].push(i.value);return Y}else if(i.name==="")return Y;let a=i,c=n.join(o,n.basename(a.name).slice(-128)),l=new Jse(a.key,a.name,a.contentType,c);if(Array.isArray(s[i.key]))s[i.key].push(l);else s[i.key]=[l];return t(c,a)}),s}).pipe(yS({SystemError:(r)=>ce(new ci({reason:"InternalError",cause:r})),BadArgument:(r)=>ce(new ci({reason:"InternalError",cause:r}))}));class Jse extends Yse{key;name;contentType;path;_tag="PersistedFile";constructor(e,t,r,n){super();this.key=e,this.name=t,this.contentType=r,this.path=n}toJSON(){return{_id:"@effect/platform/Multipart/Part",_tag:"PersistedFile",key:this.key,name:this.name,contentType:this.contentType,path:this.path}}}class zse extends hr()("@effect/platform/Multipart/MaxParts",{defaultValue:T}){}class jse extends hr()("@effect/platform/Multipart/MaxFieldSize",{defaultValue:Yu(Gc(10485760))}){}class $se extends hr()("@effect/platform/Multipart/MaxFileSize",{defaultValue:T}){}class Kse extends hr()("@effect/platform/Multipart/FieldMimeTypes",{defaultValue:Yu(np("application/json"))}){}var Zse=Symbol.for("@effect/platform/Socket");var Xse=Ke("@effect/platform/Socket"),HLe=Symbol.for("@effect/platform/Socket/CloseEvent");var eie=(e)=>ee(e,HLe),DW=Symbol.for("@effect/platform/Socket/SocketError"),WLe=(e)=>ee(e,DW);class HT extends qc(DW,"SocketError"){get message(){return`An error occurred during ${this.reason}`}}class WT extends qc(DW,"SocketError"){static is(e){return WLe(e)&&e.reason==="Close"}static isClean(e){return function(t){return WT.is(t)&&e(t.code)}}get message(){if(this.closeReason)return`${this.reason}: ${this.code}: ${this.closeReason}`;return`${this.reason}: ${this.code}`}}var qLe=(e)=>e!==1000&&e!==1006,GLe=Ke("@effect/platform/Socket/WebSocket");var TW=(e,t)=>mr((r)=>{let n,o=Tc(!1),s=r.currentContext,i=t?.closeCodeIsError??qLe,a=(f,A)=>mE(Ht(function*(d){let g=yield*IE().pipe(Yl(d)),x=yield*Yl(e,d),y=yield*nn(nH(g)(),GLe,x),S=!1;function I(Q){if(Q.data instanceof Blob)return AE(()=>Q.data.arrayBuffer()).pipe(c6((F)=>f(new Uint8Array(F))),y);let P=f(Q.data);if(tn(P))y(P)}function B(Q){x.removeEventListener("message",I),x.removeEventListener("close",R),Yn(g.deferred,ce(new HT({reason:S?"Read":"Open",cause:Q})))}function R(Q){x.removeEventListener("message",I),x.removeEventListener("error",B),Yn(g.deferred,ce(new WT({reason:"Close",code:Q.code,closeReason:Q.reason})))}if(x.addEventListener("close",R,{once:!0}),x.addEventListener("error",B,{once:!0}),x.addEventListener("message",I),x.readyState!==1){let Q=Y8(r.id());x.addEventListener("open",()=>{S=!0,Yn(Q,Y)},{once:!0}),yield*ut(Q).pipe(zk({duration:t?.openTimeout??1e4,onTimeout:()=>new HT({reason:"OpenTimeout",cause:'timeout waiting for "open"'})}),$k(TS(g)))}if(S=!0,n=x,yield*o.open,A?.onOpen)yield*A.onOpen;return yield*TS(g).pipe(r6(WT.isClean((Q)=>!i(Q)),(Q)=>Y))})).pipe(gE((d)=>wr(s,d)),ws(se(()=>{o.unsafeClose(),n=void 0})),gr),c=new TextEncoder,l=(f,A)=>a((d)=>typeof d==="string"?f(c.encode(d)):d instanceof Uint8Array?f(d):f(new Uint8Array(d)),A),p=Z((f)=>o.whenOpen(se(()=>{let A=n;if(eie(f))A.close(f.code,f.reason);else A.send(f)})));return Z(Xse.of({[Zse]:Zse,run:l,runRaw:a,writer:p}))});var tie=Symbol.for("@effect/platform/HttpServerRequest"),rie=Ke("@effect/platform/HttpServerRequest");var nie=(e)=>{let t=e.headers.host??"localhost",r=e.headers["x-forwarded-proto"]==="https"?"https":"http";try{return M(new URL(e.url,`${r}://${t}`))}catch{return T()}};var qT=tie,Za=rie;var oie=nie;import*as VT from"node:child_process";var Xt=(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 lu({reason:o,module:e,method:t,pathOrDescriptor:n,syscall:r.syscall,description:r.message,cause:r})};import{Readable as VLe}from"node:stream";var vf=(e,t,r)=>bh(iie(e,t,r)),sie=(e,t)=>{let r=t.maxBytes?Number(t.maxBytes):void 0;return ef(se(()=>{let n=e();return n.setEncoding(t.encoding??"utf8"),n}),(n)=>Dt((o)=>{let s="",i=0;n.once("error",(a)=>{o(ce(t.onFailure(a)))}),n.once("end",()=>{o(Z(s))}),n.on("data",(a)=>{if(s+=a,i+=Buffer.byteLength(a),r&&i>r)o(ce(t.onFailure(Error("maxBytes exceeded"))))})}),(n)=>se(()=>{if("closed"in n&&!n.closed)n.destroy()}))},GT=(e,t)=>{let r=t.maxBytes?Number(t.maxBytes):void 0;return ef(se(e),(n)=>Dt((o)=>{let s=Buffer.alloc(0),i=0;n.once("error",(a)=>{o(ce(t.onFailure(a)))}),n.once("end",()=>{o(Z(s))}),n.on("data",(a)=>{if(s=Buffer.concat([s,a]),i+=a.length,r&&i>r)o(ce(t.onFailure(Error("maxBytes exceeded"))))})}),(n)=>se(()=>{if("closed"in n&&!n.closed)n.destroy()}))};var iie=(e,t,r)=>q1(()=>zLe(e(),t,Ri(void 0),r)),aie=(e,t,{encoding:r,endOnDone:n=!0}={},o=Y)=>{let s=JLe(e,r),i=n?Dt((a)=>{if("closed"in e&&e.closed)a(Y);else e.once("finish",()=>a(Y)),e.end()}):Y;return{awaitRead:()=>Y,emit:s,error:(a)=>ve(i,t(a)),done:(a)=>ve(i,o)}},JLe=(e,t)=>(r)=>r.length===0?Y:Dt((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(Y);else if(c)i();else e.once("drain",i)}i()}),zLe=(e,t,r,n)=>{if(!e.readable)return vI;let o=Tc(!1);function s(){o.unsafeOpen()}function i(u){r.current=Pl(t(u)),o.unsafeOpen()}function a(){r.current=Fi,o.unsafeOpen()}e.on("readable",s),e.on("error",i),e.on("end",a);let c=n?.chunkSize?Number(n.chunkSize):void 0,l=q1(function u(){let p=e.read(c);if(p===null){if(r.current)return ioe(r.current);return o.unsafeClose(),Sf(o.await,u)}let f=[p];while(!0){if(p=e.read(c),p===null)return Sf(oT(Qr(f)),u);f.push(p)}});return soe(l,se(()=>{if(e.off("readable",s),e.off("error",i),e.off("end",a),n?.closeOnDone!==!1&&"closed"in e&&!e.closed)e.destroy()}))};class cie extends VLe{readLatch;fiber=void 0;constructor(e,t){super({});this.readLatch=Tc(!1),this.fiber=rs(e)(this.readLatch.whenOpen(QI(t,(r)=>this.readLatch.whenOpen(se(()=>{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,Td(r))this.push(null);else this.destroy(bc(r.cause))})}_read(e){this.readLatch.unsafeOpen()}_destroy(e,t){if(!this.fiber)return t(e);jl(Xo(this.fiber)).addObserver((r)=>{t(r._tag==="Failure"?bc(r.cause):e)})}}var lie=(e)=>z(ts(),(t)=>new cie(t,e));var YT=(e,t,r)=>Fne(pie(e,t,r)),pie=(e,t,r)=>Sf(Ui(se(()=>e()),Pt()),([n,o])=>W1(jLe(n,o,t),aie(n,(s)=>Qc(o,s),r,Lk(o,Y)))),jLe=(e,t,r)=>Te(()=>{function n(o){Yn(t,ce(r(o)))}return e.on("error",n),ws(ut(t),se(()=>{e.removeListener("error",n)}))});var KLe=(e)=>typeof e==="string"?e:"pipe",fie=(e)=>typeof e==="string"?e:"pipe",JI=(e)=>e instanceof globalThis.Error?e:new globalThis.Error(String(e)),Of=(e,t,r)=>{let n=M1(r).reduce((o,s)=>{let i=`${s.command} ${s.args.join(" ")}`;return o.length===0?i:`${o} | ${i}`},"");return Xt("Command",e)(t,[n])},ZLe={[N1]:N1,...Ws,toJSON(){return{_id:"@effect/platform/CommandExecutor/Process",pid:this.pid}}},zI=(e)=>(t)=>{switch(t._tag){case"StandardCommand":{let r=w(Pt(),(s)=>Dt((i)=>{let a=VT.spawn(t.command,t.args,{stdio:[KLe(t.stdin),fie(t.stdout),fie(t.stderr)],cwd:je(t.cwd,Hm),shell:t.shell,env:{...process.env,...Object.fromEntries(t.env)},detached:process.platform!=="win32"});return a.on("error",(c)=>{i(ce(Of("spawn",c,t)))}),a.on("exit",(...c)=>{Yn(s,Z(c))}),a.on("spawn",()=>{i(Z([a,s]))}),se(()=>{a.kill("SIGTERM")})})),n=process.platform==="win32"?(s,i)=>Dt((a)=>{VT.exec(`taskkill /pid ${s.pid} /T /F`,(c)=>{if(c)a(ce(Of("kill",JI(c),t)));else a(Y)})}):(s,i)=>mo({try:()=>process.kill(-s.pid,i),catch:(a)=>Of("kill",JI(a),t)}),o=(s,i)=>Te(()=>s.kill(i)?Y:ce(Of("kill",new globalThis.Error("Failed to kill process"),t)));return E(Ge(t.cwd,{onNone:()=>Y,onSome:(s)=>e.access(s)}),ve(Mt(r,([s,i])=>w(Zp(i),(a)=>{if(!a)return n(s,"SIGTERM").pipe(e0(()=>o(s,"SIGTERM")),ve(ut(i)),La);return w(ut(i),([c])=>{if(c!==0&&c!==null)return n(s,"SIGTERM").pipe(La);return Y})}))),z(([s,i])=>{let a=Tne;if(s.stdin!==null)a=YT(()=>s.stdin,(d)=>Of("toWritable",JI(d),t));let c=w(ut(i),([d,g])=>{if(d!==null)return Z(Vne(d));return ce(Of("exitCode",new globalThis.Error(`Process interrupted due to receipt of signal: ${g}`),t))}),l=n6(Zp(i)),u=(d="SIGTERM")=>n(s,d).pipe(e0(()=>o(s,d)),ve(Pa(ut(i)))),p=Jne(s.pid),f=vf(()=>s.stderr,(d)=>Of("fromReadable(stderr)",JI(d),t)),A=vf(()=>s.stdout,(d)=>Of("fromReadable(stdout)",JI(d),t));if(typeof t.stdout!=="string")A=Rne(A,t.stdout);return Object.assign(Object.create(ZLe),{pid:p,exitCode:c,isRunning:l,kill:u,stdin:a,stderr:f,stdout:A})}),typeof t.stdin==="string"?X:Er((s)=>Vd(xf(t.stdin,s.stdin))))}case"PipedCommand":{let r=M1(t);if(r.length===1)return E(r[0],zI(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)=>E(XD(l,c),zI(e),z((u)=>u.stdout),Wc),E(zI(e)(n),z((c)=>c.stdout),Wc));return E(XD(i,a),zI(e))}}},Aie=Wa(kI,E(Cn,z((e)=>zne(zI(e)))));var die=Aie;var hie=(e,t,r)=>(...n)=>Dt((o)=>{try{e(...n,(s,i)=>{if(s)o(ce(t?t(s,n):s));else o(Z(i))})}catch(s){o(r?ce(r(s,n)):Mo(s))}});var Mr=hie;import*as mie from"node:crypto";import*as Ue from"node:fs";import*as gie from"node:os";import*as hx from"node:path";var Cr=(e)=>(t)=>new ls({module:"FileSystem",method:e,cause:t}),rPe=(()=>{let e=Mr(Ue.access,Xt("FileSystem","access"),Cr("access"));return(t,r)=>{let n=Ue.constants.F_OK;if(r?.readable)n|=Ue.constants.R_OK;if(r?.writable)n|=Ue.constants.W_OK;return e(t,n)}})(),nPe=(()=>{let e=Mr(Ue.cp,Xt("FileSystem","copy"),Cr("copy"));return(t,r,n)=>e(t,r,{force:n?.overwrite??!1,preserveTimestamps:n?.preserveTimestamps??!1,recursive:!0})})(),oPe=(()=>{let e=Mr(Ue.copyFile,Xt("FileSystem","copyFile"),Cr("copyFile"));return(t,r)=>e(t,r)})(),sPe=(()=>{let e=Mr(Ue.chmod,Xt("FileSystem","chmod"),Cr("chmod"));return(t,r)=>e(t,r)})(),iPe=(()=>{let e=Mr(Ue.chown,Xt("FileSystem","chown"),Cr("chown"));return(t,r,n)=>e(t,r,n)})(),aPe=(()=>{let e=Mr(Ue.link,Xt("FileSystem","link"),Cr("link"));return(t,r)=>e(t,r)})(),cPe=(()=>{let e=Mr(Ue.mkdir,Xt("FileSystem","makeDirectory"),Cr("makeDirectory"));return(t,r)=>e(t,{recursive:r?.recursive??!1,mode:r?.mode})})(),OW=(e)=>{let t=Mr(Ue.mkdtemp,Xt("FileSystem",e),Cr(e));return(r)=>Te(()=>{let n=r?.prefix??"",o=typeof r?.directory==="string"?hx.join(r.directory,"."):gie.tmpdir();return t(n?hx.join(o,n):o+"/")})},lPe=OW("makeTempDirectory"),FW=(e)=>{let t=Mr(Ue.rm,Xt("FileSystem",e),Cr(e));return(r,n)=>t(r,{recursive:n?.recursive??!1,force:n?.force??!1})},uPe=FW("remove"),pPe=(()=>{let e=OW("makeTempDirectoryScoped"),t=FW("makeTempDirectoryScoped");return(r)=>Mt(e(r),(n)=>qr(t(n,{recursive:!0})))})(),Eie=(e)=>{let t=Mr(Ue.open,Xt("FileSystem",e),Cr(e)),r=Mr(Ue.close,Xt("FileSystem",e),Cr(e));return(n,o)=>E(Mt(t(n,o?.flag??"r",o?.mode),(s)=>qr(r(s))),z((s)=>APe(loe(s),o?.flag?.startsWith("a")??!1)))},fPe=Eie("open"),APe=(()=>{let e=(u)=>Mr(Ue.read,Xt("FileSystem",u),Cr(u)),t=e("read"),r=e("readAlloc"),n=Mr(Ue.fstat,Xt("FileSystem","stat"),Cr("stat")),o=Mr(Ue.ftruncate,Xt("FileSystem","truncate"),Cr("truncate")),s=Mr(Ue.fsync,Xt("FileSystem","sync"),Cr("sync")),i=(u)=>Mr(Ue.write,Xt("FileSystem",u),Cr(u)),a=i("write"),c=i("writeAll");class l{fd;append;[iT];semaphore=l6(1);position=0n;constructor(u,p){this.fd=u,this.append=p,this[iT]=iT}get stat(){return z(n(this.fd),yie)}get sync(){return s(this.fd)}seek(u,p){let f=Gc(u);return this.semaphore.withPermits(1)(se(()=>{if(p==="start")this.position=f;else if(p==="current")this.position=this.position+f;return this.position}))}read(u){return this.semaphore.withPermits(1)(z(Te(()=>t(this.fd,{buffer:u,position:this.position})),(p)=>{let f=Gc(p);return this.position=this.position+f,f}))}readAlloc(u){let p=Number(u);return this.semaphore.withPermits(1)(w(se(()=>Buffer.allocUnsafeSlow(p)),(f)=>z(r(this.fd,{buffer:f,position:this.position}),(A)=>{if(A===0)return T();if(this.position=this.position+BigInt(A),A===p)return M(f);let d=Buffer.allocUnsafeSlow(A);return f.copy(d,0,0,A),M(d)})))}truncate(u){return this.semaphore.withPermits(1)(z(o(this.fd,u?Number(u):void 0),()=>{if(!this.append){let p=BigInt(u??0);if(this.position>p)this.position=p}}))}write(u){return this.semaphore.withPermits(1)(z(Te(()=>a(this.fd,u,void 0,void 0,this.append?void 0:Number(this.position))),(p)=>{let f=Gc(p);if(!this.append)this.position=this.position+f;return f}))}writeAllChunk(u){return w(Te(()=>c(this.fd,u,void 0,void 0,this.append?void 0:Number(this.position))),(p)=>{if(p===0)return ce(new lu({module:"FileSystem",method:"writeAll",reason:"WriteZero",pathOrDescriptor:this.fd,description:"write returned 0 bytes written"}));if(!this.append)this.position=this.position+BigInt(p);return p<u.length?this.writeAllChunk(u.subarray(p)):Y})}writeAll(u){return this.semaphore.withPermits(1)(this.writeAllChunk(u))}}return(u,p)=>new l(u,p)})(),xie=(e)=>{let t=OW(e),r=Eie(e),n=(o)=>se(()=>mie.randomBytes(o).toString("hex"));return(o)=>E(Ui(t(o),n(6)),z(([s,i])=>hx.join(s,i+(o?.suffix??""))),Er((s)=>ro(r(s,{flag:"w+"}))))},dPe=xie("makeTempFile"),hPe=(()=>{let e=xie("makeTempFileScoped"),t=FW("makeTempFileScoped");return(r)=>Mt(e(r),(n)=>qr(t(hx.dirname(n),{recursive:!0})))})(),mPe=(e,t)=>lr({try:()=>Ue.promises.readdir(e,t),catch:(r)=>Xt("FileSystem","readDirectory")(r,[e])}),gPe=(e)=>Dt((t,r)=>{try{Ue.readFile(e,{signal:r},(n,o)=>{if(n)t(ce(Xt("FileSystem","readFile")(n,[e])));else t(Z(o))})}catch(n){t(ce(Cr("readFile")(n)))}}),EPe=(()=>{let e=Mr(Ue.readlink,Xt("FileSystem","readLink"),Cr("readLink"));return(t)=>e(t)})(),xPe=(()=>{let e=Mr(Ue.realpath,Xt("FileSystem","realPath"),Cr("realPath"));return(t)=>e(t)})(),yPe=(()=>{let e=Mr(Ue.rename,Xt("FileSystem","rename"),Cr("rename"));return(t,r)=>e(t,r)})(),yie=(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:ct(e.mtime),atime:ct(e.atime),birthtime:ct(e.birthtime),dev:e.dev,rdev:ct(e.rdev),ino:ct(e.ino),mode:e.mode,nlink:ct(e.nlink),uid:ct(e.uid),gid:ct(e.gid),size:Gc(e.size),blksize:jt(ct(e.blksize),Gc),blocks:ct(e.blocks)}),MW=(()=>{let e=Mr(Ue.stat,Xt("FileSystem","stat"),Cr("stat"));return(t)=>z(e(t),yie)})(),CPe=(()=>{let e=Mr(Ue.symlink,Xt("FileSystem","symlink"),Cr("symlink"));return(t,r)=>e(t,r)})(),SPe=(()=>{let e=Mr(Ue.truncate,Xt("FileSystem","truncate"),Cr("truncate"));return(t,r)=>e(t,r!==void 0?Number(r):void 0)})(),IPe=(()=>{let e=Mr(Ue.utimes,Xt("FileSystem","utime"),Cr("utime"));return(t,r,n)=>e(t,r,n)})(),bPe=(e,t)=>Ane((r)=>Mt(se(()=>{let n=Ue.watch(e,{recursive:t?.recursive},(o,s)=>{if(!s)return;switch(o){case"rename":{r.fromEffect(of(MW(s),{onSuccess:(i)=>Z(uoe({path:s})),onFailure:(i)=>i._tag==="SystemError"&&i.reason==="NotFound"?Z(foe({path:s})):ce(i)}));return}case"change":{r.single(poe({path:s}));return}}});return n.on("error",(o)=>{r.fail(new lu({module:"FileSystem",reason:"Unknown",method:"watch",pathOrDescriptor:e,cause:o}))}),n.on("close",()=>{r.end()}),n}),(n)=>se(()=>n.close()))),BPe=(e,t,r)=>MW(t).pipe(z((n)=>e.pipe(Bn((o)=>o.register(t,n,r)),je(()=>bPe(t,r)))),wI),QPe=(e,t,r)=>Dt((n,o)=>{try{Ue.writeFile(e,t,{signal:o,flag:r?.flag,mode:r?.mode},(s)=>{if(s)n(ce(Xt("FileSystem","writeFile")(s,[e])));else n(Y)})}catch(s){n(ce(Cr("writeFile")(s)))}}),wPe=z(bS(Y1),(e)=>coe({access:rPe,chmod:sPe,chown:iPe,copy:nPe,copyFile:oPe,link:aPe,makeDirectory:cPe,makeTempDirectory:lPe,makeTempDirectoryScoped:pPe,makeTempFile:dPe,makeTempFileScoped:hPe,open:fPe,readDirectory:mPe,readFile:gPe,readLink:EPe,realPath:xPe,remove:uPe,rename:yPe,stat:MW,symlink:CPe,truncate:SPe,utimes:IPe,watch(t,r){return BPe(e,t,r)},writeFile:QPe})),Cie=Wa(Cn,wPe);var JT=Cie;import*as jI from"node:path";import*as zT from"node:url";var NW=(e)=>mo({try:()=>zT.fileURLToPath(e),catch:(t)=>new ls({module:"Path",method:"fromFileUrl",description:`Invalid file URL: ${e}`,cause:t})}),_W=(e)=>mo({try:()=>zT.pathToFileURL(e),catch:(t)=>new ls({module:"Path",method:"toFileUrl",description:`Invalid path: ${e}`,cause:t})}),kPe=Li(Jr,Jr.of({[Rh]:Rh,...jI.posix,fromFileUrl:NW,toFileUrl:_W})),DPe=Li(Jr,Jr.of({[Rh]:Rh,...jI.win32,fromFileUrl:NW,toFileUrl:_W})),Iie=Li(Jr,Jr.of({[Rh]:Rh,...jI,fromFileUrl:NW,toFileUrl:_W}));var jT=Iie;var Bie=Ke("@effect/platform/Terminal");var UW=Bie;import*as $T from"node:readline";var Qie=(e)=>e.key.ctrl&&(e.key.name==="c"||e.key.name==="d"),wie=Ht(function*(e=Qie){let t=process.stdin,r=process.stdout,n=yield*xre({acquire:Mt(se(()=>{let u=$T.createInterface({input:t,escapeCodeTimeout:50});if($T.emitKeypressEvents(t,u),t.isTTY)t.setRawMode(!0);return u}),(u)=>se(()=>{if(t.isTTY)t.setRawMode(!1);u.close()}))}),o=se(()=>r.columns??0),s=se(()=>r.rows??0),i=se(()=>Boolean(r.isTTY)),a=_e(function*(){yield*l1(n);let u=yield*Df(),p=(f,A)=>{let d={input:ct(f),key:{name:A.name??"",ctrl:!!A.ctrl,meta:!!A.meta,shift:!!A.shift}};if(u.unsafeOffer(d),e(d))u.unsafeDone(Fi)};return yield*hE(()=>se(()=>t.off("keypress",p))),t.on("keypress",p),u}),c=l1(n).pipe(w((u)=>Dt((p)=>{let f=(A)=>p(Z(A));return u.once("line",f),se(()=>u.off("line",f))})),ro),l=(u)=>_i(Dt((p)=>{r.write(u,(f)=>f?p(ce(new ls({module:"Terminal",method:"display",description:"Failed to write prompt to stdout",cause:f}))):p(Y))}));return UW.of({columns:o,rows:s,isTTY:i,readInput:a,readLine:c,display:l})}),Rie=Oc(UW,wie(Qie));var kie=Rie;class KT extends wi("@effect/platform/Transferable/Collector")(){}var Die=()=>{let e=[],t=(o)=>{e.push(...o)},r=()=>e,n=()=>{let o=e;return e=[],o};return KT.of({unsafeAddAll:t,addAll:(o)=>se(()=>t(o)),unsafeRead:r,read:se(r),unsafeClear:n,clear:se(n)})};var Tie=Symbol.for("@effect/platform/WorkerError");var vie=Tie;class gu extends ot()("WorkerError",{reason:_("spawn","decode","send","unknown","encode"),cause:bt}){[vie]=vie;static Cause=pte({error:this,defect:bt});static encodeCause=UE(this.Cause);static decodeCause=M0(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 LW=Symbol.for("@effect/platform/Worker/PlatformWorker"),ZT=Ke("@effect/platform/Worker/PlatformWorker"),PW=Symbol.for("@effect/platform/Worker/WorkerManager"),HW=Ke("@effect/platform/Worker/WorkerManager"),Oie=Ke("@effect/platform/Worker/Spawner"),Fie=_e(function*(){let e=yield*ZT,t=0;return HW.of({[PW]:PW,spawn({encode:r,initialMessage:n}){return _e(function*(){let o=t++,s=0,i=new Map,a=Die(),c=r?(x)=>ve(a.clear,nn(r(x),KT,a)):Z,l=yield*Pt(),u=yield*e.spawn(o);yield*u.run((x)=>{if(x[0]===0)return Lk(l,Y);return p(x[1])}).pipe(SS((x)=>Kt(i.values(),(y)=>(Kp in y)?Qc(y,x):y.failCause(x))),Rc(kc),CS(fH(1000)),Dc({package:"@effect/platform",module:"Worker"}),gr,rf),yield*hE(()=>ve(Kt(i.values(),(x)=>(Kp in x)?LP(x):x.end,{discard:!0}),se(()=>i.clear())));let p=(x)=>Te(()=>{let y=i.get(x[0]);if(!y)return Y;switch(x[1]){case 0:return Kp in y?Gn(y,x[2][0]):y.offerAll(x[2]);case 1:{if(x.length===2)return Kp in y?LP(y):y.end;return Kp in y?Gn(y,x[2][0]):ve(y.offerAll(x[2]),y.end)}case 2:case 3:{if(x[1]===2)return Kp in y?xS(y,x[2]):y.fail(x[2]);let S=gu.decodeCause(x[2]);return Kp in y?Qc(y,S):y.failCause(S)}}}),f=(x,y)=>mr((S)=>{let I=S.getFiberRef(sf),B=Jo(I,uZ).pipe(qs((Q)=>Q._tag==="Span")),R=s++;return y.pipe(Er((Q)=>(i.set(R,Q),c(x).pipe(Er((P)=>u.send([R,0,P,B._tag==="Some"?[B.value.traceId,B.value.spanId,B.value.sampled]:void 0],a.unsafeRead())),rn((P)=>Dse(Q)?Q.failCause(P):Qc(Q,P))))),z((Q)=>({id:R,mailbox:Q})))}),A=({id:x},y)=>{let S=se(()=>i.delete(x));return vo(y)?ve(qr(u.send([x,1])),S):S},d=(x)=>bh(ooe(f(x,Df()),({mailbox:y})=>Tse(y),A)),g=(x)=>ef(f(x,Pt()),({mailbox:y})=>ut(y),A);if(yield*ut(l),n)yield*se(n).pipe(w(g),De((x)=>new gu({reason:"spawn",cause:x})));return{id:o,execute:d,executeEffect:g}})}})}),Mie=Wa(HW,Fie);var Nie=()=>(e)=>ZT.of({[LW]:LW,spawn(t){return _e(function*(){let r=yield*Oie,n,o=[];return{run:(a)=>Jl((c)=>_e(function*(){let l=yield*tf,u=yield*e.setup({worker:r(t),scope:l});n=u,yield*Qs(l,se(()=>{n=void 0}));let p=(yield*ts()).pipe(D6(M$(iE))),f=yield*IE(),A=rs(p);if(yield*e.listen({port:u,scope:l,emit(d){u0(f,A(a(d)))},deferred:f.deferred}),o.length>0){for(let[d,g]of o)u.postMessage([0,d],g);o.length=0}return yield*c(TS(f))}).pipe(ro)),send:(a,c)=>mo({try:()=>{if(n===void 0)o.push([a,c]);else n.postMessage([0,a],c)},catch:(l)=>new gu({reason:"send",cause:l})})}})}});var _ie=Nie,Uie=ZT;var Lie=Mie;var PPe=_ie()({setup({scope:e,worker:t}){return w(Pt(),(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",()=>{Yn(r,Fi)}),go(Qs(e,Te(()=>(n.postMessage([1]),ut(r))).pipe(gr,nf(5000),rn(()=>se(()=>n.kill())))),n)})},listen({deferred:e,emit:t,port:r}){return r.worker.on("message",(n)=>{t(n)}),r.worker.on("messageerror",(n)=>{Yn(e,new gu({reason:"decode",cause:n}))}),r.worker.on("error",(n)=>{Yn(e,new gu({reason:"unknown",cause:n}))}),r.worker.on("exit",(n)=>{Yn(e,new gu({reason:"unknown",cause:Error(`exited with code ${n}`)}))}),Y}}),Pie=Li(Uie,PPe),Hie=no(Lie,Pie);var Wie=Hie;var WW=E($d(jT,die,kie,Wie),n0(JT));var Dh=JT;import*as tv from"node:http";import*as rv from"node:https";import{Readable as zie}from"node:stream";import{pipeline as GPe}from"node:stream/promises";var qie=YT;var ev=vf;var Gie=lie;var Yie=sie,Vie=GT;class $I extends ha{source;onError;remoteAddressOverride;[us];constructor(e,t,r){super();this.source=e,this.onError=t,this.remoteAddressOverride=r,this[us]=us}get headers(){return Kn(this.source.headers)}get remoteAddress(){return ct(this.remoteAddressOverride??this.source.socket.remoteAddress)}textEffect;get text(){if(this.textEffect)return this.textEffect;return this.textEffect=on(Zs(w(If,(e)=>Yie(()=>this.source,{onFailure:this.onError,maxBytes:pt(e)})))),this.textEffect}get unsafeText(){return on(this.text)}get json(){return Xp(this.text,{try:(e)=>e===""?null:JSON.parse(e),catch:this.onError})}get unsafeJson(){return on(this.json)}get urlParamsBody(){return w(this.text,(e)=>mo({try:()=>Vc(new URLSearchParams(e)),catch:this.onError}))}get stream(){return ev(()=>this.source,this.onError)}get arrayBuffer(){return w(If,(e)=>Vie(()=>this.source,{onFailure:this.onError,maxBytes:pt(e)}))}}var GW=Symbol.for("@effect/platform-node/Http/NodeClient/HttpAgent"),YW=Ke("@effect/platform-node/Http/NodeClient/HttpAgent"),jie=(e)=>z(wc([Mt(se(()=>new tv.Agent(e)),(t)=>se(()=>t.destroy())),Mt(se(()=>new rv.Agent(e)),(t)=>se(()=>t.destroy()))]),([t,r])=>({[GW]:GW,http:t,https:r})),$ie=(e)=>Oc(YW,jie(e)),Kie=$ie(),YPe=(e)=>ST((t,r,n)=>{let o=r.protocol==="https:"?rv.request(r,{agent:e.https,method:t.method,headers:t.headers,signal:n}):tv.request(r,{agent:e.http,method:t.method,headers:t.headers,signal:n});return E(ve(VPe(o,t,t.body),JPe(o,t),{concurrent:!0}),z((s)=>new Zie(t,s)))}),VPe=(e,t,r)=>Te(()=>{switch(r._tag){case"Empty":return e.end(),Jie(e,t);case"Uint8Array":case"Raw":return e.end(r.body),Jie(e,t);case"FormData":{let n=new Response(r.formData);return n.headers.forEach((o,s)=>{e.setHeader(s,o)}),lr({try:()=>GPe(zie.fromWeb(n.body),e),catch:(o)=>new si({request:t,reason:"Transport",cause:o})})}case"Stream":return xf(Sne(r.stream,(n)=>new si({request:t,reason:"Encode",cause:n})),qie(()=>e,(n)=>new si({request:t,reason:"Transport",cause:n})))}}),JPe=(e,t)=>Dt((r)=>{function n(s){r(ce(new si({request:t,reason:"Transport",cause:s})))}e.on("error",n);function o(s){e.off("error",n),r(Z(s))}return e.on("upgrade",o),e.on("response",o),se(()=>{e.off("error",n),e.off("upgrade",o),e.off("response",o)})}),Jie=(e,t)=>Dt((r)=>{function n(s){r(ce(new si({request:t,reason:"Transport",cause:s})))}e.once("error",n);function o(){e.off("error",n),r(Y)}return e.once("finish",o),se(()=>{e.off("error",n),e.off("finish",o)})});class Zie extends $I{request;[wf];constructor(e,t){super(t,(r)=>new an({request:e,response:this,reason:"Decode",cause:r}));this.request=e,this[wf]=wf}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=cx(e);return this.cachedCookies=uu}get formData(){return lr({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(zie.toWeb(this.source),e).formData()},catch:this.onError})}toJSON(){return bf(this,{_id:"@effect/platform/HttpClientResponse",request:this.request.toJSON(),status:this.status})}}var Xie=z(YW,YPe),eae=bT(Xie),tae=no(eae,Kie);var WEe=Ii(gV(),1);_M(ym,Ii(gV(),1));var EV=Ke("@effect/platform-node/NodeHttpClient/Dispatcher");var qEe="@effect/platform-node/NodeHttpClient/undiciOptions",GEe=(e)=>ST((t,r,n,o)=>{let i=o.getFiberRef(sf).unsafeMap.get(qEe)??{};return k9e(t.body).pipe(w((a)=>lr({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 si({request:t,reason:"Transport",cause:c})})),z((a)=>new YEe(t,a)))});function k9e(e){switch(e._tag){case"Empty":return Z(null);case"Uint8Array":case"Raw":return Z(e.body);case"FormData":return Z(e.formData);case"Stream":return Gie(e.stream)}}function D9e(e){}class YEe extends ha{request;source;[us];[wf];constructor(e,t){super();this.request=e,this.source=t,this[us]=us,this[wf]=wf,t.body.on("error",D9e)}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=cx(Array.isArray(e)?e:[e]);return this.cachedCookies=uu}get headers(){return Kn(this.source.headers)}get remoteAddress(){return T()}get stream(){return ev(()=>this.source.body,(e)=>new an({request:this.request,response:this,reason:"Decode",cause:e}))}get json(){return Xp(this.text,{try:(e)=>e===""?null:JSON.parse(e),catch:(e)=>new an({request:this.request,response:this,reason:"Decode",cause:e})})}textBody;get text(){return this.textBody??=lr({try:()=>this.source.body.text(),catch:(e)=>new an({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Zs,on)}get urlParamsBody(){return w(this.text,(e)=>mo({try:()=>Vc(new URLSearchParams(e)),catch:(t)=>new an({request:this.request,response:this,reason:"Decode",cause:t})}))}formDataBody;get formData(){return this.formDataBody??=lr({try:()=>this.source.body.formData(),catch:(e)=>new an({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Zs,on)}arrayBufferBody;get arrayBuffer(){return this.arrayBufferBody??=lr({try:()=>this.source.body.arrayBuffer(),catch:(e)=>new an({request:this.request,response:this,reason:"Decode",cause:e})}).pipe(Zs,on)}toJSON(){return bf(this,{_id:"@effect/platform/HttpClientResponse",request:this.request.toJSON(),status:this.status})}}var VEe=bT(z(EV,GEe));var v9e=tae;var O9e=EV;var F9e=VEe;import{Duplex as M9e,Readable as N9e}from"node:stream";class JEe extends M9e{_parser;_canWrite=!0;_writeCallback;constructor(e){super({readableObjectMode:!0});let t,r;this._parser=RW({...e,onField:(n,o)=>{if(t!==void 0)return;let s={_tag:"Field",info:n,value:o};this.push(s),this.emit("field",s)},onFile:(n)=>{if(t!==void 0)return(s)=>{};let o=new jEe(n,this);return r=o,this.push(o),this.emit("file",o),(s)=>{if(this._canWrite=o.push(s),s===null&&!this._canWrite)r=void 0,this._resume()}},onError:(n)=>{this.emit("error",n),r?.emit("error",n),t=n},onDone:()=>{this.push(null)}})}_resume(){if(this._canWrite=!0,this._writeCallback!==void 0){let e=this._writeCallback;this._writeCallback=void 0,e()}}_read(e){}_write(e,t,r){if(this._parser.write(e instanceof Uint8Array?e:Buffer.from(e,t)),this._canWrite)r();else this._writeCallback=r}_final(e){this._parser.end(),e()}}var zEe=(e)=>new JEe(e);class jEe extends N9e{info;_parent;_tag="File";filename;constructor(e,t){super();this.info=e,this._parent=t,this.filename=e.filename}_read(e){if(this._parent._canWrite===!1)this._parent._resume()}}import*as $Ee from"node:fs";import*as KEe from"node:stream/promises";var yV=(e,t)=>E(Gse(t),z((r)=>vf(()=>{let n=zEe(r);return e.pipe(n),n},(n)=>L9e(n))),wI,xne(U9e)),ZEe=(e,t)=>Vse(yV(e,t),(r,n)=>lr({try:(o)=>KEe.pipeline(n.file,$Ee.createWriteStream(r),{signal:o}),catch:(o)=>new ci({reason:"InternalError",cause:o})})),U9e=(e)=>e._tag==="Field"?new XEe(e.info,e.value):new exe(e);class CV extends ha{[kh];constructor(){super();this[kh]=kh}}class XEe extends CV{_tag="Field";key;contentType;value;constructor(e,t){super();this.key=e.name,this.contentType=e.contentType,this.value=kW(e,t)}toJSON(){return{_id:"@effect/platform/Multipart/Part",_tag:"Field",key:this.key,value:this.value,contentType:this.contentType}}}class exe extends CV{file;_tag="File";key;name;contentType;content;contentEffect;constructor(e){super();this.file=e,this.key=e.info.name,this.name=e.filename??e.info.name,this.contentType=e.info.contentType,this.content=vf(()=>e,(t)=>new ci({reason:"InternalError",cause:t})),this.contentEffect=GT(()=>e,{onFailure:(t)=>new ci({reason:"InternalError",cause:t})})}toJSON(){return{_id:"@effect/platform/Multipart/Part",_tag:"File",key:this.key,name:this.name,contentType:this.contentType}}}function L9e(e){switch(e._tag){case"ReachedLimit":switch(e.limit){case"MaxParts":return new ci({reason:"TooManyParts",cause:e});case"MaxFieldSize":return new ci({reason:"FieldTooLarge",cause:e});case"MaxPartSize":return new ci({reason:"FileTooLarge",cause:e});case"MaxTotalSize":return new ci({reason:"BodyTooLarge",cause:e})}default:return new ci({reason:"Parse",cause:e})}}var txe=yV,rxe=ZEe;var nxe=X;var oxe=Ae(Symbol.for("@effect/platform/HttpApp/preResponseHandlers"),()=>Pi(T()));var q9e=(e)=>e;var G9e=Ae(Symbol.for("@effect/platform/HttpMiddleware/tracerDisabledWhen"),()=>Pi(tr));var Y9e=hr()("@effect/platform/HttpMiddleware/SpanNameGenerator",{defaultValue:()=>(e)=>`http.server ${e.method}`});var SV=q9e((e)=>mr((t)=>{let r=Ro(t.currentContext,Za);if(t.getFiberRef(G9e)(r))return e;let o=pt(oie(r));if(o!==void 0&&(o.username!==""||o.password!==""))o.username="REDACTED",o.password="REDACTED";let s=t.getFiberRef(TI),i=Bh(r.headers,s),a=Ot(t.currentContext,Y9e);return CE(a(r),{parent:pt(Eoe(r.headers)),kind:"server",captureStackTrace:!1},(c)=>{if(c.attribute("http.request.method",r.method),o!==void 0){if(c.attribute("url.full",o.toString()),c.attribute("url.path",o.pathname),o.search.slice(1)!=="")c.attribute("url.query",o.search.slice(1));c.attribute("url.scheme",o.protocol.slice(0,-1))}if(r.headers["user-agent"]!==void 0)c.attribute("user_agent.original",r.headers["user-agent"]);for(let l in i)c.attribute(`http.request.header.${l}`,String(i[l]));if(r.remoteAddress._tag==="Some")c.attribute("client.address",r.remoteAddress.value);return w(Dr(jd(e,c)),(l)=>{let u=bse(l);c.attribute("http.response.status_code",u.status);let p=Bh(u.headers,s);for(let f in p)c.attribute(`http.response.header.${f}`,String(p[f]));return l})})}));var ay=Symbol.for("@effect/platform/HttpApp/handled"),IV=(e,t,r)=>{let n=mr((i)=>w(e,(a)=>{let c=Ro(i.currentContext,Za),l=i.getFiberRef(sxe);if(l._tag==="None")return c[ay]=!0,go(t(c,a),a);return Er(l.value(c,a),(u)=>(c[ay]=!0,t(c,u)))})),o=rn(n,(i)=>mr((a)=>w(qI(i),([c,l])=>{let u=Ro(a.currentContext,Za),p=a.getFiberRef(sxe);if(p._tag==="None")return u[ay]=!0,ve(t(u,c),Vp(l)?Z(c):kr(l));return ve(Er(p.value(u,c),(f)=>(u[ay]=!0,t(u,f))),Vp(l)?Z(c):kr(l))}))),s=nxe(r===void 0?SV(o):xn(SV(r(o)),{onFailure:(i)=>mr((a)=>{let c=Ro(a.currentContext,Za);if(ay in c)return Y;return xn(qI(i),{onFailure:(l)=>t(c,kf({status:500})),onSuccess:([l])=>t(c,l)})}),onSuccess:(i)=>mr((a)=>{let c=Ro(a.currentContext,Za);return ay in c?Y:t(c,i)})}));return _i(z9e(s))};var J9e=Ae("@effect/platform/HttpApp/ejectedScopes",()=>new WeakSet),z9e=(e)=>w(bk(),(t)=>o6(Yl(e,t),(r)=>{if(J9e.has(t))return Y;return Jp(t,r)})),sxe=oxe;import*as HV from"node:http";import{Readable as b8e}from"node:stream";import{pipeline as B8e}from"node:stream/promises";var f8e=Ii(Xxe(),1),A8e=Ii(rF(),1),d8e=Ii(uy(),1),h8e=Ii(kV(),1),m8e=Ii(TV(),1),g8e=Ii(_V(),1),lF=Ii(aF(),1),UV=Ii(sye(),1);var iye=mW,aye=lse;var LV=Ii(hye(),1);import*as mye from"node:fs";import{Readable as C8e}from"node:stream";var S8e=aye({fileResponse(e,t,r,n,o,s,i){let a=mye.createReadStream(e,{start:o,end:s});return IW(a,{headers:{...n,"content-type":n["content-type"]??LV.default.getType(e)??"application/octet-stream","content-length":i.toString()},status:t,statusText:r})},fileWebResponse(e,t,r,n,o){return IW(C8e.fromWeb(e.stream()),{headers:Ka(n,pu({"content-type":n["content-type"]??LV.default.getType(e.name)??"application/octet-stream","content-length":e.size.toString()})),status:t,statusText:r})}}),gye=E(Wa(iye,S8e),no(Dh),no(nse));var Eye=(e,t)=>_e(function*(){let r=yield*tf,n=yield*Mt(se(e),(i)=>Dt((a)=>{if(!i.listening)return a(Y);i.close((c)=>{if(c)a(Mo(c));else a(Y)})}));yield*Dt((i)=>{function a(c){i(ce(new vT({cause:c})))}n.on("error",a),n.listen(t,()=>{n.off("error",a),i(Y)})});let o=n.address(),s=yield*E(Mt(se(()=>new UV.default({noServer:!0})),(i)=>Dt((a)=>{i.close(()=>a(Y))})),Yl(r),Zs);return dse({address:typeof o==="string"?{_tag:"UnixAddress",path:o}:{_tag:"TcpAddress",hostname:o.address==="::"?"0.0.0.0":o.address,port:o.port},serve:(i,a)=>_e(function*(){let c=yield*xye(i,a),l=yield*Q8e(s,i,a);yield*hE(()=>se(()=>{n.off("request",c),n.off("upgrade",l)})),n.on("request",c),n.on("upgrade",l)})})}).pipe(nn(If,M(Gc(10485760)))),xye=(e,t)=>{let r=IV(e,Sye,t);return z(ts(),(n)=>{let o=rs(n);return function(i,a){let c=o(nn(r,Za,new pF(i,a)));a.on("close",()=>{if(!a.writableEnded)c.unsafeInterruptAsFork(OT)})}})},Q8e=(e,t,r)=>{let n=IV(t,Sye,r);return z(_6(),(o)=>function(i,a,c){let l=void 0,u=()=>{if(l===void 0)l=new HV.ServerResponse(i),l.assignSocket(a),l.on("finish",()=>{a.end()});return l},p=TW(w(e,(A)=>Mt(Dt((d)=>A.handleUpgrade(i,a,c,(g)=>{d(Z(g))})),(d)=>se(()=>d.close())))),f=o(nn(n,Za,new pF(i,u,p)));a.on("close",()=>{if(!a.writableEnded)f.unsafeInterruptAsFork(OT)})})};class pF extends $I{source;response;upgradeEffect;url;headersOverride;[qT];constructor(e,t,r,n=e.url,o,s){super(e,(i)=>new WI({request:this,reason:"Decode",cause:i}),s);this.source=e,this.response=t,this.upgradeEffect=r,this.url=n,this.headersOverride=o,this[qT]=qT}cachedCookies;get cookies(){if(this.cachedCookies)return this.cachedCookies;return this.cachedCookies=Xne(this.headers.cookie??"")}get resolvedResponse(){return typeof this.response==="function"?this.response():this.response}modify(e){return new pF(this.source,this.response,this.upgradeEffect,e.url??this.url,e.headers??this.headersOverride,e.remoteAddress??this.remoteAddressOverride)}get originalUrl(){return this.source.url}get method(){return this.source.method.toUpperCase()}get headers(){return this.headersOverride??=this.source.headers,this.headersOverride}multipartEffect;get multipart(){if(this.multipartEffect)return this.multipartEffect;return this.multipartEffect=on(Zs(rxe(this.source,this.source.headers))),this.multipartEffect}get multipartStream(){return txe(this.source,this.source.headers)}get upgrade(){return this.upgradeEffect??ce(new WI({request:this,reason:"Decode",description:"not an upgradeable ServerRequest"}))}toString(){return`ServerRequest(${this.method} ${this.url})`}toJSON(){return bf(this,{_id:"@effect/platform/HttpServerRequest",method:this.method,url:this.originalUrl})}}var yye=$d(gye,AW,WW),Cye=(e,t)=>$d(Oc(yW,Eye(e,t)),yye);var Sye=(e,t)=>Te(()=>{let r=e.resolvedResponse;if(r.writableEnded)return Y;let n=t.headers;if(!L1(t.cookies)){n={...n};let s=rT(t.cookies);if(n["set-cookie"]!==void 0)s.push(n["set-cookie"]);n["set-cookie"]=s}if(e.method==="HEAD")return r.writeHead(t.status,n),Dt((s)=>{r.end(()=>s(Y))});let o=t.body;switch(o._tag){case"Empty":return r.writeHead(t.status,n),r.end(),Y;case"Raw":{if(r.writeHead(t.status,n),typeof o.body==="object"&&o.body!==null&&"pipe"in o.body&&typeof o.body.pipe==="function")return lr({try:(s)=>B8e(o.body,r,{signal:s,end:!0}),catch:(s)=>new TT({request:e,response:t,reason:"Decode",cause:s})}).pipe(gr,Rc(PV(r,t)));return Dt((s)=>{r.end(o.body,()=>s(Y))})}case"Uint8Array":return r.writeHead(t.status,n),Dt((s)=>{r.end(o.body,()=>s(Y))});case"FormData":return Te(()=>{let s=new Response(o.formData);return r.writeHead(t.status,{...n,...Object.fromEntries(s.headers)}),Dt((i,a)=>{b8e.fromWeb(s.body,{signal:a}).pipe(r).on("error",(c)=>{i(ce(new TT({request:e,response:t,reason:"Decode",cause:c})))}).once("finish",()=>{i(Y)})}).pipe(gr,Rc(PV(r,t)))});case"Stream":{r.writeHead(t.status,n);let s=Tc();return r.on("drain",()=>s.unsafeOpen()),o.stream.pipe(Ine,QI((i)=>{let a=hn(i);if(a.length===0)return Y;let c=!1;for(let l=0;l<a.length;l++){let u=r.write(a[l]);if(!u&&!c)c=!0,s.unsafeClose();else if(u&&c)c=!1}if(!c)return Y;return s.await}),gr,xn({onSuccess:()=>se(()=>r.end()),onFailure:PV(r,t)}))}}}),PV=(e,t)=>(r)=>qI(r).pipe(w(([n,o])=>{let s=e.headersSent;if(!s)e.writeHead(n.status);if(!e.writableEnded)e.end();return kr(s?Ld(r,$s(t)):o)}));var R8e=Cye;var hB=jT;var bye=new URL("../",import.meta.url),Bye=new URL("skills/expandai/",bye),$Ut=new URL("assets/opencode/expandai-webfetch.js",bye);class k8e extends ot()("McpParseError",{path:m,error:bt}){get message(){return`Failed to parse MCP config at ${this.path}: ${Ve(this.error)}`}}class D8e extends ot()("McpWriteError",{path:m,error:bt}){get message(){return`Failed to write MCP config at ${this.path}: ${Ve(this.error)}`}}var T8e=_("claude-code","cursor","opencode","codex","fx"),Rye=_(...T8e.literals,"unknown"),rLt=_("project","global"),fF=Fn({key:m,value:Tt}),nLt=xo(b({mcpServers:C(fF,{default:()=>({})})},fF),{space:2}),oLt=xo(b({mcp:C(fF,{default:()=>({})})},fF),{space:2}),kye="expandai",v8e={command:"expandai",args:[]},O8e={command:"npx",args:["-y","expandai"]};var Qye=_e(function*(){let e=yield*Cn,t=yield*Jr,r=yield*Do("PATH").pipe(bd("")),n=yield*Do("PATHEXT").pipe(bd(".COM;.EXE;.BAT;.CMD")),o=t.sep==="\\",s=o?["",...nC(n.split(";"),RP)]:[""];return{resolve:we("CliInvocation.resolve")(function*(){let a=nC(r.split(o?";":":"),RP);return(yield*t6(a,(l)=>t6(s,(u)=>e.exists(t.join(l.replace(/^"(.*)"$/u,"$1"),`expandai${u}`)).pipe(yE(()=>!1)))))?v8e:O8e})}});class qV extends vc()("@expandai/cli/Install/CliInvocation",{dependencies:[Dh,hB],effect:Qye}){static layer=Wa(qV,Qye.pipe(z(qV.make)))}var F8e=we(function*(e){let t=yield*Cn;if(!(yield*t.exists(e)))return"{}";return yield*t.readFileString(e)}),wye=we(function*(e,t){let r=yield*Cn,n=yield*Jr;yield*r.makeDirectory(n.dirname(e),{recursive:!0}),yield*r.writeFileString(e,`${t}
|
|
183
|
-
`)});class M8e extends vc()("@expandai/cli/Install/ConfigIo",{dependencies:[Dh,hB],effect:_e(function*(){let e=yield*Cn,t=yield*Jr,r=we("ConfigIo.read")(function*(a,c){let l=yield*F8e(a).pipe(nn(Cn,e));return yield*P0(c)(l)}),n=we("ConfigIo.write")(function*(a,c,l){let u=yield*hh(l)(c);yield*wye(a,u).pipe(nn(Cn,e),nn(Jr,t))}),o=we("ConfigIo.exists")(function*(a){return yield*e.exists(a)}),s=we("ConfigIo.readText")(function*(a){return(yield*e.exists(a))?yield*e.readFileString(a):""}),i=we("ConfigIo.writeText")(function*(a,c){yield*wye(a,c).pipe(nn(Cn,e),nn(Jr,t))});return{read:r,write:n,exists:o,readText:s,writeText:i}})}){}class N8e extends vc()("@expandai/cli/Install/SkillIo",{dependencies:[Dh,hB],effect:_e(function*(){let e=yield*Cn,t=yield*Jr,r=yield*t.fromFileUrl(Bye),n=we("SkillIo.install")(function*(a){return yield*e.makeDirectory(t.dirname(a),{recursive:!0}),yield*e.copy(r,a,{overwrite:!0}),a}),o=we("SkillIo.uninstall")(function*(a){if(yield*e.exists(a))yield*e.remove(a,{recursive:!0});return a}),s=we("SkillIo.isCurrent")(function*(a){let c=t.join(a,"SKILL.md");if(!(yield*e.exists(c)))return!1;let[l,u]=yield*wc([e.readFileString(c),e.readFileString(t.join(r,"SKILL.md"))]);return l===u}),i=we("SkillIo.isInstalled")(function*(a){return yield*e.exists(t.join(a,"SKILL.md"))});return{install:n,uninstall:o,isCurrent:s,isInstalled:i}})}){}var mB="0.1.5";var Dye=Symbol.for("effect/PrimaryKey");var GV=Symbol.for("@effect/rpc/RpcSchema/Stream"),vye=(e)=>e.ast.annotations[th]===GV;var Oye=({failure:e,success:t})=>Object.assign(ni([t,e],{decode:(r,n)=>Tye(Lc(S2(r)),Lc(n)),encode:(r,n)=>Tye(Pc(S2(r)),Pc(n))},{schemaId:GV,[GV]:{success:t,failure:e}}),{success:t,failure:e}),U8e=(e)=>ee(e,B1),Tye=(e,t)=>(r,n,o)=>w(vn(),(s)=>{if(!U8e(r))return ce(new Fr(o,r));return Z(r.pipe(Cne((i)=>e(i,n)),Q1((i)=>{if(NE(i))return hne(i);return of(t(i,n),{onFailure:Mo,onSuccess:ce})}),jD(s)))});var Mye=Symbol.for("@effect/rpc/Rpc");var P8e={[Mye]:Mye,pipe(){return W(this,arguments)},setSuccess(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return Ou({_tag:this._tag,payloadSchema:On(e)?e:b(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return Ou({_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 Ou({_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 Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:dr(this.annotations,e,t)})},annotateContext(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:wr(this.annotations,e)})}},Ou=(e)=>{function t(){}return Object.setPrototypeOf(t,P8e),Object.assign(t,e),t.key=`@effect/rpc/Rpc/${e._tag}`,t},Wo=(e,t)=>{let r=t?.success??qE,n=t?.error??Af,o;if(t?.primaryKey)o=class extends Oe(`@effect/rpc/Rpc/${e}`)(t.payload){[Dye](){return t.primaryKey(this)}};else o=On(t?.payload)?t?.payload:t?.payload?b(t?.payload):qE;return Ou({_tag:e,payloadSchema:o,successSchema:t?.stream?Oye({success:r,failure:n}):r,errorSchema:t?.stream?Af:n,defectSchema:t?.defect??bt,annotations:Pr(),middlewares:new Set})},Nye=(e)=>Ou({_tag:e._tag,payloadSchema:e,successSchema:e.success,errorSchema:e.failure,defectSchema:bt,annotations:Pr(),middlewares:new Set});var H8e=Symbol.for("@effect/rpc/Rpc/Wrapper"),_ye=(e)=>(H8e in e);var W8e=BigInt(0),Pye=Ht(function*(e,t){let r=t?.spanPrefix??"RpcClient",n=t?.supportsAck??!0,o=t?.disableTracing??!1,s=t?.generateRequestId??(()=>W8e++),i=yield*vn(),a=Ot(i,iE),c=new Map,l=!1;yield*Qs(a,Te(()=>(l=!0,u(PZ(q8e)))));let u=Ht(function*(S){for(let[I,B]of c)if(c.delete(I),B._tag==="Mailbox")yield*B.mailbox.done(S);else B.resume(S)}),p=(S)=>{let I=vye(S.successSchema),B=d(S);return(R,Q)=>{let P=Q?.headers?Kn(Q.headers):oi,F=Q?.context??Pr();if(!I){let V=(G)=>f(S,B,G,S.payloadSchema.make?S.payloadSchema.make(R):R,P,F,Q?.discard??!1);return o?V(void 0):CE(`${r}.${S._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes},V)}let D=A(S,B,S.payloadSchema.make?S.payloadSchema.make(R):R,P,Q?.streamBufferSize??16,F);if(Q?.asMailbox)return D;return Wc(z(D,vse))}},f=(S,I,B,R,Q,P,F)=>mr((D)=>{if(l)return es;let V=s(),G=I({_tag:"Request",id:V,tag:S._tag,payload:R,traceId:B?.traceId,spanId:B?.spanId,sampled:B?.sampled,headers:Ka(D.getFiberRef(Lye),Q)});if(F)return w(G,(v)=>t.onFromClient({message:v,context:P,discard:F}));let le=l0({context:D.currentContext,fiberRefs:D.getFiberRefs(),runtimeFlags:SE.runtimeFlags}),Be,Fe=!1;return Vk(Dt((v)=>{let O={_tag:"Effect",rpc:S,context:P,resume(H){if(Fe=!0,v(H),Be&&!Be.unsafePoll())D.currentScheduler.scheduleTask(()=>{Be.unsafeInterruptAsFork(D.id())},0,Be)}};c.set(V,O),Be=G.pipe(w((H)=>t.onFromClient({message:H,context:P,discard:F})),B?jd(B):X,rs(le)),Be.addObserver((H)=>{if(H._tag==="Failure")return v(H)})}),(v)=>{if(Fe)return Y;c.delete(V);let O=Array.from(v).flatMap((H)=>Array.from(jN(H)));return ve(Xo(Be),g(V,O,P))})}),A=Ht(function*(S,I,B,R,Q,P){if(l)return yield*es;let F=o?void 0:yield*p6(`${r}.${S._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes}),D=HA(aP()),V=s(),G=Ro(D.currentContext,iE);yield*Ik(G,(Be)=>{if(!c.has(V))return Y;return c.delete(V),g(V,vo(Be)?Array.from(Ak(Be.cause)).flatMap((Fe)=>Array.from(jN(Fe))):[],P)});let le=yield*Df(Q);return c.set(V,{_tag:"Mailbox",rpc:S,mailbox:le,scope:G,context:P}),yield*I({_tag:"Request",id:V,tag:S._tag,traceId:F?.traceId,payload:B,spanId:F?.spanId,sampled:F?.sampled,headers:Ka(D.getFiberRef(Lye),R)}).pipe(w((Be)=>t.onFromClient({message:Be,context:P,discard:!1})),F?jd(F):X,rn((Be)=>le.failCause(Be)),gr,Xs(G)),le}),d=(S)=>{let I=[];for(let B of S.middlewares.values()){let R=i.unsafeMap.get(`${B.key}/Client`);if(!R)continue;I.push(R)}return I.length===0?Z:function(B){let R=0;return z(BS({while:()=>R<I.length,body:()=>I[R]({rpc:S,request:B}),step(Q){B=Q,R++}}),()=>B)}},g=(S,I,B)=>Dt((R)=>{let Q=HA(aP()),P=l0({context:Q.currentContext,fiberRefs:Q.getFiberRefs(),runtimeFlags:SE.runtimeFlags});t.onFromClient({message:{_tag:"Interrupt",requestId:S,interruptors:I},context:B,discard:!1}).pipe(nf(1000),rs(P)).addObserver(()=>{R(Y)})}),x=(S)=>{switch(S._tag){case"Chunk":{let I=S.requestId,B=c.get(I);if(!B||B._tag!=="Mailbox")return Y;return B.mailbox.offerAll(S.values).pipe(n?ve(t.onFromClient({message:{_tag:"Ack",requestId:S.requestId},context:B.context,discard:!1})):X,rn((R)=>B.mailbox.done(En(R))))}case"Exit":{let I=S.requestId,B=c.get(I);if(!B)return Y;if(c.delete(I),B._tag==="Effect")return B.resume(S.exit),Y;return B.mailbox.done(UZ(S.exit))}case"Defect":return u(Zg(S.defect));case"ClientEnd":return Y}},y;if(t.flatten){let S=new Map;y=function(B,R,Q){let P=S.get(B);if(!P)P=p(e.requests.get(B)),S.set(B,P);return P(R,Q)}}else{y={};for(let S of e.requests.values()){let I=S._tag.indexOf("."),B=I===-1?void 0:S._tag.slice(0,I);if(B!==void 0&&!(B in y))y[B]={};let R=B!==void 0?y[B]:y,Q=B!==void 0?S._tag.slice(I+1):S._tag;R[Q]=p(S)}}return{client:y,write:x}}),q8e=cg(-503,0);var Lye=Ae("@effect/rpc/RpcClient/currentHeaders",()=>Pi(oi));var Hye=/\+/g,Wye=function(){};Wye.prototype=Object.create(null);function qye(e){let t=new Wye;if(typeof e!=="string")return t;let r=e.length,n="",o="",s=-1,i=-1,a=!1,c=!1,l=!1,u=!1,p=!1,f=0;for(let A=0;A<r+1;A++)if(f=A!==r?e.charCodeAt(A):38,f===38){if(p=i>s,!p)i=A;if(n=e.slice(s+1,i),p||n.length>0){if(l)n=n.replace(Hye," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(p){if(o=e.slice(i+1,A),u)o=o.replace(Hye," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let d=t[n];if(d===void 0)t[n]=o;else if(d.pop)d.push(o);else t[n]=[d,o]}o="",s=A,i=A,a=!1,c=!1,l=!1,u=!1}else if(f===61)if(i<=s)i=A;else c=!0;else if(f===43)if(i>s)u=!0;else l=!0;else if(f===37)if(i>s)c=!0;else a=!0;return t}var V8e=/^https?:\/\/.*?\//,YV=/(\/:[^/()]*?)\?(\/?)/,Jye=(e={})=>new zye(e);class zye{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(YV);if(n&&n.index!==void 0){J8e(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let s=t.replace(YV,"$1$2"),i=t.replace(YV,"$2");this.on(e,s,r),this.on(e,i,r);return}if(this.options.ignoreDuplicateSlashes)t=Gye(t);if(this.options.ignoreTrailingSlash)t=Yye(t);let o=typeof e==="string"?[e]:e;for(let s of o)this._on(s,t,r)}all(e,t){this.on(X8e,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new gB("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new gB(""),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 p=n.slice(o,c);if(!this.options.caseSensitive)p=p.toLowerCase();p=p.split("::").join(":"),p=p.split("%").join("%25"),s=s.createStaticChild(p)}if(l){let p=!1,f=[],A=c+1;for(let d=A;;d++){let g=n.charCodeAt(d),x=g===40,y=g===45||g===46,S=g===47||d===n.length;if(x||y||S){let I=n.slice(A,d);if(i.push(I),p=p||x||y,x){let Q=j8e(n,d),P=n.slice(d,Q+1);f.push($8e(P)),d=Q+1}else f.push("(.*?)");let B=d;for(;d<n.length;d++){let Q=n.charCodeAt(d);if(Q===47)break;if(Q===58)if(n.charCodeAt(d+1)===58)d++;else break}let R=n.slice(B,d);if(R)R=R.split("::").join(":"),R=R.split("%").join("%25"),f.push(K8e(R));if(A=d+1,S||n.charCodeAt(d)===47||d===n.length){let Q=p?"()"+R:R,P=n.slice(c,d);n=n.slice(0,c+1)+Q+n.slice(d),c+=Q.length;let F=p?new RegExp("^"+f.join("")+"$"):void 0;s=s.createParametricChild(F,R,P),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(V8e,"/");if(this.options.ignoreDuplicateSlashes)t=Gye(t);let n,o,s;try{n=Z8e(t),t=n.path,o=n.querystring,s=n.shouldDecodeParam}catch(f){return}if(this.options.ignoreTrailingSlash)t=Yye(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,p=[];while(!0){if(c===u&&r.isLeafNode){let A=r.handlerStorage?.find();if(A!==void 0)return{handler:A.handler,params:A.createParams(l),searchParams:qye(o)}}let f=r.getNextNode(t,c,p,l.length);if(f===void 0){if(p.length===0)return;let A=p.pop();c=A.brotherPathIndex,l.splice(A.paramsCount),f=A.brotherNode}if(r=f,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let A=i.slice(c);if(s)A=Vye(A);l.push(A),c=u;continue}if(r._tag==="ParametricNode"){let A=i.indexOf("/",c);if(A===-1)A=u;let d=i.slice(c,A);if(s)d=Vye(d);if(r.regex!==void 0){let g=r.regex.exec(d);if(g===null)continue;for(let x=1;x<g.length;x++){let y=g[x];if(y.length>a)return;l.push(y)}}else{if(d.length>a)return;l.push(d)}c=A}}}}class jye{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:z8e(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class VV{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 jye;this.isLeafNode=!0,this.handlerStorage.add(e)}}class JV extends VV{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 gB(e),this.staticChildren[r]}}class gB extends JV{_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 $ye(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 Kye;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new gB(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 $ye extends JV{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 Kye extends VV{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var J8e=(e,t)=>{if(!e)throw Error(t)};function Gye(e){return e.replace(/\/\/+/g,"/")}function Yye(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function z8e(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 j8e(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 $8e(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 K8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zye(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 Z8e(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(Zye(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 Vye(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=Zye(s,i);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var X8e=["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 Xye=Jye;var nCe=(e,t)=>{let r=t.definitionPath??"#/$defs/",n=(a)=>r+a,o=t.target??"jsonSchema7",s=t.topLevelReferenceStrategy??"keep",i=t.additionalPropertiesStrategy??"strict";return In(e,t.definitions,"handle-identifier",[],{getRef:n,target:o,topLevelReferenceStrategy:s,additionalPropertiesStrategy:i},"handle-annotation","handle-errors")},EB={$id:"/schemas/never",not:{}},bm={$id:"/schemas/any"},oCe={$id:"/schemas/unknown"},sCe={$id:"/schemas/void"},r6e={$id:"/schemas/object",anyOf:[{type:"object"},{type:"array"}]},n6e={$id:"/schemas/%7B%7D",anyOf:[{type:"object"},{type:"array"}]};function iCe(e){if(e!==void 0)return pt(cf(e))}function aCe(e){if(e!==void 0)return pt(PS(e))}function cCe(e){if(e!==void 0)return D7(e);return T()}function o6e(e,t){return O0(e,!1)(t)}function lCe(e){if(e!==void 0)return pt(k7(e))}function s6e(e,t){let r=O0(e,!1),n=rp(t,(o)=>r(o).pipe(qs(AF)));return n.length>0?n:void 0}function eCe(e,t,r){if(t!==void 0)switch(e._tag){case"StringKeyword":return t!==QE.annotations[r]?t:void 0;case"NumberKeyword":return t!==wE.annotations[r]?t:void 0;case"BooleanKeyword":return t!==RE.annotations[r]?t:void 0}return t}function AF(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)=>AF(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)=>AF(n,t))}finally{t.delete(e)}}return!1}function uCe(e,t,r,n,o){let s={};if(t!==void 0)s.description=t;if(r!==void 0)s.title=r;if(de(n)){let i=o6e(e,n.value);if(de(i)&&AF(i.value))s.default=i.value}if(o!==void 0){let i=s6e(e,o);if(i!==void 0)s.examples=i}if(Object.keys(s).length===0)return;return s}function zV(e,t){return uCe(e,iCe(t),aCe(t),cCe(t),lCe(t))}function pCe(e){return uCe(e,eCe(e,iCe(e),Wi),eCe(e,aCe(e),Eo),cCe(e),lCe(e))}function jV(e,t){if(t){if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}return e}var dF=(e)=>{if($e(MH(e)))return zH(e,dF,(t)=>dF(t.from))},i6e=(e)=>e.annotations[th]===y0,a6e=(e,t)=>{if(Uc(e)){if(e.annotations[th]===d0)return"type"in t&&t.type!=="integer"}return"type"in t||"oneOf"in t||"anyOf"in t||"$ref"in t},c6e=(e,t,r)=>{let n={...e,...pCe(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 l6e(e){switch(e.target){case"jsonSchema7":return!1;case"jsonSchema2019-09":case"jsonSchema2020-12":case"openApi3.1":return!0}}function u6e(e){switch(e.additionalPropertiesStrategy){case"allow":return!0;case"strict":return!1}}function cr(e,t){return fCe(e,pCe(t))}function fCe(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 $V(e){let t=pt(_H(e));if(t===void 0){if(WH(e))return $V(e.f());if(w0(e)&&qS(e.from)&&N7(e.to)){let r=e.to,n=Zl(r);if(de(n))return $V(r)}}return t}function In(e,t,r,n,o,s,i){if(r==="handle-identifier"&&(o.topLevelReferenceStrategy!=="skip"||WH(e))){let c=$V(e);if(c!==void 0){let l=c.replace(/~/ig,"~0").replace(/\//ig,"~1"),u={$ref:o.getRef(l)};if(!nN(t,c))t[c]=u,t[c]=In(e,t,"ignore-identifier",n,o,"handle-annotation",i);return u}}if(s==="handle-annotation"){let c=MH(e);if(de(c)){let l=c.value;if(a6e(e,l))switch(e._tag){case"Declaration":return cr(l,e);default:return l}else switch(e._tag){case"Refinement":{let u=NS(e);if(u===void 0)return c6e(In(e.from,t,r,n,o,"handle-annotation",i),l,e);else return In(u,t,r,n,o,"handle-annotation",i)}default:return{...In(e,t,r,n,o,"ignore-annotation",i),...l}}}}let a=Zl(e);if(de(a))return In(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 cr(bm,e);throw Error(mH(n,e))}case"Suspend":{if(r==="handle-identifier"){if(i==="ignore-errors")return cr(bm,e);throw Error(c7(n,e))}return In(e.f(),t,"ignore-identifier",n,o,"handle-annotation",i)}case"NeverKeyword":return cr(EB,e);case"VoidKeyword":return cr(sCe,e);case"UnknownKeyword":return cr(oCe,e);case"AnyKeyword":return cr(bm,e);case"ObjectKeyword":return cr(r6e,e);case"StringKeyword":return cr({type:"string"},e);case"NumberKeyword":return cr({type:"number"},e);case"BooleanKeyword":return cr({type:"boolean"},e);case"Literal":{let c=e.literal;if(c===null)return cr({type:"null"},e);else if(Gt(c))return cr({type:"string",enum:[c]},e);else if(eo(c))return cr({type:"number",enum:[c]},e);else if(Ps(c))return cr({type:"boolean",enum:[c]},e);if(i==="ignore-errors")return cr(bm,e);throw Error(mH(n,e))}case"Enums":{let c=e.enums.map((l)=>({type:eo(l[1])?"number":"string",title:l[0],enum:[l[1]]}));return c.length>=1?cr({$comment:"/schemas/enums",anyOf:c},e):cr(EB,e)}case"TupleType":{let c=e.elements.map((A,d)=>jV(In(A.type,t,"handle-identifier",n.concat(d),o,"handle-annotation",i),zV(A.type,A))),l=e.rest.map((A)=>jV(In(A.type,t,"handle-identifier",n,o,"handle-annotation",i),zV(A.type,A))),u={type:"array"},p=e.elements.length;if(p>0)if(u.minItems=p-e.elements.filter((A)=>A.isOptional).length,o.target==="jsonSchema7")u.items=c;else u.prefixItems=c;let f=l.length;if(f>0){let A=l[0];if(f===1&&e.elements.every((g)=>g.type===e.rest[0].type))if(o.target==="jsonSchema7")u.items=A;else u.items=A,delete u.prefixItems;else if(o.target==="jsonSchema7")u.additionalItems=A;else u.items=A;if(f>1){if(i==="ignore-errors")return cr(bm,e);throw Error(l7(n))}}else if(p>0)if(o.target==="jsonSchema7")u.additionalItems=!1;else u.items=!1;else u.maxItems=0;return cr(u,e)}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return cr(n6e,e);let c={type:"object",required:[],properties:{},additionalProperties:u6e(o)},l=void 0,u=void 0;for(let p of e.indexSignatures){let f=dF(p.type)??p.type,A=p.parameter;switch(A._tag){case"StringKeyword":{c.additionalProperties=In(f,t,"handle-identifier",n,o,"handle-annotation",i);break}case"TemplateLiteral":{l=In(f,t,"handle-identifier",n,o,"handle-annotation",i),u={type:"string",pattern:vE(A).source};break}case"Refinement":{l=In(f,t,"handle-identifier",n,o,"handle-annotation",i),u=In(A,t,"handle-identifier",n,o,"handle-annotation",i);break}case"SymbolKeyword":{let d=n.concat("[symbol]");c.additionalProperties=In(f,t,"handle-identifier",d,o,"handle-annotation",i),u=In(A,t,"handle-identifier",d,o,"handle-annotation",i);break}}}for(let p=0;p<e.propertySignatures.length;p++){let f=e.propertySignatures[p],A=f.name;if(Gt(A)){let d=dF(f.type),g=d??f.type;if(c.properties[A]=jV(In(g,t,"handle-identifier",n.concat(f.name),o,"handle-annotation",i),zV(g,f)),!f.isOptional&&d===void 0)c.required.push(A)}else{if(i==="ignore-errors")return cr(bm,e);throw Error(u7(A,n))}}if(l!==void 0)delete c.additionalProperties,c.patternProperties={"":l};if(u!==void 0)c.propertyNames=u;return cr(c,e)}case"Union":{let c=e.types.map((u)=>In(u,t,"handle-identifier",n,o,"handle-annotation",i)),l=h6e(c);switch(l.length){case 0:return EB;case 1:return cr(l[0],e);default:return cr({anyOf:l},e)}}case"Refinement":return In(e.from,t,r,n,o,"handle-annotation",i);case"TemplateLiteral":{let c=vE(e);return cr({type:"string",title:String(e),description:"a template literal",pattern:c.source},e)}case"Transformation":{if(i6e(e.from)){let l={type:"string",contentMediaType:"application/json"};if(l6e(o))l.contentSchema=In(e.to,t,r,n,o,"handle-annotation",i);return l}let c=In(e.from,t,r,n,o,"handle-annotation",i);if(e.transformation._tag==="TypeLiteralTransformation"&&tCe(c)){let l=In(e.to,{},"ignore-identifier",n,o,"handle-annotation","ignore-errors");if(tCe(l))for(let u of e.transformation.propertySignatureTransformations){let{to:p,from:f}=u;if(Gt(p)&&Gt(f)){let A=l.properties[p];if(zu(A)){let d=c.properties[f];if(zu(d)){let g={};if(Gt(A.title))g.title=A.title;if(Gt(A.description))g.description=A.description;if(Array.isArray(A.examples))g.examples=A.examples;if(Object.hasOwn(A,"default")&&A.default!==void 0)g.default=A.default;c.properties[f]=fCe(d,g)}}}}}return cr(c,e)}}}function tCe(e){return zu(e)&&e.type==="object"&&zu(e.properties)}function p6e(e){return e===EB||ee(e,"$id")&&e.$id===EB.$id&&Object.keys(e).length===3&&e.title===sh.annotations[Eo]}function f6e(e){return"$id"in e&&e.$id===bm.$id}function A6e(e){return"$id"in e&&e.$id===oCe.$id}function d6e(e){return"$id"in e&&e.$id===sCe.$id}function rCe(e){return ee(e,"enum")&&"type"in e&&Object.keys(e).length===2}function h6e(e){let t=[];for(let r of e){if(p6e(r))continue;if(f6e(r)||A6e(r)||d6e(r))return[r];if(rCe(r)&&t.length>0){let n=t[t.length-1];if(rCe(n)&&n.type===r.type){t[t.length-1]={type:n.type,enum:[...n.enum,...r.enum]};continue}}t.push(r)}return t}var g6e={add(...e){return dA({requests:ACe(...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 dA({requests:t,annotations:fp(r)})},middleware(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.middleware(e));return dA({requests:t,annotations:this.annotations})},toHandlersContext(e){return _e(this,function*(){let t=yield*vn(),r=tn(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 fp(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 dA({requests:t,annotations:this.annotations})},toLayer(e){return RS(this.toHandlersContext(e))},of:X,toLayerHandler(e,t){return RS(_e(this,function*(){let r=yield*vn(),n=tn(t)?yield*t:t,o=new Map,s=this.requests.get(e);return o.set(s.key,{handler:n,context:r}),fp(o)}))},accessHandler(e){return qP((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=_ye(a)?a.value:a;return tn(c)?Jn(c,n):jD(c,n)}})},annotate(e,t){return dA({requests:this.requests,annotations:dr(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsContext(wl(e,t))},annotateContext(e){return dA({requests:this.requests,annotations:wr(this.annotations,e)})},annotateRpcsContext(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.annotateContext(wr(e,n.annotations)));return dA({requests:t,annotations:this.annotations})}},dA=(e)=>Object.assign(function(){},g6e,{requests:e.requests,annotations:e.annotations}),ACe=(...e)=>{let t=new Map;for(let r of e)t.set(r._tag,On(r)?Nye(r):r);return t},dCe=(...e)=>dA({requests:ACe(...e),annotations:Pr()});var x6e=Ie(m,re),hCe=Ie(m,re);class Fu extends b({_meta:U(b({progressToken:U(hCe)}))}){}class hA extends b({_meta:U(Fn({key:m,value:Tt}))}){}class mA extends b({_meta:U(Fn({key:m,value:Tt}))}){}var mCe=m;class y6e extends b({...Fu.fields,cursor:U(mCe)}){}class xB extends b({...hA.fields,nextCursor:U(mCe)}){}var gCe=_("user","assistant");class Bm extends b({audience:U(Re(gCe)),priority:U(re.pipe(q0(0,1)))}){}class KV extends b({name:m,title:U(m),version:m}){}class ECe extends Oe("@effect/ai/McpSchema/ClientCapabilities")({experimental:U(Fn({key:m,value:b({})})),roots:U(b({listChanged:U(ae)})),sampling:U(b({})),elicitation:U(b({}))}){}class xCe extends b({experimental:U(Fn({key:m,value:b({})})),logging:U(b({})),completions:U(b({})),prompts:U(b({listChanged:U(ae)})),resources:U(b({subscribe:U(ae),listChanged:U(ae)})),tools:U(b({listChanged:U(ae)}))}){}class Us extends Oe("@effect/ai/McpSchema/McpError")({code:re,message:m,data:U(Tt)}){}var C6e=-32600,S6e=-32601,I6e=-32602,b6e=-32603,B6e=-32700;class Q6e extends ot()("ParseError",{...Us.fields,code:Yi(B6e)}){}class w6e extends ot()("InvalidRequest",{...Us.fields,code:Yi(C6e)}){}class R6e extends ot()("MethodNotFound",{...Us.fields,code:Yi(S6e)}){}class yB extends ot()("InvalidParams",{...Us.fields,code:Yi(I6e)}){}class my extends ot()("InternalError",{...Us.fields,code:Yi(b6e)}){static notImplemented=new my({message:"Not implemented"})}class yCe extends Oe("@effect/ai/McpSchema/InitializeResult")({...hA.fields,protocolVersion:m,capabilities:xCe,serverInfo:KV,instructions:U(m)}){}class k6e extends Wo("initialize",{success:yCe,error:Us,payload:{...Fu.fields,protocolVersion:m,capabilities:ECe,clientInfo:KV}}){}class CCe extends Wo("notifications/cancelled",{payload:{...mA.fields,requestId:x6e,reason:U(m)}}){}class SCe extends Wo("notifications/progress",{payload:{...mA.fields,progressToken:hCe,progress:U(re),total:U(re),message:U(m)}}){}class CB extends Oe("@effect/ai/McpSchema/Resource")({uri:m,name:m,title:U(m),description:U(m),mimeType:U(m),annotations:U(Bm),size:U(re)}){}class hF extends Oe("@effect/ai/McpSchema/ResourceTemplate")({uriTemplate:m,name:m,title:U(m),description:U(m),mimeType:U(m),annotations:U(Bm)}){}class ZV extends b({uri:m,mimeType:U(m)}){}class XV extends b({...ZV.fields,text:m}){}class eJ extends b({...ZV.fields,blob:V0}){}class ICe extends Oe("@effect/ai/McpSchema/ListResourcesResult")({...xB.fields,resources:Re(CB)}){}class bCe extends Oe("@effect/ai/McpSchema/ListResourceTemplatesResult")({...xB.fields,resourceTemplates:Re(hF)}){}class BCe extends b({...hA.fields,contents:Re(Ie(XV,eJ))}){}class D6e extends Wo("resources/read",{success:BCe,error:Us,payload:{...Fu.fields,uri:m}}){}class QCe extends Wo("notifications/resources/list_changed",{payload:nu(mA)}){}class T6e extends Wo("resources/subscribe",{error:Us,payload:{...Fu.fields,uri:m}}){}class v6e extends Wo("resources/unsubscribe",{error:Us,payload:{...Fu.fields,uri:m}}){}class wCe extends Wo("notifications/resources/updated",{payload:{...mA.fields,uri:m}}){}class RCe extends b({name:m,title:U(m),description:U(m),required:U(ae)}){}class tJ extends Oe("@effect/ai/McpSchema/Prompt")({name:m,title:U(m),description:U(m),arguments:U(Re(RCe))}){}class rJ extends b({type:Yi("text"),text:m,annotations:U(Bm)}){}class kCe extends b({type:Yi("image"),data:V0,mimeType:m,annotations:U(Bm)}){}class DCe extends b({type:Yi("audio"),data:V0,mimeType:m,annotations:U(Bm)}){}class TCe extends b({type:Yi("resource"),resource:Ie(XV,eJ),annotations:U(Bm)}){}class vCe extends b({...CB.fields,type:Yi("resource_link")}){}class nJ extends Ie(rJ,kCe,DCe,TCe,vCe){}class OCe extends b({role:gCe,content:nJ}){}class FCe extends Oe("@effect/ai/McpSchema/ListPromptsResult")({...xB.fields,prompts:Re(tJ)}){}class oJ extends Oe("@effect/ai/McpSchema/GetPromptResult")({...hA.fields,messages:Re(OCe),description:U(m)}){}class O6e extends Wo("prompts/get",{success:oJ,error:Us,payload:{...Fu.fields,name:m,title:U(m),arguments:U(Fn({key:m,value:m}))}}){}class MCe extends Wo("notifications/prompts/list_changed",{payload:nu(mA)}){}class mF extends Oe("@effect/ai/McpSchema/ToolAnnotations")({title:U(m),readOnlyHint:C(ae,{default:()=>!1}),destructiveHint:C(ae,{default:()=>!0}),idempotentHint:C(ae,{default:()=>!1}),openWorldHint:C(ae,{default:()=>!0})}){}class gF extends Oe("@effect/ai/McpSchema/Tool")({name:m,title:U(m),description:U(m),inputSchema:Tt,annotations:U(mF)}){}class NCe extends Oe("@effect/ai/McpSchema/ListToolsResult")({...xB.fields,tools:Re(gF)}){}class SB extends Oe("@effect/ai/McpSchema/CallToolResult")({...hA.fields,content:Re(nJ),structuredContent:U(Tt),isError:U(ae)}){}class F6e extends Wo("tools/call",{success:SB,error:Us,payload:{...Fu.fields,name:m,arguments:Fn({key:m,value:Tt})}}){}class _Ce extends Wo("notifications/tools/list_changed",{payload:nu(mA)}){}var UCe=_("debug","info","notice","warning","error","critical","alert","emergency");class M6e extends Wo("logging/setLevel",{payload:{...Fu.fields,level:UCe},error:Us}){}class LCe extends Wo("notifications/message",{payload:b({...mA.fields,level:UCe,logger:U(m),data:Tt})}){}class IB extends Oe("@effect/ai/McpSchema/CompleteResult")({completion:b({values:Re(m),total:U(re),hasMore:U(ae)})}){static empty=IB.make({completion:{values:[],total:0,hasMore:!1}})}class PCe extends Oe("@effect/ai/McpSchema/ElicitAcceptResult")({...hA.fields,action:_("accept"),content:Tt}){}class HCe extends Oe("@effect/ai/McpSchema/ElicitDeclineResult")({...hA.fields,action:_("cancel","decline")}){}var N6e=Ie(PCe,HCe);class sJ extends Wo("elicitation/create",{success:N6e,error:Us,payload:{message:m,requestedSchema:Tt}}){}class WCe extends ot("@effect/ai/McpSchema/ElicitationDeclined")("ElicitationDeclined",{request:sJ.payloadSchema,cause:U(bt)}){}class iJ extends dCe(CCe,SCe,LCe,wCe,QCe,_Ce,MCe){}var qCe=Symbol.for("@effect/ai/McpSchema/ParamNameId");var _6e="~@effect/ai/Tool",GCe="~@effect/ai/Tool/ProviderDefined";var YCe={[_6e]:{_Requirements:X},pipe(){return W(this,arguments)},addDependency(){return gA({...this})},setParameters(e){return gA({...this,parametersSchema:On(e)?e:b(e)})},setSuccess(e){return gA({...this,successSchema:e})},setFailure(e){return gA({...this,failureSchema:e})},annotate(e,t){return gA({...this,annotations:dr(this.annotations,e,t)})},annotateContext(e){return gA({...this,annotations:wr(this.annotations,e)})}},SLt={...YCe,[GCe]:GCe},gA=(e)=>{let t=Object.assign(Object.create(YCe),e);return t.id=`@effect/ai/Tool/${e.name}`,t};var U6e=b({}),aJ=(e,t)=>{let r=t?.success??qE,n=t?.failure??Af;return gA({name:e,description:t?.description,parametersSchema:t?.parameters?b(t?.parameters):U6e,successSchema:r,failureSchema:n,failureMode:t?.failureMode??"error",annotations:Pr()})};var VCe=(e)=>gA({name:e._tag,description:pt(cf(e.ast.to)),parametersSchema:e,successSchema:e.success,failureSchema:e.failure,failureMode:"error",annotations:Pr()});class cJ extends wi("@effect/ai/Tool/Title")(){}class gy extends hr()("@effect/ai/Tool/Readonly",{defaultValue:tr}){}class Ey extends hr()("@effect/ai/Tool/Destructive",{defaultValue:Io}){}class lJ extends hr()("@effect/ai/Tool/Idempotent",{defaultValue:tr}){}class uJ extends hr()("@effect/ai/Tool/OpenWorld",{defaultValue:Io}){}class Al extends wi("@effect/ai/McpServer")(){static make=_e(function*(){let e=H6e(),t=dn(),r=new Map,n=[],o=[],s=[],i=new Map,a=new Map,c=yield*Df(),l=new Map,u=yield*Pye(iJ,{spanPrefix:"McpServer/Notifications",onFromClient(p){let f=p.message;if(f._tag!=="Request")return Y;if(f.tag.includes("list_changed")){if(!l.has(f.tag))l.set(f.tag,setTimeout(()=>{c.unsafeOffer(f),l.delete(f.tag)},0))}else c.unsafeOffer(f);return u.write({clientId:0,requestId:f.id,_tag:"Exit",exit:Fi})}});return Al.of({notifications:u.client,notificationsMailbox:c,initializedClients:new Set,get tools(){return t},addTool:(p)=>Te(()=>(t.push(p.tool),r.set(p.tool.name,p.handle),u.client["notifications/tools/list_changed"]({}))),callTool:(p)=>Te(()=>{let f=r.get(p.name);if(!f)return ce(new yB({message:`Tool '${p.name}' not found`}));return f(p.arguments)}),get resources(){return n},get resourceTemplates(){return o},addResource:(p,f)=>Te(()=>(n.push(p),e.add(p.uri,{_tag:"Resource",effect:f}),u.client["notifications/resources/list_changed"]({}))),addResourceTemplate:({completions:p,handle:f,routerPath:A,template:d})=>Te(()=>{o.push(d),e.add(A,{_tag:"ResourceTemplate",handle:f});for(let[g,x]of Object.entries(p))a.set(`ref/resource/${d.uriTemplate}/${g}`,x);return u.client["notifications/resources/list_changed"]({})}),findResource:(p)=>Te(()=>{let f=e.find(p);if(!f)return Z({contents:[]});else if(f.handler._tag==="Resource")return f.handler.effect;let A=[];for(let d of Object.keys(f.params))A[Number(d)]=f.params[d];return f.handler.handle(p,A)}),get prompts(){return s},addPrompt:(p)=>Te(()=>{s.push(p.prompt),i.set(p.prompt.name,p.handle);for(let[f,A]of Object.entries(p.completions))a.set(`ref/prompt/${p.prompt.name}/${f}`,A);return u.client["notifications/prompts/list_changed"]({})}),getPromptResult:Ht(function*({arguments:p,name:f}){let A=i.get(f);if(!A)return yield*new yB({message:`Prompt '${f}' not found`});return yield*A(p??{})}),completion:Ht(function*(p){let f=p.ref,A=f.type==="ref/resource"?`ref/resource/${f.uri}/${p.argument.name}`:`ref/prompt/${f.name}/${p.argument.name}`,d=a.get(A);return d?yield*d(p.argument.value):IB.empty})})});static layer=Oc(Al,Al.make)}var L6e=Ht(function*(e){let t=yield*Al,r=yield*e,n=yield*vn();for(let o of Object.values(r.tools)){let s=new gF({name:o.name,description:o.description,inputSchema:q6e(o.parametersSchema.ast),annotations:new mF({...Jo(o.annotations,cJ).pipe(jt((i)=>({title:i})),pt),readOnlyHint:Ot(o.annotations,gy),destructiveHint:Ot(o.annotations,Ey),idempotentHint:Ot(o.annotations,lJ),openWorldHint:Ot(o.annotations,uJ)})});yield*t.addTool({tool:s,handle(i){return r.handle(o.name,i).pipe(Jn(n),Xk({onFailure:(a)=>new SB({isError:!0,structuredContent:typeof a==="object"?a:void 0,content:[{type:"text",text:JSON.stringify(a)}]}),onSuccess:(a)=>new SB({isError:!1,structuredContent:typeof a.encodedResult==="object"?a.encodedResult:void 0,content:[{type:"text",text:JSON.stringify(a.encodedResult)}]})}))}})}}),P6e=(e)=>r0(L6e(e)).pipe(no(Al.layer)),JCe=function(){if(arguments.length===1){let o=arguments[0];return _e(function*(){let s=yield*vn();yield*(yield*Al).addResource(new CB({...o,annotations:o}),o.content.pipe(Jn(s),z((a)=>zCe(o.uri,a)),rn((a)=>{let c=gk(a)[0];return new my({message:c.message})})))})}let{params:e,routerPath:t,schema:r,uriPath:n}=W6e(...arguments);return Ht(function*(o){let s=yield*vn(),i=yield*Al,a=is(r),c=new hF({...o,uriTemplate:n,annotations:o}),l={};for(let[u,p]of Object.entries(o.completion??{})){let f=hh(Re(e[u])),A=(d)=>p(d).pipe(w(f),z((g)=>new IB({completion:{values:g,total:g.length,hasMore:!1}})),rn((g)=>{let x=gk(g)[0];return new my({message:x.message})}),Jn(s));l[u]=A}yield*i.addResourceTemplate({template:c,routerPath:t,completions:l,handle:(u,p)=>a(p).pipe(De((f)=>new yB({message:f.message})),w((f)=>o.content(u,...f).pipe(z((A)=>zCe(u,A)),rn((A)=>{let d=gk(A)[0];return new my({message:d.message})}))),Jn(s))})})},jCe=function(){if(arguments.length===1)return r0(JCe(arguments[0])).pipe(no(Al.layer));let e=JCe(...arguments);return(t)=>r0(e(t)).pipe(no(Al.layer))};var H6e=()=>{let e=Xye({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(n,o)=>{e.on("GET",n,o)},find:(n)=>e.find("GET",n)}},W6e=(e,...t)=>{let r=e[0].replace(":","::"),n=e[0],o={},s=oI();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 p=yn(qCe)(c.ast).pipe(je(()=>`param${u}`));o[p]=c,n+=`{${p}}${l}`}s=oI(...i)}return{routerPath:r,uriPath:n,schema:s,params:o}};var q6e=(e)=>{if(MS(e).length===0)return{type:"object",properties:{},required:[],additionalProperties:!1};let r={},n=nCe(e,{definitions:r,topLevelReferenceStrategy:"skip"});if(Object.keys(r).length===0)return n;return n.$defs=r,n},zCe=(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 EF="~@effect/ai/AiError";class xF extends ot("@effect/ai/AiError/MalformedInput")("MalformedInput",{module:m,method:m,description:U(m),cause:U(bt)}){[EF]=EF}class BB extends ot("@effect/ai/AiError/MalformedOutput")("MalformedOutput",{module:m,method:m,description:U(m),cause:U(bt)}){[EF]=EF;static fromParseError({error:e,...t}){return new BB({...t,cause:e})}}var Y6e={...Pg,...Ws,of:X,toContext(e){return _e(this,function*(){let t=yield*vn(),r=tn(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 fp(n)})},toLayer(e){return RS(this.toContext(e))},commit(){return _e(this,function*(){let e=this.tools,t=yield*vn(),r=new WeakMap,n=(s)=>{let i=r.get(s);if(Wy(i)){let a=t.unsafeMap.get(s.id),c=is(s.parametersSchema),l=Ie(s.successSchema,s.failureSchema),u=Uee(l),p=hh(l);i={context:a.context,handler:a.handler,decodeParameters:c,validateResult:u,encodeResult:p},r.set(s,i)}return i},o=we("Toolkit.handle",{captureStackTrace:!1})(function*(s,i){yield*u6({tool:s,parameters:i});let a=e[s];if(Wy(a)){let A=Object.keys(e).join(",");return yield*new BB({module:"Toolkit",method:`${s}.handle`,description:`Failed to find tool with name '${s}' in toolkit - available tools: ${A}`})}let c=n(a),l=yield*De(c.decodeParameters(i),(A)=>new BB({module:"Toolkit",method:`${s}.handle`,description:`Failed to decode tool call parameters for tool '${s}' from:
|
|
183
|
+
`)});class M8e extends vc()("@expandai/cli/Install/ConfigIo",{dependencies:[Dh,hB],effect:_e(function*(){let e=yield*Cn,t=yield*Jr,r=we("ConfigIo.read")(function*(a,c){let l=yield*F8e(a).pipe(nn(Cn,e));return yield*P0(c)(l)}),n=we("ConfigIo.write")(function*(a,c,l){let u=yield*hh(l)(c);yield*wye(a,u).pipe(nn(Cn,e),nn(Jr,t))}),o=we("ConfigIo.exists")(function*(a){return yield*e.exists(a)}),s=we("ConfigIo.readText")(function*(a){return(yield*e.exists(a))?yield*e.readFileString(a):""}),i=we("ConfigIo.writeText")(function*(a,c){yield*wye(a,c).pipe(nn(Cn,e),nn(Jr,t))});return{read:r,write:n,exists:o,readText:s,writeText:i}})}){}class N8e extends vc()("@expandai/cli/Install/SkillIo",{dependencies:[Dh,hB],effect:_e(function*(){let e=yield*Cn,t=yield*Jr,r=yield*t.fromFileUrl(Bye),n=we("SkillIo.install")(function*(a){return yield*e.makeDirectory(t.dirname(a),{recursive:!0}),yield*e.copy(r,a,{overwrite:!0}),a}),o=we("SkillIo.uninstall")(function*(a){if(yield*e.exists(a))yield*e.remove(a,{recursive:!0});return a}),s=we("SkillIo.isCurrent")(function*(a){let c=t.join(a,"SKILL.md");if(!(yield*e.exists(c)))return!1;let[l,u]=yield*wc([e.readFileString(c),e.readFileString(t.join(r,"SKILL.md"))]);return l===u}),i=we("SkillIo.isInstalled")(function*(a){return yield*e.exists(t.join(a,"SKILL.md"))});return{install:n,uninstall:o,isCurrent:s,isInstalled:i}})}){}var mB="0.1.6";var Dye=Symbol.for("effect/PrimaryKey");var GV=Symbol.for("@effect/rpc/RpcSchema/Stream"),vye=(e)=>e.ast.annotations[th]===GV;var Oye=({failure:e,success:t})=>Object.assign(ni([t,e],{decode:(r,n)=>Tye(Lc(S2(r)),Lc(n)),encode:(r,n)=>Tye(Pc(S2(r)),Pc(n))},{schemaId:GV,[GV]:{success:t,failure:e}}),{success:t,failure:e}),U8e=(e)=>ee(e,B1),Tye=(e,t)=>(r,n,o)=>w(vn(),(s)=>{if(!U8e(r))return ce(new Fr(o,r));return Z(r.pipe(Cne((i)=>e(i,n)),Q1((i)=>{if(NE(i))return hne(i);return of(t(i,n),{onFailure:Mo,onSuccess:ce})}),jD(s)))});var Mye=Symbol.for("@effect/rpc/Rpc");var P8e={[Mye]:Mye,pipe(){return W(this,arguments)},setSuccess(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:e,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setError(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:e,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},setPayload(e){return Ou({_tag:this._tag,payloadSchema:On(e)?e:b(e),successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,annotations:this.annotations,middlewares:this.middlewares})},middleware(e){return Ou({_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 Ou({_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 Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:dr(this.annotations,e,t)})},annotateContext(e){return Ou({_tag:this._tag,payloadSchema:this.payloadSchema,successSchema:this.successSchema,errorSchema:this.errorSchema,defectSchema:this.defectSchema,middlewares:this.middlewares,annotations:wr(this.annotations,e)})}},Ou=(e)=>{function t(){}return Object.setPrototypeOf(t,P8e),Object.assign(t,e),t.key=`@effect/rpc/Rpc/${e._tag}`,t},Wo=(e,t)=>{let r=t?.success??qE,n=t?.error??Af,o;if(t?.primaryKey)o=class extends Oe(`@effect/rpc/Rpc/${e}`)(t.payload){[Dye](){return t.primaryKey(this)}};else o=On(t?.payload)?t?.payload:t?.payload?b(t?.payload):qE;return Ou({_tag:e,payloadSchema:o,successSchema:t?.stream?Oye({success:r,failure:n}):r,errorSchema:t?.stream?Af:n,defectSchema:t?.defect??bt,annotations:Pr(),middlewares:new Set})},Nye=(e)=>Ou({_tag:e._tag,payloadSchema:e,successSchema:e.success,errorSchema:e.failure,defectSchema:bt,annotations:Pr(),middlewares:new Set});var H8e=Symbol.for("@effect/rpc/Rpc/Wrapper"),_ye=(e)=>(H8e in e);var W8e=BigInt(0),Pye=Ht(function*(e,t){let r=t?.spanPrefix??"RpcClient",n=t?.supportsAck??!0,o=t?.disableTracing??!1,s=t?.generateRequestId??(()=>W8e++),i=yield*vn(),a=Ot(i,iE),c=new Map,l=!1;yield*Qs(a,Te(()=>(l=!0,u(PZ(q8e)))));let u=Ht(function*(S){for(let[I,B]of c)if(c.delete(I),B._tag==="Mailbox")yield*B.mailbox.done(S);else B.resume(S)}),p=(S)=>{let I=vye(S.successSchema),B=d(S);return(R,Q)=>{let P=Q?.headers?Kn(Q.headers):oi,F=Q?.context??Pr();if(!I){let V=(G)=>f(S,B,G,S.payloadSchema.make?S.payloadSchema.make(R):R,P,F,Q?.discard??!1);return o?V(void 0):CE(`${r}.${S._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes},V)}let D=A(S,B,S.payloadSchema.make?S.payloadSchema.make(R):R,P,Q?.streamBufferSize??16,F);if(Q?.asMailbox)return D;return Wc(z(D,vse))}},f=(S,I,B,R,Q,P,F)=>mr((D)=>{if(l)return es;let V=s(),G=I({_tag:"Request",id:V,tag:S._tag,payload:R,traceId:B?.traceId,spanId:B?.spanId,sampled:B?.sampled,headers:Ka(D.getFiberRef(Lye),Q)});if(F)return w(G,(v)=>t.onFromClient({message:v,context:P,discard:F}));let le=l0({context:D.currentContext,fiberRefs:D.getFiberRefs(),runtimeFlags:SE.runtimeFlags}),Be,Fe=!1;return Vk(Dt((v)=>{let O={_tag:"Effect",rpc:S,context:P,resume(H){if(Fe=!0,v(H),Be&&!Be.unsafePoll())D.currentScheduler.scheduleTask(()=>{Be.unsafeInterruptAsFork(D.id())},0,Be)}};c.set(V,O),Be=G.pipe(w((H)=>t.onFromClient({message:H,context:P,discard:F})),B?jd(B):X,rs(le)),Be.addObserver((H)=>{if(H._tag==="Failure")return v(H)})}),(v)=>{if(Fe)return Y;c.delete(V);let O=Array.from(v).flatMap((H)=>Array.from(jN(H)));return ve(Xo(Be),g(V,O,P))})}),A=Ht(function*(S,I,B,R,Q,P){if(l)return yield*es;let F=o?void 0:yield*p6(`${r}.${S._tag}`,{captureStackTrace:!1,attributes:t.spanAttributes}),D=HA(aP()),V=s(),G=Ro(D.currentContext,iE);yield*Ik(G,(Be)=>{if(!c.has(V))return Y;return c.delete(V),g(V,vo(Be)?Array.from(Ak(Be.cause)).flatMap((Fe)=>Array.from(jN(Fe))):[],P)});let le=yield*Df(Q);return c.set(V,{_tag:"Mailbox",rpc:S,mailbox:le,scope:G,context:P}),yield*I({_tag:"Request",id:V,tag:S._tag,traceId:F?.traceId,payload:B,spanId:F?.spanId,sampled:F?.sampled,headers:Ka(D.getFiberRef(Lye),R)}).pipe(w((Be)=>t.onFromClient({message:Be,context:P,discard:!1})),F?jd(F):X,rn((Be)=>le.failCause(Be)),gr,Xs(G)),le}),d=(S)=>{let I=[];for(let B of S.middlewares.values()){let R=i.unsafeMap.get(`${B.key}/Client`);if(!R)continue;I.push(R)}return I.length===0?Z:function(B){let R=0;return z(BS({while:()=>R<I.length,body:()=>I[R]({rpc:S,request:B}),step(Q){B=Q,R++}}),()=>B)}},g=(S,I,B)=>Dt((R)=>{let Q=HA(aP()),P=l0({context:Q.currentContext,fiberRefs:Q.getFiberRefs(),runtimeFlags:SE.runtimeFlags});t.onFromClient({message:{_tag:"Interrupt",requestId:S,interruptors:I},context:B,discard:!1}).pipe(nf(1000),rs(P)).addObserver(()=>{R(Y)})}),x=(S)=>{switch(S._tag){case"Chunk":{let I=S.requestId,B=c.get(I);if(!B||B._tag!=="Mailbox")return Y;return B.mailbox.offerAll(S.values).pipe(n?ve(t.onFromClient({message:{_tag:"Ack",requestId:S.requestId},context:B.context,discard:!1})):X,rn((R)=>B.mailbox.done(En(R))))}case"Exit":{let I=S.requestId,B=c.get(I);if(!B)return Y;if(c.delete(I),B._tag==="Effect")return B.resume(S.exit),Y;return B.mailbox.done(UZ(S.exit))}case"Defect":return u(Zg(S.defect));case"ClientEnd":return Y}},y;if(t.flatten){let S=new Map;y=function(B,R,Q){let P=S.get(B);if(!P)P=p(e.requests.get(B)),S.set(B,P);return P(R,Q)}}else{y={};for(let S of e.requests.values()){let I=S._tag.indexOf("."),B=I===-1?void 0:S._tag.slice(0,I);if(B!==void 0&&!(B in y))y[B]={};let R=B!==void 0?y[B]:y,Q=B!==void 0?S._tag.slice(I+1):S._tag;R[Q]=p(S)}}return{client:y,write:x}}),q8e=cg(-503,0);var Lye=Ae("@effect/rpc/RpcClient/currentHeaders",()=>Pi(oi));var Hye=/\+/g,Wye=function(){};Wye.prototype=Object.create(null);function qye(e){let t=new Wye;if(typeof e!=="string")return t;let r=e.length,n="",o="",s=-1,i=-1,a=!1,c=!1,l=!1,u=!1,p=!1,f=0;for(let A=0;A<r+1;A++)if(f=A!==r?e.charCodeAt(A):38,f===38){if(p=i>s,!p)i=A;if(n=e.slice(s+1,i),p||n.length>0){if(l)n=n.replace(Hye," ");if(a)try{n=decodeURIComponent(n)||n}catch{}if(p){if(o=e.slice(i+1,A),u)o=o.replace(Hye," ");if(c)try{o=decodeURIComponent(o)||o}catch{}}let d=t[n];if(d===void 0)t[n]=o;else if(d.pop)d.push(o);else t[n]=[d,o]}o="",s=A,i=A,a=!1,c=!1,l=!1,u=!1}else if(f===61)if(i<=s)i=A;else c=!0;else if(f===43)if(i>s)u=!0;else l=!0;else if(f===37)if(i>s)c=!0;else a=!0;return t}var V8e=/^https?:\/\/.*?\//,YV=/(\/:[^/()]*?)\?(\/?)/,Jye=(e={})=>new zye(e);class zye{constructor(e={}){this.options={ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!1,maxParamLength:100,...e}}options;routes=[];trees={};on(e,t,r){let n=t.match(YV);if(n&&n.index!==void 0){J8e(t.length===n.index+n[0].length,"Optional Parameter needs to be the last parameter of the path");let s=t.replace(YV,"$1$2"),i=t.replace(YV,"$2");this.on(e,s,r),this.on(e,i,r);return}if(this.options.ignoreDuplicateSlashes)t=Gye(t);if(this.options.ignoreTrailingSlash)t=Yye(t);let o=typeof e==="string"?[e]:e;for(let s of o)this._on(s,t,r)}all(e,t){this.on(X8e,e,t)}_on(e,t,r){if(this.trees[e]===void 0)this.trees[e]=new gB("/");let n=t;if(n==="*"&&this.trees[e].prefix.length!==0){let c=this.trees[e];this.trees[e]=new gB(""),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 p=n.slice(o,c);if(!this.options.caseSensitive)p=p.toLowerCase();p=p.split("::").join(":"),p=p.split("%").join("%25"),s=s.createStaticChild(p)}if(l){let p=!1,f=[],A=c+1;for(let d=A;;d++){let g=n.charCodeAt(d),x=g===40,y=g===45||g===46,S=g===47||d===n.length;if(x||y||S){let I=n.slice(A,d);if(i.push(I),p=p||x||y,x){let Q=j8e(n,d),P=n.slice(d,Q+1);f.push($8e(P)),d=Q+1}else f.push("(.*?)");let B=d;for(;d<n.length;d++){let Q=n.charCodeAt(d);if(Q===47)break;if(Q===58)if(n.charCodeAt(d+1)===58)d++;else break}let R=n.slice(B,d);if(R)R=R.split("::").join(":"),R=R.split("%").join("%25"),f.push(K8e(R));if(A=d+1,S||n.charCodeAt(d)===47||d===n.length){let Q=p?"()"+R:R,P=n.slice(c,d);n=n.slice(0,c+1)+Q+n.slice(d),c+=Q.length;let F=p?new RegExp("^"+f.join("")+"$"):void 0;s=s.createParametricChild(F,R,P),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(V8e,"/");if(this.options.ignoreDuplicateSlashes)t=Gye(t);let n,o,s;try{n=Z8e(t),t=n.path,o=n.querystring,s=n.shouldDecodeParam}catch(f){return}if(this.options.ignoreTrailingSlash)t=Yye(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,p=[];while(!0){if(c===u&&r.isLeafNode){let A=r.handlerStorage?.find();if(A!==void 0)return{handler:A.handler,params:A.createParams(l),searchParams:qye(o)}}let f=r.getNextNode(t,c,p,l.length);if(f===void 0){if(p.length===0)return;let A=p.pop();c=A.brotherPathIndex,l.splice(A.paramsCount),f=A.brotherNode}if(r=f,r._tag==="StaticNode"){c+=r.prefix.length;continue}if(r._tag==="WildcardNode"){let A=i.slice(c);if(s)A=Vye(A);l.push(A),c=u;continue}if(r._tag==="ParametricNode"){let A=i.indexOf("/",c);if(A===-1)A=u;let d=i.slice(c,A);if(s)d=Vye(d);if(r.regex!==void 0){let g=r.regex.exec(d);if(g===null)continue;for(let x=1;x<g.length;x++){let y=g[x];if(y.length>a)return;l.push(y)}}else{if(d.length>a)return;l.push(d)}c=A}}}}class jye{handlers=[];unconstrainedHandler;find(){return this.unconstrainedHandler}add(e){let t={params:e.params,handler:e.handler,createParams:z8e(e.params)};this.handlers.push(t),this.unconstrainedHandler=this.handlers[0]}}class VV{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 jye;this.isLeafNode=!0,this.handlerStorage.add(e)}}class JV extends VV{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 gB(e),this.staticChildren[r]}}class gB extends JV{_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 $ye(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 Kye;return this.wildcardChild}split(e,t){let r=this.prefix.slice(0,t),n=this.prefix.slice(t);this.setPrefix(n);let o=new gB(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 $ye extends JV{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 Kye extends VV{_tag="WildcardNode";getNextNode(e,t,r,n){return}}var J8e=(e,t)=>{if(!e)throw Error(t)};function Gye(e){return e.replace(/\/\/+/g,"/")}function Yye(e){if(e.length>1&&e.charCodeAt(e.length-1)===47)return e.slice(0,-1);return e}function z8e(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 j8e(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 $8e(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 K8e(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zye(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 Z8e(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(Zye(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 Vye(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=Zye(s,i);r+=e.slice(n,o)+a,n=o+3}return e.slice(0,t)+r+e.slice(n)}var X8e=["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 Xye=Jye;var nCe=(e,t)=>{let r=t.definitionPath??"#/$defs/",n=(a)=>r+a,o=t.target??"jsonSchema7",s=t.topLevelReferenceStrategy??"keep",i=t.additionalPropertiesStrategy??"strict";return In(e,t.definitions,"handle-identifier",[],{getRef:n,target:o,topLevelReferenceStrategy:s,additionalPropertiesStrategy:i},"handle-annotation","handle-errors")},EB={$id:"/schemas/never",not:{}},bm={$id:"/schemas/any"},oCe={$id:"/schemas/unknown"},sCe={$id:"/schemas/void"},r6e={$id:"/schemas/object",anyOf:[{type:"object"},{type:"array"}]},n6e={$id:"/schemas/%7B%7D",anyOf:[{type:"object"},{type:"array"}]};function iCe(e){if(e!==void 0)return pt(cf(e))}function aCe(e){if(e!==void 0)return pt(PS(e))}function cCe(e){if(e!==void 0)return D7(e);return T()}function o6e(e,t){return O0(e,!1)(t)}function lCe(e){if(e!==void 0)return pt(k7(e))}function s6e(e,t){let r=O0(e,!1),n=rp(t,(o)=>r(o).pipe(qs(AF)));return n.length>0?n:void 0}function eCe(e,t,r){if(t!==void 0)switch(e._tag){case"StringKeyword":return t!==QE.annotations[r]?t:void 0;case"NumberKeyword":return t!==wE.annotations[r]?t:void 0;case"BooleanKeyword":return t!==RE.annotations[r]?t:void 0}return t}function AF(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)=>AF(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)=>AF(n,t))}finally{t.delete(e)}}return!1}function uCe(e,t,r,n,o){let s={};if(t!==void 0)s.description=t;if(r!==void 0)s.title=r;if(de(n)){let i=o6e(e,n.value);if(de(i)&&AF(i.value))s.default=i.value}if(o!==void 0){let i=s6e(e,o);if(i!==void 0)s.examples=i}if(Object.keys(s).length===0)return;return s}function zV(e,t){return uCe(e,iCe(t),aCe(t),cCe(t),lCe(t))}function pCe(e){return uCe(e,eCe(e,iCe(e),Wi),eCe(e,aCe(e),Eo),cCe(e),lCe(e))}function jV(e,t){if(t){if("$ref"in e)return{allOf:[e],...t};return{...e,...t}}return e}var dF=(e)=>{if($e(MH(e)))return zH(e,dF,(t)=>dF(t.from))},i6e=(e)=>e.annotations[th]===y0,a6e=(e,t)=>{if(Uc(e)){if(e.annotations[th]===d0)return"type"in t&&t.type!=="integer"}return"type"in t||"oneOf"in t||"anyOf"in t||"$ref"in t},c6e=(e,t,r)=>{let n={...e,...pCe(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 l6e(e){switch(e.target){case"jsonSchema7":return!1;case"jsonSchema2019-09":case"jsonSchema2020-12":case"openApi3.1":return!0}}function u6e(e){switch(e.additionalPropertiesStrategy){case"allow":return!0;case"strict":return!1}}function cr(e,t){return fCe(e,pCe(t))}function fCe(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 $V(e){let t=pt(_H(e));if(t===void 0){if(WH(e))return $V(e.f());if(w0(e)&&qS(e.from)&&N7(e.to)){let r=e.to,n=Zl(r);if(de(n))return $V(r)}}return t}function In(e,t,r,n,o,s,i){if(r==="handle-identifier"&&(o.topLevelReferenceStrategy!=="skip"||WH(e))){let c=$V(e);if(c!==void 0){let l=c.replace(/~/ig,"~0").replace(/\//ig,"~1"),u={$ref:o.getRef(l)};if(!nN(t,c))t[c]=u,t[c]=In(e,t,"ignore-identifier",n,o,"handle-annotation",i);return u}}if(s==="handle-annotation"){let c=MH(e);if(de(c)){let l=c.value;if(a6e(e,l))switch(e._tag){case"Declaration":return cr(l,e);default:return l}else switch(e._tag){case"Refinement":{let u=NS(e);if(u===void 0)return c6e(In(e.from,t,r,n,o,"handle-annotation",i),l,e);else return In(u,t,r,n,o,"handle-annotation",i)}default:return{...In(e,t,r,n,o,"ignore-annotation",i),...l}}}}let a=Zl(e);if(de(a))return In(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 cr(bm,e);throw Error(mH(n,e))}case"Suspend":{if(r==="handle-identifier"){if(i==="ignore-errors")return cr(bm,e);throw Error(c7(n,e))}return In(e.f(),t,"ignore-identifier",n,o,"handle-annotation",i)}case"NeverKeyword":return cr(EB,e);case"VoidKeyword":return cr(sCe,e);case"UnknownKeyword":return cr(oCe,e);case"AnyKeyword":return cr(bm,e);case"ObjectKeyword":return cr(r6e,e);case"StringKeyword":return cr({type:"string"},e);case"NumberKeyword":return cr({type:"number"},e);case"BooleanKeyword":return cr({type:"boolean"},e);case"Literal":{let c=e.literal;if(c===null)return cr({type:"null"},e);else if(Gt(c))return cr({type:"string",enum:[c]},e);else if(eo(c))return cr({type:"number",enum:[c]},e);else if(Ps(c))return cr({type:"boolean",enum:[c]},e);if(i==="ignore-errors")return cr(bm,e);throw Error(mH(n,e))}case"Enums":{let c=e.enums.map((l)=>({type:eo(l[1])?"number":"string",title:l[0],enum:[l[1]]}));return c.length>=1?cr({$comment:"/schemas/enums",anyOf:c},e):cr(EB,e)}case"TupleType":{let c=e.elements.map((A,d)=>jV(In(A.type,t,"handle-identifier",n.concat(d),o,"handle-annotation",i),zV(A.type,A))),l=e.rest.map((A)=>jV(In(A.type,t,"handle-identifier",n,o,"handle-annotation",i),zV(A.type,A))),u={type:"array"},p=e.elements.length;if(p>0)if(u.minItems=p-e.elements.filter((A)=>A.isOptional).length,o.target==="jsonSchema7")u.items=c;else u.prefixItems=c;let f=l.length;if(f>0){let A=l[0];if(f===1&&e.elements.every((g)=>g.type===e.rest[0].type))if(o.target==="jsonSchema7")u.items=A;else u.items=A,delete u.prefixItems;else if(o.target==="jsonSchema7")u.additionalItems=A;else u.items=A;if(f>1){if(i==="ignore-errors")return cr(bm,e);throw Error(l7(n))}}else if(p>0)if(o.target==="jsonSchema7")u.additionalItems=!1;else u.items=!1;else u.maxItems=0;return cr(u,e)}case"TypeLiteral":{if(e.propertySignatures.length===0&&e.indexSignatures.length===0)return cr(n6e,e);let c={type:"object",required:[],properties:{},additionalProperties:u6e(o)},l=void 0,u=void 0;for(let p of e.indexSignatures){let f=dF(p.type)??p.type,A=p.parameter;switch(A._tag){case"StringKeyword":{c.additionalProperties=In(f,t,"handle-identifier",n,o,"handle-annotation",i);break}case"TemplateLiteral":{l=In(f,t,"handle-identifier",n,o,"handle-annotation",i),u={type:"string",pattern:vE(A).source};break}case"Refinement":{l=In(f,t,"handle-identifier",n,o,"handle-annotation",i),u=In(A,t,"handle-identifier",n,o,"handle-annotation",i);break}case"SymbolKeyword":{let d=n.concat("[symbol]");c.additionalProperties=In(f,t,"handle-identifier",d,o,"handle-annotation",i),u=In(A,t,"handle-identifier",d,o,"handle-annotation",i);break}}}for(let p=0;p<e.propertySignatures.length;p++){let f=e.propertySignatures[p],A=f.name;if(Gt(A)){let d=dF(f.type),g=d??f.type;if(c.properties[A]=jV(In(g,t,"handle-identifier",n.concat(f.name),o,"handle-annotation",i),zV(g,f)),!f.isOptional&&d===void 0)c.required.push(A)}else{if(i==="ignore-errors")return cr(bm,e);throw Error(u7(A,n))}}if(l!==void 0)delete c.additionalProperties,c.patternProperties={"":l};if(u!==void 0)c.propertyNames=u;return cr(c,e)}case"Union":{let c=e.types.map((u)=>In(u,t,"handle-identifier",n,o,"handle-annotation",i)),l=h6e(c);switch(l.length){case 0:return EB;case 1:return cr(l[0],e);default:return cr({anyOf:l},e)}}case"Refinement":return In(e.from,t,r,n,o,"handle-annotation",i);case"TemplateLiteral":{let c=vE(e);return cr({type:"string",title:String(e),description:"a template literal",pattern:c.source},e)}case"Transformation":{if(i6e(e.from)){let l={type:"string",contentMediaType:"application/json"};if(l6e(o))l.contentSchema=In(e.to,t,r,n,o,"handle-annotation",i);return l}let c=In(e.from,t,r,n,o,"handle-annotation",i);if(e.transformation._tag==="TypeLiteralTransformation"&&tCe(c)){let l=In(e.to,{},"ignore-identifier",n,o,"handle-annotation","ignore-errors");if(tCe(l))for(let u of e.transformation.propertySignatureTransformations){let{to:p,from:f}=u;if(Gt(p)&&Gt(f)){let A=l.properties[p];if(zu(A)){let d=c.properties[f];if(zu(d)){let g={};if(Gt(A.title))g.title=A.title;if(Gt(A.description))g.description=A.description;if(Array.isArray(A.examples))g.examples=A.examples;if(Object.hasOwn(A,"default")&&A.default!==void 0)g.default=A.default;c.properties[f]=fCe(d,g)}}}}}return cr(c,e)}}}function tCe(e){return zu(e)&&e.type==="object"&&zu(e.properties)}function p6e(e){return e===EB||ee(e,"$id")&&e.$id===EB.$id&&Object.keys(e).length===3&&e.title===sh.annotations[Eo]}function f6e(e){return"$id"in e&&e.$id===bm.$id}function A6e(e){return"$id"in e&&e.$id===oCe.$id}function d6e(e){return"$id"in e&&e.$id===sCe.$id}function rCe(e){return ee(e,"enum")&&"type"in e&&Object.keys(e).length===2}function h6e(e){let t=[];for(let r of e){if(p6e(r))continue;if(f6e(r)||A6e(r)||d6e(r))return[r];if(rCe(r)&&t.length>0){let n=t[t.length-1];if(rCe(n)&&n.type===r.type){t[t.length-1]={type:n.type,enum:[...n.enum,...r.enum]};continue}}t.push(r)}return t}var g6e={add(...e){return dA({requests:ACe(...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 dA({requests:t,annotations:fp(r)})},middleware(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.middleware(e));return dA({requests:t,annotations:this.annotations})},toHandlersContext(e){return _e(this,function*(){let t=yield*vn(),r=tn(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 fp(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 dA({requests:t,annotations:this.annotations})},toLayer(e){return RS(this.toHandlersContext(e))},of:X,toLayerHandler(e,t){return RS(_e(this,function*(){let r=yield*vn(),n=tn(t)?yield*t:t,o=new Map,s=this.requests.get(e);return o.set(s.key,{handler:n,context:r}),fp(o)}))},accessHandler(e){return qP((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=_ye(a)?a.value:a;return tn(c)?Jn(c,n):jD(c,n)}})},annotate(e,t){return dA({requests:this.requests,annotations:dr(this.annotations,e,t)})},annotateRpcs(e,t){return this.annotateRpcsContext(wl(e,t))},annotateContext(e){return dA({requests:this.requests,annotations:wr(this.annotations,e)})},annotateRpcsContext(e){let t=new Map;for(let[r,n]of this.requests)t.set(r,n.annotateContext(wr(e,n.annotations)));return dA({requests:t,annotations:this.annotations})}},dA=(e)=>Object.assign(function(){},g6e,{requests:e.requests,annotations:e.annotations}),ACe=(...e)=>{let t=new Map;for(let r of e)t.set(r._tag,On(r)?Nye(r):r);return t},dCe=(...e)=>dA({requests:ACe(...e),annotations:Pr()});var x6e=Ie(m,re),hCe=Ie(m,re);class Fu extends b({_meta:U(b({progressToken:U(hCe)}))}){}class hA extends b({_meta:U(Fn({key:m,value:Tt}))}){}class mA extends b({_meta:U(Fn({key:m,value:Tt}))}){}var mCe=m;class y6e extends b({...Fu.fields,cursor:U(mCe)}){}class xB extends b({...hA.fields,nextCursor:U(mCe)}){}var gCe=_("user","assistant");class Bm extends b({audience:U(Re(gCe)),priority:U(re.pipe(q0(0,1)))}){}class KV extends b({name:m,title:U(m),version:m}){}class ECe extends Oe("@effect/ai/McpSchema/ClientCapabilities")({experimental:U(Fn({key:m,value:b({})})),roots:U(b({listChanged:U(ae)})),sampling:U(b({})),elicitation:U(b({}))}){}class xCe extends b({experimental:U(Fn({key:m,value:b({})})),logging:U(b({})),completions:U(b({})),prompts:U(b({listChanged:U(ae)})),resources:U(b({subscribe:U(ae),listChanged:U(ae)})),tools:U(b({listChanged:U(ae)}))}){}class Us extends Oe("@effect/ai/McpSchema/McpError")({code:re,message:m,data:U(Tt)}){}var C6e=-32600,S6e=-32601,I6e=-32602,b6e=-32603,B6e=-32700;class Q6e extends ot()("ParseError",{...Us.fields,code:Yi(B6e)}){}class w6e extends ot()("InvalidRequest",{...Us.fields,code:Yi(C6e)}){}class R6e extends ot()("MethodNotFound",{...Us.fields,code:Yi(S6e)}){}class yB extends ot()("InvalidParams",{...Us.fields,code:Yi(I6e)}){}class my extends ot()("InternalError",{...Us.fields,code:Yi(b6e)}){static notImplemented=new my({message:"Not implemented"})}class yCe extends Oe("@effect/ai/McpSchema/InitializeResult")({...hA.fields,protocolVersion:m,capabilities:xCe,serverInfo:KV,instructions:U(m)}){}class k6e extends Wo("initialize",{success:yCe,error:Us,payload:{...Fu.fields,protocolVersion:m,capabilities:ECe,clientInfo:KV}}){}class CCe extends Wo("notifications/cancelled",{payload:{...mA.fields,requestId:x6e,reason:U(m)}}){}class SCe extends Wo("notifications/progress",{payload:{...mA.fields,progressToken:hCe,progress:U(re),total:U(re),message:U(m)}}){}class CB extends Oe("@effect/ai/McpSchema/Resource")({uri:m,name:m,title:U(m),description:U(m),mimeType:U(m),annotations:U(Bm),size:U(re)}){}class hF extends Oe("@effect/ai/McpSchema/ResourceTemplate")({uriTemplate:m,name:m,title:U(m),description:U(m),mimeType:U(m),annotations:U(Bm)}){}class ZV extends b({uri:m,mimeType:U(m)}){}class XV extends b({...ZV.fields,text:m}){}class eJ extends b({...ZV.fields,blob:V0}){}class ICe extends Oe("@effect/ai/McpSchema/ListResourcesResult")({...xB.fields,resources:Re(CB)}){}class bCe extends Oe("@effect/ai/McpSchema/ListResourceTemplatesResult")({...xB.fields,resourceTemplates:Re(hF)}){}class BCe extends b({...hA.fields,contents:Re(Ie(XV,eJ))}){}class D6e extends Wo("resources/read",{success:BCe,error:Us,payload:{...Fu.fields,uri:m}}){}class QCe extends Wo("notifications/resources/list_changed",{payload:nu(mA)}){}class T6e extends Wo("resources/subscribe",{error:Us,payload:{...Fu.fields,uri:m}}){}class v6e extends Wo("resources/unsubscribe",{error:Us,payload:{...Fu.fields,uri:m}}){}class wCe extends Wo("notifications/resources/updated",{payload:{...mA.fields,uri:m}}){}class RCe extends b({name:m,title:U(m),description:U(m),required:U(ae)}){}class tJ extends Oe("@effect/ai/McpSchema/Prompt")({name:m,title:U(m),description:U(m),arguments:U(Re(RCe))}){}class rJ extends b({type:Yi("text"),text:m,annotations:U(Bm)}){}class kCe extends b({type:Yi("image"),data:V0,mimeType:m,annotations:U(Bm)}){}class DCe extends b({type:Yi("audio"),data:V0,mimeType:m,annotations:U(Bm)}){}class TCe extends b({type:Yi("resource"),resource:Ie(XV,eJ),annotations:U(Bm)}){}class vCe extends b({...CB.fields,type:Yi("resource_link")}){}class nJ extends Ie(rJ,kCe,DCe,TCe,vCe){}class OCe extends b({role:gCe,content:nJ}){}class FCe extends Oe("@effect/ai/McpSchema/ListPromptsResult")({...xB.fields,prompts:Re(tJ)}){}class oJ extends Oe("@effect/ai/McpSchema/GetPromptResult")({...hA.fields,messages:Re(OCe),description:U(m)}){}class O6e extends Wo("prompts/get",{success:oJ,error:Us,payload:{...Fu.fields,name:m,title:U(m),arguments:U(Fn({key:m,value:m}))}}){}class MCe extends Wo("notifications/prompts/list_changed",{payload:nu(mA)}){}class mF extends Oe("@effect/ai/McpSchema/ToolAnnotations")({title:U(m),readOnlyHint:C(ae,{default:()=>!1}),destructiveHint:C(ae,{default:()=>!0}),idempotentHint:C(ae,{default:()=>!1}),openWorldHint:C(ae,{default:()=>!0})}){}class gF extends Oe("@effect/ai/McpSchema/Tool")({name:m,title:U(m),description:U(m),inputSchema:Tt,annotations:U(mF)}){}class NCe extends Oe("@effect/ai/McpSchema/ListToolsResult")({...xB.fields,tools:Re(gF)}){}class SB extends Oe("@effect/ai/McpSchema/CallToolResult")({...hA.fields,content:Re(nJ),structuredContent:U(Tt),isError:U(ae)}){}class F6e extends Wo("tools/call",{success:SB,error:Us,payload:{...Fu.fields,name:m,arguments:Fn({key:m,value:Tt})}}){}class _Ce extends Wo("notifications/tools/list_changed",{payload:nu(mA)}){}var UCe=_("debug","info","notice","warning","error","critical","alert","emergency");class M6e extends Wo("logging/setLevel",{payload:{...Fu.fields,level:UCe},error:Us}){}class LCe extends Wo("notifications/message",{payload:b({...mA.fields,level:UCe,logger:U(m),data:Tt})}){}class IB extends Oe("@effect/ai/McpSchema/CompleteResult")({completion:b({values:Re(m),total:U(re),hasMore:U(ae)})}){static empty=IB.make({completion:{values:[],total:0,hasMore:!1}})}class PCe extends Oe("@effect/ai/McpSchema/ElicitAcceptResult")({...hA.fields,action:_("accept"),content:Tt}){}class HCe extends Oe("@effect/ai/McpSchema/ElicitDeclineResult")({...hA.fields,action:_("cancel","decline")}){}var N6e=Ie(PCe,HCe);class sJ extends Wo("elicitation/create",{success:N6e,error:Us,payload:{message:m,requestedSchema:Tt}}){}class WCe extends ot("@effect/ai/McpSchema/ElicitationDeclined")("ElicitationDeclined",{request:sJ.payloadSchema,cause:U(bt)}){}class iJ extends dCe(CCe,SCe,LCe,wCe,QCe,_Ce,MCe){}var qCe=Symbol.for("@effect/ai/McpSchema/ParamNameId");var _6e="~@effect/ai/Tool",GCe="~@effect/ai/Tool/ProviderDefined";var YCe={[_6e]:{_Requirements:X},pipe(){return W(this,arguments)},addDependency(){return gA({...this})},setParameters(e){return gA({...this,parametersSchema:On(e)?e:b(e)})},setSuccess(e){return gA({...this,successSchema:e})},setFailure(e){return gA({...this,failureSchema:e})},annotate(e,t){return gA({...this,annotations:dr(this.annotations,e,t)})},annotateContext(e){return gA({...this,annotations:wr(this.annotations,e)})}},SLt={...YCe,[GCe]:GCe},gA=(e)=>{let t=Object.assign(Object.create(YCe),e);return t.id=`@effect/ai/Tool/${e.name}`,t};var U6e=b({}),aJ=(e,t)=>{let r=t?.success??qE,n=t?.failure??Af;return gA({name:e,description:t?.description,parametersSchema:t?.parameters?b(t?.parameters):U6e,successSchema:r,failureSchema:n,failureMode:t?.failureMode??"error",annotations:Pr()})};var VCe=(e)=>gA({name:e._tag,description:pt(cf(e.ast.to)),parametersSchema:e,successSchema:e.success,failureSchema:e.failure,failureMode:"error",annotations:Pr()});class cJ extends wi("@effect/ai/Tool/Title")(){}class gy extends hr()("@effect/ai/Tool/Readonly",{defaultValue:tr}){}class Ey extends hr()("@effect/ai/Tool/Destructive",{defaultValue:Io}){}class lJ extends hr()("@effect/ai/Tool/Idempotent",{defaultValue:tr}){}class uJ extends hr()("@effect/ai/Tool/OpenWorld",{defaultValue:Io}){}class Al extends wi("@effect/ai/McpServer")(){static make=_e(function*(){let e=H6e(),t=dn(),r=new Map,n=[],o=[],s=[],i=new Map,a=new Map,c=yield*Df(),l=new Map,u=yield*Pye(iJ,{spanPrefix:"McpServer/Notifications",onFromClient(p){let f=p.message;if(f._tag!=="Request")return Y;if(f.tag.includes("list_changed")){if(!l.has(f.tag))l.set(f.tag,setTimeout(()=>{c.unsafeOffer(f),l.delete(f.tag)},0))}else c.unsafeOffer(f);return u.write({clientId:0,requestId:f.id,_tag:"Exit",exit:Fi})}});return Al.of({notifications:u.client,notificationsMailbox:c,initializedClients:new Set,get tools(){return t},addTool:(p)=>Te(()=>(t.push(p.tool),r.set(p.tool.name,p.handle),u.client["notifications/tools/list_changed"]({}))),callTool:(p)=>Te(()=>{let f=r.get(p.name);if(!f)return ce(new yB({message:`Tool '${p.name}' not found`}));return f(p.arguments)}),get resources(){return n},get resourceTemplates(){return o},addResource:(p,f)=>Te(()=>(n.push(p),e.add(p.uri,{_tag:"Resource",effect:f}),u.client["notifications/resources/list_changed"]({}))),addResourceTemplate:({completions:p,handle:f,routerPath:A,template:d})=>Te(()=>{o.push(d),e.add(A,{_tag:"ResourceTemplate",handle:f});for(let[g,x]of Object.entries(p))a.set(`ref/resource/${d.uriTemplate}/${g}`,x);return u.client["notifications/resources/list_changed"]({})}),findResource:(p)=>Te(()=>{let f=e.find(p);if(!f)return Z({contents:[]});else if(f.handler._tag==="Resource")return f.handler.effect;let A=[];for(let d of Object.keys(f.params))A[Number(d)]=f.params[d];return f.handler.handle(p,A)}),get prompts(){return s},addPrompt:(p)=>Te(()=>{s.push(p.prompt),i.set(p.prompt.name,p.handle);for(let[f,A]of Object.entries(p.completions))a.set(`ref/prompt/${p.prompt.name}/${f}`,A);return u.client["notifications/prompts/list_changed"]({})}),getPromptResult:Ht(function*({arguments:p,name:f}){let A=i.get(f);if(!A)return yield*new yB({message:`Prompt '${f}' not found`});return yield*A(p??{})}),completion:Ht(function*(p){let f=p.ref,A=f.type==="ref/resource"?`ref/resource/${f.uri}/${p.argument.name}`:`ref/prompt/${f.name}/${p.argument.name}`,d=a.get(A);return d?yield*d(p.argument.value):IB.empty})})});static layer=Oc(Al,Al.make)}var L6e=Ht(function*(e){let t=yield*Al,r=yield*e,n=yield*vn();for(let o of Object.values(r.tools)){let s=new gF({name:o.name,description:o.description,inputSchema:q6e(o.parametersSchema.ast),annotations:new mF({...Jo(o.annotations,cJ).pipe(jt((i)=>({title:i})),pt),readOnlyHint:Ot(o.annotations,gy),destructiveHint:Ot(o.annotations,Ey),idempotentHint:Ot(o.annotations,lJ),openWorldHint:Ot(o.annotations,uJ)})});yield*t.addTool({tool:s,handle(i){return r.handle(o.name,i).pipe(Jn(n),Xk({onFailure:(a)=>new SB({isError:!0,structuredContent:typeof a==="object"?a:void 0,content:[{type:"text",text:JSON.stringify(a)}]}),onSuccess:(a)=>new SB({isError:!1,structuredContent:typeof a.encodedResult==="object"?a.encodedResult:void 0,content:[{type:"text",text:JSON.stringify(a.encodedResult)}]})}))}})}}),P6e=(e)=>r0(L6e(e)).pipe(no(Al.layer)),JCe=function(){if(arguments.length===1){let o=arguments[0];return _e(function*(){let s=yield*vn();yield*(yield*Al).addResource(new CB({...o,annotations:o}),o.content.pipe(Jn(s),z((a)=>zCe(o.uri,a)),rn((a)=>{let c=gk(a)[0];return new my({message:c.message})})))})}let{params:e,routerPath:t,schema:r,uriPath:n}=W6e(...arguments);return Ht(function*(o){let s=yield*vn(),i=yield*Al,a=is(r),c=new hF({...o,uriTemplate:n,annotations:o}),l={};for(let[u,p]of Object.entries(o.completion??{})){let f=hh(Re(e[u])),A=(d)=>p(d).pipe(w(f),z((g)=>new IB({completion:{values:g,total:g.length,hasMore:!1}})),rn((g)=>{let x=gk(g)[0];return new my({message:x.message})}),Jn(s));l[u]=A}yield*i.addResourceTemplate({template:c,routerPath:t,completions:l,handle:(u,p)=>a(p).pipe(De((f)=>new yB({message:f.message})),w((f)=>o.content(u,...f).pipe(z((A)=>zCe(u,A)),rn((A)=>{let d=gk(A)[0];return new my({message:d.message})}))),Jn(s))})})},jCe=function(){if(arguments.length===1)return r0(JCe(arguments[0])).pipe(no(Al.layer));let e=JCe(...arguments);return(t)=>r0(e(t)).pipe(no(Al.layer))};var H6e=()=>{let e=Xye({ignoreTrailingSlash:!0,ignoreDuplicateSlashes:!0,caseSensitive:!0});return{add:(n,o)=>{e.on("GET",n,o)},find:(n)=>e.find("GET",n)}},W6e=(e,...t)=>{let r=e[0].replace(":","::"),n=e[0],o={},s=oI();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 p=yn(qCe)(c.ast).pipe(je(()=>`param${u}`));o[p]=c,n+=`{${p}}${l}`}s=oI(...i)}return{routerPath:r,uriPath:n,schema:s,params:o}};var q6e=(e)=>{if(MS(e).length===0)return{type:"object",properties:{},required:[],additionalProperties:!1};let r={},n=nCe(e,{definitions:r,topLevelReferenceStrategy:"skip"});if(Object.keys(r).length===0)return n;return n.$defs=r,n},zCe=(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 EF="~@effect/ai/AiError";class xF extends ot("@effect/ai/AiError/MalformedInput")("MalformedInput",{module:m,method:m,description:U(m),cause:U(bt)}){[EF]=EF}class BB extends ot("@effect/ai/AiError/MalformedOutput")("MalformedOutput",{module:m,method:m,description:U(m),cause:U(bt)}){[EF]=EF;static fromParseError({error:e,...t}){return new BB({...t,cause:e})}}var Y6e={...Pg,...Ws,of:X,toContext(e){return _e(this,function*(){let t=yield*vn(),r=tn(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 fp(n)})},toLayer(e){return RS(this.toContext(e))},commit(){return _e(this,function*(){let e=this.tools,t=yield*vn(),r=new WeakMap,n=(s)=>{let i=r.get(s);if(Wy(i)){let a=t.unsafeMap.get(s.id),c=is(s.parametersSchema),l=Ie(s.successSchema,s.failureSchema),u=Uee(l),p=hh(l);i={context:a.context,handler:a.handler,decodeParameters:c,validateResult:u,encodeResult:p},r.set(s,i)}return i},o=we("Toolkit.handle",{captureStackTrace:!1})(function*(s,i){yield*u6({tool:s,parameters:i});let a=e[s];if(Wy(a)){let A=Object.keys(e).join(",");return yield*new BB({module:"Toolkit",method:`${s}.handle`,description:`Failed to find tool with name '${s}' in toolkit - available tools: ${A}`})}let c=n(a),l=yield*De(c.decodeParameters(i),(A)=>new BB({module:"Toolkit",method:`${s}.handle`,description:`Failed to decode tool call parameters for tool '${s}' from:
|
|
184
184
|
'${JSON.stringify(i,void 0,2)}'`,cause:A})),{isFailure:u,result:p}=yield*c.handler(l).pipe(z((A)=>({result:A,isFailure:!1})),Vn((A)=>a.failureMode==="error"?ce(A):Z({result:A,isFailure:!0})),Er(({result:A})=>c.validateResult(A)),gE((A)=>wr(c.context,A)),De((A)=>NE(A)?new xF({module:"Toolkit",method:`${s}.handle`,description:`Failed to validate tool call result for tool '${s}'`,cause:A}):A)),f=yield*De(c.encodeResult(p),(A)=>new xF({module:"Toolkit",method:`${s}.handle`,description:`Failed to encode tool call result for tool '${s}'`,cause:A}));return{isFailure:u,result:p,encodedResult:f}});return{tools:e,handle:o}})},toJSON(){return{_id:"@effect/ai/Toolkit",tools:Array.from(Object.values(this.tools)).map((e)=>e.name)}},pipe(){return W(this,arguments)}},V6e=(e)=>Object.assign(function(){},Y6e,{tools:e}),J6e=(...e)=>{let t={};for(let r of e){let n=On(r)?VCe(r):r;t[r.name]=n}return t};var z6e=(...e)=>V6e(J6e(...e));import{homedir as U7e}from"node:os";var Qm="https://expand.land";function j6e(e){return e.replace(/\/+$/,"")}function ZCe(e){return e!==null&&e!==void 0&&Number.isInteger(e)&&e>0&&e<=2147483647?e:void 0}function KCe(e){return e!==null&&e!==void 0&&Number.isInteger(e)&&e>=0&&e<=4294967295?e:void 0}function QB(e,t="https://expand.land"){return`${j6e(t)}/s/${encodeURIComponent(e)}`}function XCe(e,t="https://expand.land"){return`${QB(e,t)}/appendix`}function eSe(e,t,r="https://expand.land"){let n=`${QB(e,r)}/content`,o=ZCe(t);return o===void 0?n:`${n}?id=${o}`}var $6e=/^[A-Za-z0-9._~-]+$/u;function tSe(e){let t=e.trim();if(t.length===0)return;if($6e.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 K6e(e){return new URL(e).origin}function xy(e,t){if(e==null)return t;try{return K6e(e)}catch{return t}}function yy(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=QB(e,o?n:typeof r==="string"?r:"https://expand.land"),l=ZCe(i?.evidenceId);if(l!==void 0)return`${c}?id=${l}`;if(s==="statejson"){let u=KCe(i?.stateJsonSourceId);return u===void 0?c:`${c}?id=${u}`}if(s==="markdown"||s==="appendix"){let u=KCe(i?.nodeIds?.[0]);return u===void 0?c:`${c}/playground#focus=${u}`}return c}var TSe=Ii(RSe(),1);class RJ extends ot()("CredentialStorageLockError",{error:bt}){get message(){return"Could not lock credential storage. Try again shortly."}}var kSe=Pi(new Set);function DSe(e,t){if(typeof e!=="object"||e===null||!("code"in e))return!1;return e.code===t}function N7e(e){return DSe(e.error,"ERELEASED")||DSe(e.error,"ENOTACQUIRED")}var Nu=Ht(function*(e,t,r=`${e}.lock`){let n=yield*iFe(kSe);if(n.has(e))return yield*t;return yield*ef(lr({try:()=>TSe.lock(e,{realpath:!1,lockfilePath:r,onCompromised:()=>{return}}),catch:(o)=>new RJ({error:o})}).pipe(CS({schedule:fH("25 millis"),times:400,while:({error:o})=>o instanceof Error&&("code"in o)&&o.code==="ELOCKED"})),()=>EE(t,kSe,new Set([...n,e])),(o)=>lr({try:()=>o(),catch:(s)=>new RJ({error:s})}).pipe(Vn((s)=>N7e(s)?Y:Mo(s))))});var kJ=we("runNonInteractiveCommand")(function*(e){let t=yield*e.pipe(XD(mne),J_e("pipe"),V_e("inherit"),Y_e),[r]=yield*wc([t.exitCode,P_e(t.stdout)],{concurrency:"unbounded"});return r},ro);function vSe(e,t,r,n){return ro(_e(function*(){let o=yield*e.open(t,{flag:"wx",mode:n}),s=yield*o.stat,i={dev:s.dev,ino:pt(s.ino),mode:s.mode,type:s.type},a=yield*Dr(o.writeAll(new TextEncoder().encode(r)).pipe(ve(o.sync)));if(vo(a))return{identity:i,writeExit:a,pathMatchesHandle:!1};let c=yield*e.stat(t),l=by(i,{exists:!0,dev:c.dev,ino:pt(c.ino),type:c.type});return{identity:i,writeExit:a,pathMatchesHandle:l}}))}function by(e,t){return t.exists&&t.dev===e.dev&&t.ino===e.ino&&t.type===e.type}import{homedir as _7e}from"node:os";var OSe=_e(function*(){let e=yield*Jr;return yield*Do("XDG_CONFIG_HOME").pipe(bd(""),Lg((t)=>t.trim()===""?e.join(_7e(),".config"):t))});var OF="https://api.expand.ai",L7e="https://expand.ai",vB=(e)=>Do(e).pipe(_l,Lg(Ge({onNone:()=>!1,onSome:(t)=>t!==""&&t!=="0"&&t!=="false"}))),_Se=(e,t)=>Do(e).pipe(_l,Lg(Bn(lh(t)))),FF=3;function P7e(e,t){if(e===0)return"accepted";if(e===FF)return"refused";return t?"tolerated":"refused"}function DJ(e){let t=e.replace(/\//g,"\\");if(!t.startsWith("\\\\"))return!1;return!/^\\\\[?.]\\[a-z]:/i.test(t)}function H7e(e,t,r){if(DJ(e))return!1;return t.filter((n)=>!DJ(n)).some((n)=>e===n||e.startsWith(`${n}${r}`))}var USe=Y0(C2.pipe($ee("ApiKey"))),vm="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.",W7e=x2("ApiKey",{apiKey:USe}),TJ=x2("OAuth",{accessToken:Y0(m),refreshToken:U(Y0(m)),expiresAt:J0,clientId:U(m)}),q7e=b({enabled:U(ae),distinctId:U(m),noticeShown:U(ae)}),vJ=b({sessionToken:Y0(m),mintedAt:J0});class _u extends Oe("ExpandCliConfig")({apiUrl:U(W0),authMethod:U(Ie(W7e,TJ)),telemetry:U(q7e),anonymousSession:U(vJ)}){static Json=xo(_u)}function G7e(e,t){if(e._tag==="ApiKey")return"healthy";if(E6(t,e.expiresAt))return ns(e.accessToken).trim().length>0?"healthy":"unusable";let r=e.refreshToken;return r!==void 0&&ns(r).trim().length>0?"refresh_required":"unusable"}function Y7e(e,t){return G7e(e,t)!=="unusable"}var V7e=xo(b({alg:mh})),J7e=xo(b({iss:W0}));function z7e(e,t){if(e._tag!=="OAuth")return!1;let r=ns(e.accessToken).split(".");if(r.length!==3||r.some((o)=>!/^[A-Za-z0-9_-]+$/u.test(o)||zt(ZP(o))))return!1;let n=ct(r[0]).pipe(Bn((o)=>Xy(XP(o))),Bn(lh(V7e)));if($e(n))return!1;return ct(r[1]).pipe(Bn((o)=>Xy(XP(o))),Bn(lh(J7e)),WA(({iss:o})=>(o.protocol==="https:"||o.protocol==="http:")&&o.origin!==t.origin))}var j7e=Fn({key:m,value:Tt}),vF=xo(j7e);function $7e(e,t){return{...e,...t}}function K7e(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function Z7e(e){return`'${e.replaceAll("'","''")}'`}function FSe(e,t){return`$PSModuleAutoLoadingPreference = 'None'
|
|
185
185
|
$targetPaths = @(${t.map((r)=>Z7e(r)).join(", ")})
|
|
186
186
|
function Get-CredentialItem($targetPath) {
|
package/build/esm/main.js
CHANGED
|
@@ -298,7 +298,7 @@ foreach ($targetPath in $targetPaths) {
|
|
|
298
298
|
}
|
|
299
299
|
}
|
|
300
300
|
'SECURE'
|
|
301
|
-
`,m=[process.env.USERPROFILE,zBt()].filter((ce)=>typeof ce==="string"&&ce.trim()!==""&&!cee(ce)),g=(ce)=>r.resolve(ce).toLowerCase().replace(/\\+$/,""),y=Ce(function*(ce){let De=(Yt)=>t.realPath(Yt).pipe(Ft(()=>M(Yt)),K(g)),Fe=yield*De(ce),st=yield*ot(m,De);return $Bt(Fe,st,r.sep)}),w=Ce(function*(ce,De,Fe){if(ce===0)return;let st=yield*y(o);return yield*o0t(o,ce,st,De,Fe)}),b=(ce,De)=>w(1,ce,De),D=Ce(function*(ce){let De=yield*vB("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",wPe(d,ce)).pipe(aee,jr(gE,e),Ft((Fe)=>b("could not run the Windows ACL allowlist script",String(Fe)).pipe(un(0))));yield*w(De,"the Windows ACL allowlist script did not complete",`PowerShell exited with status ${De}`)}),k=Ce(function*(ce){let De=yield*vB("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",wPe(A,ce)).pipe(aee,jr(gE,e),Ft((Fe)=>b("could not inspect the Windows ACL allowlist",String(Fe)).pipe(un(0))));yield*w(De,"the Windows ACL allowlist could not be verified",`PowerShell exited with status ${De}`)}),B=W("ConfigManager.inspectSecureStorage")(function*(){let ce=yield*a(o);if(!ce.exists)return yield*Z;if(ce.type!=="Directory")return yield*i(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*i(n,"credential path is not a regular file",Error("Invalid file"));if(process.platform==="win32"){let st=De.exists?[o,n]:[o],Yt=yield*ot(st,a);yield*k(st);let rr=yield*ot(st,a);return yield*ot(st,(io,bi)=>c(io,Yt[bi]??{exists:!1},rr[bi]??{exists:!1}),{discard:!0}),yield*Z}if(((yield*t.stat(o).pipe(fe((st)=>i(o,"could not inspect directory mode",st)))).mode&4095)!==448)return yield*i(o,"config directory mode is not 700",Error("Invalid directory mode"));if(De.exists){if(((yield*t.stat(n).pipe(fe((Yt)=>i(n,"could not inspect credential file mode",Yt)))).mode&4095)!==384)return yield*i(n,"credential file mode is not 600",Error("Invalid file mode"))}return yield*Z}),S=W("ConfigManager.ensureSecureStorage")(function*(){yield*t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((Fe)=>i(o,"could not create the config directory",Fe)));let ce=yield*a(o);if(!ce.exists||ce.type!=="Directory")return yield*i(o,"config directory is not a regular directory",Error("Invalid config directory"));if(!(yield*t.exists(n).pipe(fe((Fe)=>i(n,"could not inspect the credential file",Fe))))){let Fe=yield*jt(t.writeFileString(n,"{}",{flag:"wx",mode:384}));if(qt(Fe)&&(!(Fe.left instanceof ji)||Fe.left.reason!=="AlreadyExists"))return yield*i(n,"could not create the credential file",Fe.left)}if(yield*l(n),process.platform==="win32"){let Fe=[o,n],st=yield*ot(Fe,(rr)=>a(rr));yield*D(Fe);let Yt=yield*ot(Fe,(rr)=>a(rr));yield*ot(Fe,(rr,io)=>c(rr,st[io]??{exists:!1},Yt[io]??{exists:!1}),{discard:!0})}else yield*f(o,448,"Directory"),yield*f(n,384,"File");return yield*Z});function Q(){return t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((ce)=>i(o,"could not create the config directory",ce)),be(process.platform==="win32"?D([o]):f(o,448,"Directory")),be(rm(n,S())))}let I=Ce(function*(ce){yield*Q();let De=yield*l(n),Fe=yield*d5e(0,2147483647),st=r.join(o,`.config.json.${process.pid}.${Fe.toString(16)}.tmp`),Yt=Ce(function*(Cs,js){let Is=yield*jt(l(st));if(qt(Is))return yield*new JC({path:n,temporaryPath:st,error:Is.left,operationError:js});if(!BPe(De.parent,Is.right.parent))return yield*new JC({path:n,temporaryPath:st,error:Error("Config temp parent identity changed; refusing cleanup"),operationError:js});if(!$0(Cs,Is.right.file))return yield*new JC({path:n,temporaryPath:st,error:Error("Config temp identity changed or disappeared; refusing cleanup"),operationError:js});let vI=yield*jt(t.remove(st));if(qt(vI))return yield*new JC({path:n,temporaryPath:st,error:vI.left,operationError:js})}),rr=yield*bPe(t,st,ce,384).pipe(fe(()=>new dy({path:st})));if($o(rr.writeExit)){let Cs=new dy({path:st});return yield*Yt(rr.identity,Cs),yield*Cs}if(!rr.pathMatchesHandle){let Cs=new dy({path:st});return yield*Yt(rr.identity,Cs),yield*Cs}let io=yield*jt(Y(function*(){let Cs=yield*l(st);if(yield*c(De.parentPath,De.parent,Cs.parent),!$0(rr.identity,Cs.file))return yield*i(st,"config temp identity differs from its creating handle",Error("Config temp replacement detected"));if(process.platform==="win32"){yield*D([st]);let Is=yield*l(st);if(yield*c(De.parentPath,De.parent,Is.parent),!$0(rr.identity,Is.file))return yield*i(st,"config temp changed while applying its ACL",Error("Config temp replacement detected"))}else if(((yield*t.stat(st).pipe(fe((vI)=>i(st,"could not verify config temp mode",vI)))).mode&4095)!==384)return yield*i(st,"config temp mode is not 600",Error("Invalid config temp mode"));let js=yield*l(n);yield*c(De.parentPath,De.parent,js.parent),yield*c(n,De.file,js.file),yield*t.rename(st,n).pipe(fe(()=>new dy({path:n})))}));if(qt(io))return yield*Yt(rr.identity,io.left),yield*io.left;let bi=yield*l(n);if(yield*c(De.parentPath,De.parent,bi.parent),!$0(rr.identity,bi.file))return yield*i(n,"atomic credential installation identity could not be verified",Error("Installed file identity mismatch"))});function O(ce){return Q().pipe(be(rm(n,I(ce))))}let v=Y(function*(){if(!(yield*t.exists(n)))return{config:nm.make({}),raw:{}};let De=yield*p(n),Fe=yield*Tu(aq)(De).pipe(fe((rr)=>new Ay({path:n,error:rr})));return{config:yield*ir(nm)(Fe).pipe(fe((rr)=>new Ay({path:n,error:rr}))),raw:Fe}}),H=v.pipe(K(({config:ce})=>ce)),T=W("loadConfig")(function*(){let{config:ce,noAnonymous:De}=yield*QPe,Fe=yield*H,st={env:vt(ce.apiUrl),file:vt(Fe.apiUrl)},Yt={env:vt(ce.authMethod),file:vt(Fe.authMethod)};yield*tl(`EXPAND_API_URL overrides apiUrl from ${n}`).pipe(Ms(()=>e$e(st.env,st.file,(Is,vI)=>Is.toString()!==vI.toString()).pipe(Ue(()=>!1))));let rr=yield*fc,io=ZQ([st.env,st.file]).pipe(Ue(()=>new URL(cq))),bi=Yt.file.pipe(ns((Is)=>XBt(Is,io))),Cs=Yt.file.pipe(ns((Is)=>Is._tag==="OAuth"&&gO(Is,rr)),ns(()=>ze(Yt.env)||ze(bi))),js=ZQ([Cs,Yt.env,Yt.file]);return yield*tl(`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(Ms(()=>ne(Yt.env)&&ne(Cs))),yield*tl(`Using EXPAND_API_KEY for ${io.origin} because the stored login was issued by a different API origin.`).pipe(Ms(()=>ne(Yt.env)&&ne(bi))),yield*tl(`EXPAND_API_KEY overrides the API key stored in ${n}`).pipe(Ms(()=>ne(Yt.env)&&Rm(Yt.file,(Is)=>Is._tag==="ApiKey"))),{apiUrl:io,authMethod:js,anonymousSession:vt(Fe.anonymousSession),noAnonymous:De}}),j=W("saveConfig")(function*(ce){let De=yield*vo(nm.Json)(ce);yield*O(De)}),F=W("updateConfig")(function*(ce){let De=yield*v,Fe=nm.make({...De.config,...ce}),st=yield*vo(nm.Json)(Fe).pipe(N(Tu(aq))),Yt={...t0t(De.raw,st)};if(Object.hasOwn(ce,"anonymousSession")&&ce.anonymousSession===void 0)delete Yt.anonymousSession;let rr=yield*vo(aq)(Yt);yield*O(rr)});function C(ce){return Q().pipe(be(rm(n,F(ce))))}let R=W("readConfigFile")(function*(){return yield*v.pipe(K(({config:ce})=>({config:ce,parseFailed:!1})),nl(()=>({config:nm.make({}),parseFailed:!0})))}),L=W("clearConfig")(function*(){let ce=yield*jt(v);if(qt(ce)){if(!(ce.left instanceof Ay))return yield*ce.left;yield*tl(`Could not parse ${n}; removing it. Telemetry preferences and apiUrl were not preserved.`),yield*t.remove(n).pipe(fe(()=>new dy({path:n})));return}let De={...ce.right.raw};delete De.authMethod,delete De.anonymousSession;let Fe=yield*vo(aq)(De);yield*O(Fe)});function G(){return Q().pipe(be(rm(n,L())))}let ae=W("getApiUrl")(function*(){let{config:ce}=yield*QPe,De=yield*H,Fe={env:vt(ce.apiUrl),file:vt(De.apiUrl)};return ZQ([Fe.env,Fe.file]).pipe(Ue(()=>new URL(cq)))}),Me=W("getAppUrl")(function*(){return yield*Ht("EXPAND_APP_URL").pipe(yr(YBt))}),He=W("getPlaygroundHost")(function*(){return yield*Ht("EXPAND_PLAYGROUND_HOST").pipe(yr(VC))});return{configPath:n,inspectSecureStorage:B,ensureSecureStorage:Q,loadConfig:T,saveConfig:j,updateConfig:C,clearConfig:G,readConfigFile:R,getApiUrl:ae,getAppUrl:Me,getPlaygroundHost:He}})}){}var ZC="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.",dq="Authorization complete. That setup code has been consumed and cannot be reused.",Aq="Expand is already authorized. Agent setup is complete.",pee="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.",fee="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.",dee="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.",ii=V("claude-code","cursor","opencode","codex","fx");class hq extends Ne("InitDetectionResult")({schemaVersion:V(1),status:V("detected"),harnesses:ve(ii),current:z(ii),userMessage:V(fee,dee)}){}var Aee=eB(ii),Va=V("project","global"),i0t=V("webfetch-hook","runtime-skill","mcp"),s0t=V("unverified","observed","reload_required","blocked"),zhr=V("authorization_required","completed"),a0t=E.pipe(yn(20),wP(256)),c0t=uh(a0t,fh(E),{strict:!0,decode:(e)=>e,encode:()=>"<redacted-redacted-setup-token>"});class mq extends Ne("InitRequest")({harnesses:Aee,scope:Va,setupToken:z(c0t)}){}var l0t=q({schemaVersion:V(1),status:V("authorization_required"),harnesses:Aee,scope:Va,userMessage:V(ZC),authorization:q({url:Kg,userCode:E,approvalExpiresAt:id})}),u0t=q({runtimeState:s0t,nextAction:E}),p0t=q({harness:ii,configured:Ie,changed:Ie,components:ve(i0t),version:E,verification:u0t}),f0t=q({harness:ii,code:E,recoverable:Ie}),d0t=q({schemaVersion:V(1),status:V("completed"),harnesses:Aee,scope:Va,userMessage:V(dq,Aq,pee),auth:q({healthy:Ie}),projectPath:z(E),installations:eB(p0t),failures:z(ve(f0t))}),EO=Je(l0t,d0t);class hy extends Ne("InitErrorEnvelope")({schemaVersion:V(1),status:V("error"),code:E,message:E,recoverable:Ie}){}var Zu="expandai-cli-browser",A0t=q({apiOrigin:E,clientId:V(Zu),purpose:z(V("login","agent-setup")),harness:V("agent-harnesses"),scope:V("project","global"),canonicalScopeRoot:E});class K0 extends Ne("PendingInitRecord")({key:A0t,deviceCode:fh(E),userCode:E,verificationUri:E,intervalSeconds:de,nextPollAt:id,approvalExpiresAt:id}){}class im extends et()("PendingInitCorrupt",{path:E,error:Vt}){recoverable=!0;get message(){return`Pending authorization state at ${this.path} is corrupt and was left unchanged.`}}class hee extends et()("PendingInitStorageError",{path:E,error:Vt}){recoverable=!0;get message(){return`Could not access pending authorization state at ${this.path}.`}}class mee extends Ne("DeviceAuthorizationCreated")({deviceCode:fh(fs),userCode:fs,verificationUri:Kg,expiresIn:hr.pipe(xK()),interval:hr.pipe(o6e())}){}var h0t=q({access_token:fh(fs),refresh_token:fh(fs),token_type:fs,expires_in:de.pipe(xK()),scope:z(E)}),m0t=V("create","poll");class Xu extends et()("DeviceAuthorizationApiError",{operation:m0t,kind:V("request_failed","rejected","invalid_response"),status:z(de),recoverable:Ie}){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 gq extends Ct()("@expandai/cli/Auth/DeviceAuthorizationClient",{dependencies:[Yd,Bt.Default],effect:Y(function*(){let e=yield*Mh,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*FB(new URL("/v1/cli-authorization/device",c)).pipe(yl(a),fe(()=>r("create","request_failed")));return yield*e.execute(l).pipe(N((u)=>Wt(u.status).pipe(Qe((p)=>p>=200&&p<300,()=>Ws(mee)(u).pipe(fe(()=>r("create","invalid_response")))),hd(()=>u.text.pipe(tn,be(r("create","rejected",u.status)))))),Ft((u)=>u instanceof Xu?u:r("create","request_failed")))}),o=q({error:E,error_description:z(E)}),i=new Set(["invalid_target","invalid_client","invalid_scope","unsupported_grant_type","unauthorized_client","invalid_request"]),s=W("DeviceAuthorizationClient.poll")(function*(a){let c=yield*t.getApiUrl(),l=FB(new URL("/api/auth/oauth2/token",c)).pipe(rwe({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:oa(a),client_id:Zu,resource:c.toString()}));return yield*e.execute(l).pipe(N(Ce(function*(u){return yield*Wt(u.status).pipe(Qe((p)=>p>=200&&p<300,()=>Ws(h0t)(u).pipe(fe(()=>r("poll","invalid_response")),K((p)=>({_tag:"Tokens",token:p})))),Qe((p)=>p>=500,()=>u.text.pipe(tn,be(r("poll","rejected",u.status)))),hd(()=>Ws(o)(u).pipe(fe(()=>r("poll","invalid_response")),K((p)=>Wt(p.error).pipe(Qe("authorization_pending",()=>({_tag:"Pending"})),Qe("slow_down",()=>({_tag:"SlowDown"})),Qe("access_denied",()=>({_tag:"Denied"})),Qe("expired_token",()=>({_tag:"Expired"})),hd(()=>i.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:s}})}){}var Si="0.1.5";class DPe extends DS()("DeviceAuthorizationTokensSaved",{}){}class RPe extends DS()("DeviceAuthorizationPending",{}){}class vPe extends DS()("DeviceAuthorizationSlowDown",{}){}class TPe extends DS()("DeviceAuthorizationExpired",{}){}class OPe extends DS()("DeviceAuthorizationInvalid",{}){}class gf extends et()("DeviceAuthorizationDenied",{recoverable:V(!0)}){get message(){return"The authorization request was denied in the browser. Run the same command again to start a new one."}}class sm extends et()("DeviceAuthorizationRefused",{error:E,description:z(E),recoverable:V(!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 am extends et()("DeviceAuthorizationCredentialSaveFailed",{recoverable:V(!1)}){get message(){return"Authorization succeeded, but credentials could not be saved. Start authorization again."}}function kPe(e){return e.platform??process.platform}class XC extends Ct()("@expandai/cli/Auth/DeviceAuthorization",{dependencies:[Bt.Default,gq.Default],effect:Y(function*(){let e=yield*Bt,t=yield*gq,r=W("DeviceAuthorization.create")(function*(i){yield*e.ensureSecureStorage();let s={platform:kPe(i),machineLabel:`${kPe(i)}-${process.arch}`,cliVersion:Si};return yield*i.purpose==="login"?t.create({purpose:"login",harness:"agent-harnesses",scope:"global",...s}):t.create({purpose:"agent-setup",harness:i.harness,scope:i.scope,...s})}),n=Ce(function*(i){let s=yield*fc,a=yield*jt(e.updateConfig({authMethod:mO.make({accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:zw(s,Yc(i.expires_in)),clientId:Zu})}));return yield*Wn(a,{onLeft:()=>new am({recoverable:!1}),onRight:()=>Z})}),o=W("DeviceAuthorization.poll")(function*(i){let s=yield*t.poll(i);return yield*Wt(s).pipe(xr("Tokens",({token:a})=>n(a).pipe(un(new DPe))),xr("Pending",()=>M(new RPe)),xr("SlowDown",()=>M(new vPe)),xr("Denied",()=>new gf({recoverable:!0})),xr("Expired",()=>M(new TPe)),xr("Invalid",()=>M(new OPe)),xr("Refused",({error:a,description:c})=>new sm({error:a,...c===void 0?{}:{description:c},recoverable:!1})),Sr)});return{create:r,poll:o}})}){}import{createHash as g0t}from"node:crypto";var gee=Nt(K0),E0t=300000,MPe=Nt(Je(BS(E,V(Zu),V("agent-harnesses"),V("project","global"),E),BS(E,V(Zu),V("login"))));function Eee(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function y0t(e){return e instanceof ji&&(e.reason==="AlreadyExists"||Eee(e.cause,"EEXIST"))}function x0t(e){return e instanceof ji&&(e.reason==="NotFound"||Eee(e.cause,"ENOENT"))}function S0t(e){return e.purpose==="login"?Do(MPe)([e.apiOrigin,e.clientId,e.purpose]):Do(MPe)([e.apiOrigin,e.clientId,e.harness,e.scope,e.canonicalScopeRoot])}function _Pe(e,t){let r=e.dirname(t);return r===t?[t]:[t,..._Pe(e,r)]}class cm extends Ct()("@expandai/cli/Auth/PendingInitStore",{dependencies:[Uv],effect:Y(function*(){let e=yield*lr,t=yield*sr,r=t.join(yield*J0,"expandai"),n=t.join(r,"pending-init"),o=(S,Q)=>new hee({path:S,error:Q}),i=(S,Q)=>Q.pipe(fe((I)=>o(S,I))),s=Ce(function*(S){let Q=yield*jt(e.readLink(S));if(vn(Q))return yield*o(S,Error("Symbolic links are not allowed for pending authorization"));let I=Q.left;if(I instanceof ji&&(I.reason==="InvalidData"||I.reason==="NotFound"||I.method==="readLink"&&Eee(I.cause,"EINVAL")))return;return yield*o(S,I)}),a=Ce(function*(){if(yield*s(r),yield*s(n),yield*i(n,e.makeDirectory(n,{recursive:!0,mode:448})),yield*s(r),yield*s(n),(yield*i(n,e.stat(n))).type!=="Directory")return yield*o(n,Error("Pending authorization path is not a directory"));if(process.platform!=="win32")yield*i(r,e.chmod(r,448)),yield*i(n,e.chmod(n,448))}),c=(S)=>{let Q=g0t("sha256").update(S0t(S)).digest("hex");return t.join(n,`${Q}.json`)},l=Ce(function*(S,Q){let I=yield*Tu(gee)(Q).pipe(fe(()=>new im({path:S,error:Error("Stored pending authorization did not match the expected schema")})));if(c(I.key)!==S)return yield*new im({path:S,error:Error("Stored pending authorization key did not match its file")});return I}),u=Ce(function*(S){if(yield*s(S),!(yield*i(S,e.exists(S))))return U();let I=yield*i(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 O=yield*i(S,e.readFileString(S));return P(yield*l(S,O))}),p=(S)=>u(c(S)),f=Ce(function*(S){let Q=wR(yield*fc);return wR(S.approvalExpiresAt)+E0t<=Q}),d=Ce(function*(S){yield*a();let Q=c(S.key),I=yield*vo(gee)(S).pipe(fe((v)=>o(Q,v))),O=yield*jt(Tr(Y(function*(){let v=yield*e.open(Q,{flag:"wx",mode:384});yield*v.writeAll(new TextEncoder().encode(I)),yield*v.sync})));if(qt(O)){if(y0t(O.left))return!1;return yield*e.remove(Q).pipe(tn),yield*o(Q,O.left)}if(process.platform!=="win32"){let v=yield*jt(e.chmod(Q,384));if(qt(v))return yield*e.remove(Q).pipe(tn),yield*o(Q,v.left)}return!0}),A=W("PendingInitStore.replaceIfMatch")(function*(S,Q){yield*a();let I=c(Q.key);if(c(S.key)!==I)return yield*o(I,Error("Pending authorization replacement changed its key"));let O=yield*u(I);if(ze(O)||O.value.userCode!==S.userCode)return!1;let v=yield*vo(gee)(Q).pipe(fe((j)=>o(I,j))),H=`${I}.${process.pid}.${Math.random().toString(36).slice(2,10)}.tmp`,T=yield*Tr(vr(M(H),()=>e.remove(H).pipe(tn)).pipe(be(Y(function*(){yield*s(H),yield*Tr(Y(function*(){let j=yield*e.open(H,{flag:"wx",mode:384});yield*j.writeAll(new TextEncoder().encode(v)),yield*j.sync})),yield*e.rename(H,I)})))).pipe(jt);if(qt(T))return yield*o(I,T.left);return!0}),m=Ce(function*(S){let Q=c(S.key),I=yield*u(Q);if(ze(I)||I.value.userCode!==S.userCode)return!1;return yield*i(Q,e.remove(Q)),!0}),g=W("PendingInitStore.get")(function*(S){let Q=yield*p(S);if(ze(Q)||!(yield*f(Q.value)))return Q;return yield*m(Q.value),U()}),y=W("PendingInitStore.peek")(function*(S){return yield*p(S)}),w=W("PendingInitStore.putIfAbsent")(function*(S){let Q=yield*p(S.key);if(ne(Q)&&!(yield*f(Q.value)))return Q.value;if(ne(Q))yield*m(Q.value);if(yield*d(S))return S;let I=yield*p(S.key);return yield*Te(I,{onNone:()=>o(c(S.key),Error("Pending record creation lost without a winner")),onSome:M})}),b=W("PendingInitStore.removeIfMatch")((S)=>m(S)),D=W("PendingInitStore.removeCorrupt")(function*(S){let Q=c(S),I=yield*jt(u(Q));if(vn(I))return!1;if(!(I.left instanceof im))return yield*I.left;let O=yield*jt(e.remove(Q));if(qt(O)&&x0t(O.left))return!1;if(qt(O))return yield*o(Q,O.left);return!0}),k=W("PendingInitStore.pruneExpired")(function*(){if(yield*s(n),!(yield*i(n,e.exists(n))))return 0;let Q=yield*i(n,e.readDirectory(n));return(yield*ot(Q.filter((O)=>O.endsWith(".json")),(O)=>Y(function*(){let v=yield*u(t.join(n,O));if(ze(v)||!(yield*f(v.value)))return 0;return(yield*m(v.value))?1:0}).pipe(nl(()=>0)))).reduce((O,v)=>O+v,0)}),B=W("PendingInitStore.canonicalScopeRoot")(function*(S,Q=process.cwd()){if(S==="global")return"global";let I=yield*i(Q,e.realPath(Q)),v=(yield*ot(_Pe(t,I),(H)=>i(H,e.exists(t.join(H,".git"))).pipe(K((T)=>({candidate:H,exists:T}))))).find(({exists:H})=>H)?.candidate;return v===void 0?I:yield*i(v,e.realPath(v))});return{pendingPath:n,get:g,peek:y,putIfAbsent:w,replaceIfMatch:A,removeIfMatch:b,removeCorrupt:D,pruneExpired:k,canonicalScopeRoot:B}})}){}var C0t=Zu,I0t=5;class yO extends Ne("ManualAuthorizationInput")({purpose:_(V("login","agent-setup"),{default:()=>"agent-setup"}),harness:V("agent-harnesses"),scope:Va,cwd:z(E),platform:z(E)}){}class yee extends Ne("ManualAuthorizationRequired")({verificationUri:E,userCode:fs,approvalExpiresAt:id}){}class xee extends DS()("TokensSaved",{}){}class my extends DS()("AuthorizationPending",{pending:yee}){}var bmr=Je(xee,my);function Z0(e){return new yee({verificationUri:e.verificationUri,userCode:e.userCode,approvalExpiresAt:e.approvalExpiresAt})}class ep extends Ct()("@expandai/cli/Auth/ManualAuthorization",{dependencies:[Bt.Default,cm.Default,XC.Default],effect:Y(function*(){let e=yield*Bt,t=yield*cm,r=yield*XC,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:C0t,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*fc,A=new K0({key:u,deviceCode:f.deviceCode,userCode:f.userCode,verificationUri:f.verificationUri.toString(),intervalSeconds:f.interval,nextPollAt:zw(d,Yc(f.interval)),approvalExpiresAt:zw(d,Yc(f.expiresIn))}),m=yield*jt(t.putIfAbsent(A));if(qt(m))return yield*m.left;return m.right}),i=Ce(function*(l,u){let p=yield*fc,f=l.intervalSeconds+(u?I0t:0),d=new K0({...l,intervalSeconds:f,nextPollAt:zw(p,Yc(f))}),A=yield*jt(t.replaceIfMatch(l,d));if(qt(A))return l;return A.right?d:l}),s=Ce(function*(l,u){let p=yield*jt(t.get(u));if(vn(p))return p.right;if(l.purpose!=="login"||!(p.left instanceof im))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*s(l,u);if(ze(p)){let g=yield*o(l,u);return new my({pending:Z0(g)})}let f=p.value,d=yield*fc;if(BXe(d,f.approvalExpiresAt)){yield*t.removeIfMatch(f);let g=yield*o(l,u);return new my({pending:Z0(g)})}if(AP(d,f.nextPollAt))return new my({pending:Z0(f)});let A=yield*jt(r.poll(f.deviceCode)),m=Ce(function*(){yield*t.removeIfMatch(f);let g=yield*o(l,u);return new my({pending:Z0(g)})});return yield*Wn(A,{onLeft:(g)=>t.removeIfMatch(f).pipe(Ms(()=>g instanceof gf),be(se(g))),onRight:(g)=>Wt(g).pipe(xr("DeviceAuthorizationTokensSaved",()=>t.removeIfMatch(f).pipe(un(new xee))),xr("DeviceAuthorizationPending",()=>i(f,!1).pipe(K((y)=>new my({pending:Z0(y)})))),xr("DeviceAuthorizationSlowDown",()=>i(f,!0).pipe(K((y)=>new my({pending:Z0(y)})))),xr("DeviceAuthorizationExpired",m),xr("DeviceAuthorizationInvalid",m),Sr)})}),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*Wt(u).pipe(xr("DeviceAuthorizationTokensSaved",()=>Z),xr("DeviceAuthorizationPending",p),xr("DeviceAuthorizationSlowDown",p),xr("DeviceAuthorizationExpired",p),xr("DeviceAuthorizationInvalid",p),Sr)});return{advance:a,redeemPreApproved:c}})}){}var FPe="Authorization complete. Expand is ready to use; retry the command that required authentication.",b0t=V("authorization_internal_error","authorization_unreachable","authorization_rejected","authorization_service_unavailable","authorization_invalid_response","authorization_denied","authorization_refused","credential_save_failed","credential_storage_insecure");class Tc extends et()("DeviceLoginError",{code:b0t,recoverable:Ie,httpStatus:z(de)}){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 yq extends Ne("DeviceLoginErrorEnvelope")({schemaVersion:V(1),status:V("error"),code:E,message:E,recoverable:Ie}){}var w0t=q({schemaVersion:V(1),status:V("authorization_required"),userMessage:V(ZC),authorization:q({url:Kg,userCode:fs,approvalExpiresAt:id})}),B0t=q({schemaVersion:V(1),status:V("completed"),userMessage:V(FPe),auth:q({healthy:V(!0)})}),Eq=Je(w0t,B0t);function Q0t(e){if(e instanceof vc)return new Tc({code:"credential_storage_insecure",recoverable:!1});if(e instanceof gf)return new Tc({code:"authorization_denied",recoverable:!0});if(e instanceof sm)return new Tc({code:"authorization_refused",recoverable:!1});if(e instanceof am)return new Tc({code:"credential_save_failed",recoverable:!1});if(e instanceof Xu)switch(e.kind){case"request_failed":return new Tc({code:"authorization_unreachable",recoverable:!0});case"rejected":if(e.status!==void 0&&e.status>=500)return new Tc({code:"authorization_service_unavailable",recoverable:!0,httpStatus:e.status});return new Tc({code:"authorization_rejected",recoverable:e.recoverable});case"invalid_response":return new Tc({code:"authorization_invalid_response",recoverable:!1})}return new Tc({code:"authorization_internal_error",recoverable:!1})}class xO extends Ct()("@expandai/cli/Auth/DeviceLogin",{dependencies:[ep.Default],effect:Y(function*(){let e=yield*ep;return{run:W("DeviceLogin.run")(function*(){let r=yield*e.advance(new yO({purpose:"login",harness:"agent-harnesses",scope:"global"})).pipe(fe(Q0t));return yield*Wt(r).pipe(xr("TokensSaved",()=>ir(Eq)({schemaVersion:1,status:"completed",userMessage:FPe,auth:{healthy:!0}}).pipe(fe(()=>new Tc({code:"authorization_internal_error",recoverable:!1})))),xr("AuthorizationPending",({pending:n})=>ir(Eq)({schemaVersion:1,status:"authorization_required",userMessage:ZC,authorization:{url:n.verificationUri,userCode:n.userCode,approvalExpiresAt:SS(n.approvalExpiresAt)}}).pipe(fe(()=>new Tc({code:"authorization_internal_error",recoverable:!1})))),Sr)})}})}){}class xq extends et()("SetupGrantAuthorizationError",{code:V("invalid_or_expired","stored_credential_conflict","request_failed","denied","credential_save_failed","refused","config_unreadable"),recoverable:Ie}){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 eI(e){return new xq({code:e,recoverable:e!=="denied"&&e!=="credential_save_failed"&&e!=="refused"})}class X0 extends Ct()("@expandai/cli/Auth/SetupGrantAuthorization",{dependencies:[Bt.Default,ep.Default],effect:Y(function*(){let e=yield*Bt,t=yield*ep;return{authorize:W("SetupGrantAuthorization.authorize")(function*(n){let o=yield*e.readConfigFile();if(o.parseFailed)return yield*eI("config_unreadable");if(o.config.authMethod?._tag==="ApiKey")return yield*eI("stored_credential_conflict");yield*Kx({harness:n.harness,scope:n.scope}),yield*t.redeemPreApproved(n.setupToken).pipe(fe((i)=>{if(i instanceof gf)return eI("denied");if(i instanceof am)return eI("credential_save_failed");if(i instanceof sm)return eI("refused");if(i instanceof Xu&&i.kind==="request_failed")return eI("request_failed");return eI("invalid_or_expired")}))})}})}){}import oHe from"node:process";import _ee from"node:path";import{fileURLToPath as uQt}from"node:url";import pQt from"node:child_process";import fQt,{constants as dQt}from"node:fs/promises";import U0t from"node:path";import{promisify as P0t}from"node:util";import H0t from"node:child_process";import Bee,{constants as zPe}from"node:fs/promises";import UPe from"node:process";import T0t from"node:os";import bee from"node:fs";import R0t from"node:fs";import NPe from"node:fs";var See;function k0t(){try{return NPe.statSync("/.dockerenv"),!0}catch{return!1}}function D0t(){try{return NPe.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Cee(){if(See===void 0)See=k0t()||D0t();return See}var Iee,v0t=()=>{try{return R0t.statSync("/run/.containerenv"),!0}catch{return!1}};function tI(){if(Iee===void 0)Iee=v0t()||Cee();return Iee}var LPe=()=>{if(UPe.platform!=="linux")return!1;if(T0t.release().toLowerCase().includes("microsoft")){if(tI())return!1;return!0}try{if(bee.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!tI()}catch{}if(bee.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||bee.existsSync("/run/WSL"))return!tI();return!1},jd=UPe.env.__IS_WSL_TEST__?LPe:LPe();import PPe from"node:process";import{Buffer as O0t}from"node:buffer";import{promisify as M0t}from"node:util";import _0t from"node:child_process";var F0t=M0t(_0t.execFile),wee=()=>`${PPe.env.SYSTEMROOT||PPe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var HPe=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],WPe=(e)=>O0t.from(e,"utf16le").toString("base64"),N0t=(e)=>`'${String(e).replaceAll(/['‘’‚‛]/g,(t)=>t+t)}'`,qPe=(e)=>[...HPe,WPe(e)],L0t=(e)=>({encoding:"utf8",...e,shell:!1}),tp=async(e,t={})=>{let{powerShellPath:r,...n}=t;return F0t(r??wee(),qPe(e),L0t(n))};tp.argumentsPrefix=HPe;tp.encodeCommand=WPe;tp.escapeArgument=N0t;tp.createArguments=qPe;function GPe(e){for(let t of e.split(`
|
|
301
|
+
`,m=[process.env.USERPROFILE,zBt()].filter((ce)=>typeof ce==="string"&&ce.trim()!==""&&!cee(ce)),g=(ce)=>r.resolve(ce).toLowerCase().replace(/\\+$/,""),y=Ce(function*(ce){let De=(Yt)=>t.realPath(Yt).pipe(Ft(()=>M(Yt)),K(g)),Fe=yield*De(ce),st=yield*ot(m,De);return $Bt(Fe,st,r.sep)}),w=Ce(function*(ce,De,Fe){if(ce===0)return;let st=yield*y(o);return yield*o0t(o,ce,st,De,Fe)}),b=(ce,De)=>w(1,ce,De),D=Ce(function*(ce){let De=yield*vB("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",wPe(d,ce)).pipe(aee,jr(gE,e),Ft((Fe)=>b("could not run the Windows ACL allowlist script",String(Fe)).pipe(un(0))));yield*w(De,"the Windows ACL allowlist script did not complete",`PowerShell exited with status ${De}`)}),k=Ce(function*(ce){let De=yield*vB("powershell.exe","-NoLogo","-NoProfile","-NonInteractive","-Command",wPe(A,ce)).pipe(aee,jr(gE,e),Ft((Fe)=>b("could not inspect the Windows ACL allowlist",String(Fe)).pipe(un(0))));yield*w(De,"the Windows ACL allowlist could not be verified",`PowerShell exited with status ${De}`)}),B=W("ConfigManager.inspectSecureStorage")(function*(){let ce=yield*a(o);if(!ce.exists)return yield*Z;if(ce.type!=="Directory")return yield*i(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*i(n,"credential path is not a regular file",Error("Invalid file"));if(process.platform==="win32"){let st=De.exists?[o,n]:[o],Yt=yield*ot(st,a);yield*k(st);let rr=yield*ot(st,a);return yield*ot(st,(io,bi)=>c(io,Yt[bi]??{exists:!1},rr[bi]??{exists:!1}),{discard:!0}),yield*Z}if(((yield*t.stat(o).pipe(fe((st)=>i(o,"could not inspect directory mode",st)))).mode&4095)!==448)return yield*i(o,"config directory mode is not 700",Error("Invalid directory mode"));if(De.exists){if(((yield*t.stat(n).pipe(fe((Yt)=>i(n,"could not inspect credential file mode",Yt)))).mode&4095)!==384)return yield*i(n,"credential file mode is not 600",Error("Invalid file mode"))}return yield*Z}),S=W("ConfigManager.ensureSecureStorage")(function*(){yield*t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((Fe)=>i(o,"could not create the config directory",Fe)));let ce=yield*a(o);if(!ce.exists||ce.type!=="Directory")return yield*i(o,"config directory is not a regular directory",Error("Invalid config directory"));if(!(yield*t.exists(n).pipe(fe((Fe)=>i(n,"could not inspect the credential file",Fe))))){let Fe=yield*jt(t.writeFileString(n,"{}",{flag:"wx",mode:384}));if(qt(Fe)&&(!(Fe.left instanceof ji)||Fe.left.reason!=="AlreadyExists"))return yield*i(n,"could not create the credential file",Fe.left)}if(yield*l(n),process.platform==="win32"){let Fe=[o,n],st=yield*ot(Fe,(rr)=>a(rr));yield*D(Fe);let Yt=yield*ot(Fe,(rr)=>a(rr));yield*ot(Fe,(rr,io)=>c(rr,st[io]??{exists:!1},Yt[io]??{exists:!1}),{discard:!0})}else yield*f(o,448,"Directory"),yield*f(n,384,"File");return yield*Z});function Q(){return t.makeDirectory(o,{recursive:!0,mode:448}).pipe(fe((ce)=>i(o,"could not create the config directory",ce)),be(process.platform==="win32"?D([o]):f(o,448,"Directory")),be(rm(n,S())))}let I=Ce(function*(ce){yield*Q();let De=yield*l(n),Fe=yield*d5e(0,2147483647),st=r.join(o,`.config.json.${process.pid}.${Fe.toString(16)}.tmp`),Yt=Ce(function*(Cs,js){let Is=yield*jt(l(st));if(qt(Is))return yield*new JC({path:n,temporaryPath:st,error:Is.left,operationError:js});if(!BPe(De.parent,Is.right.parent))return yield*new JC({path:n,temporaryPath:st,error:Error("Config temp parent identity changed; refusing cleanup"),operationError:js});if(!$0(Cs,Is.right.file))return yield*new JC({path:n,temporaryPath:st,error:Error("Config temp identity changed or disappeared; refusing cleanup"),operationError:js});let vI=yield*jt(t.remove(st));if(qt(vI))return yield*new JC({path:n,temporaryPath:st,error:vI.left,operationError:js})}),rr=yield*bPe(t,st,ce,384).pipe(fe(()=>new dy({path:st})));if($o(rr.writeExit)){let Cs=new dy({path:st});return yield*Yt(rr.identity,Cs),yield*Cs}if(!rr.pathMatchesHandle){let Cs=new dy({path:st});return yield*Yt(rr.identity,Cs),yield*Cs}let io=yield*jt(Y(function*(){let Cs=yield*l(st);if(yield*c(De.parentPath,De.parent,Cs.parent),!$0(rr.identity,Cs.file))return yield*i(st,"config temp identity differs from its creating handle",Error("Config temp replacement detected"));if(process.platform==="win32"){yield*D([st]);let Is=yield*l(st);if(yield*c(De.parentPath,De.parent,Is.parent),!$0(rr.identity,Is.file))return yield*i(st,"config temp changed while applying its ACL",Error("Config temp replacement detected"))}else if(((yield*t.stat(st).pipe(fe((vI)=>i(st,"could not verify config temp mode",vI)))).mode&4095)!==384)return yield*i(st,"config temp mode is not 600",Error("Invalid config temp mode"));let js=yield*l(n);yield*c(De.parentPath,De.parent,js.parent),yield*c(n,De.file,js.file),yield*t.rename(st,n).pipe(fe(()=>new dy({path:n})))}));if(qt(io))return yield*Yt(rr.identity,io.left),yield*io.left;let bi=yield*l(n);if(yield*c(De.parentPath,De.parent,bi.parent),!$0(rr.identity,bi.file))return yield*i(n,"atomic credential installation identity could not be verified",Error("Installed file identity mismatch"))});function O(ce){return Q().pipe(be(rm(n,I(ce))))}let v=Y(function*(){if(!(yield*t.exists(n)))return{config:nm.make({}),raw:{}};let De=yield*p(n),Fe=yield*Tu(aq)(De).pipe(fe((rr)=>new Ay({path:n,error:rr})));return{config:yield*ir(nm)(Fe).pipe(fe((rr)=>new Ay({path:n,error:rr}))),raw:Fe}}),H=v.pipe(K(({config:ce})=>ce)),T=W("loadConfig")(function*(){let{config:ce,noAnonymous:De}=yield*QPe,Fe=yield*H,st={env:vt(ce.apiUrl),file:vt(Fe.apiUrl)},Yt={env:vt(ce.authMethod),file:vt(Fe.authMethod)};yield*tl(`EXPAND_API_URL overrides apiUrl from ${n}`).pipe(Ms(()=>e$e(st.env,st.file,(Is,vI)=>Is.toString()!==vI.toString()).pipe(Ue(()=>!1))));let rr=yield*fc,io=ZQ([st.env,st.file]).pipe(Ue(()=>new URL(cq))),bi=Yt.file.pipe(ns((Is)=>XBt(Is,io))),Cs=Yt.file.pipe(ns((Is)=>Is._tag==="OAuth"&&gO(Is,rr)),ns(()=>ze(Yt.env)||ze(bi))),js=ZQ([Cs,Yt.env,Yt.file]);return yield*tl(`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(Ms(()=>ne(Yt.env)&&ne(Cs))),yield*tl(`Using EXPAND_API_KEY for ${io.origin} because the stored login was issued by a different API origin.`).pipe(Ms(()=>ne(Yt.env)&&ne(bi))),yield*tl(`EXPAND_API_KEY overrides the API key stored in ${n}`).pipe(Ms(()=>ne(Yt.env)&&Rm(Yt.file,(Is)=>Is._tag==="ApiKey"))),{apiUrl:io,authMethod:js,anonymousSession:vt(Fe.anonymousSession),noAnonymous:De}}),j=W("saveConfig")(function*(ce){let De=yield*vo(nm.Json)(ce);yield*O(De)}),F=W("updateConfig")(function*(ce){let De=yield*v,Fe=nm.make({...De.config,...ce}),st=yield*vo(nm.Json)(Fe).pipe(N(Tu(aq))),Yt={...t0t(De.raw,st)};if(Object.hasOwn(ce,"anonymousSession")&&ce.anonymousSession===void 0)delete Yt.anonymousSession;let rr=yield*vo(aq)(Yt);yield*O(rr)});function C(ce){return Q().pipe(be(rm(n,F(ce))))}let R=W("readConfigFile")(function*(){return yield*v.pipe(K(({config:ce})=>({config:ce,parseFailed:!1})),nl(()=>({config:nm.make({}),parseFailed:!0})))}),L=W("clearConfig")(function*(){let ce=yield*jt(v);if(qt(ce)){if(!(ce.left instanceof Ay))return yield*ce.left;yield*tl(`Could not parse ${n}; removing it. Telemetry preferences and apiUrl were not preserved.`),yield*t.remove(n).pipe(fe(()=>new dy({path:n})));return}let De={...ce.right.raw};delete De.authMethod,delete De.anonymousSession;let Fe=yield*vo(aq)(De);yield*O(Fe)});function G(){return Q().pipe(be(rm(n,L())))}let ae=W("getApiUrl")(function*(){let{config:ce}=yield*QPe,De=yield*H,Fe={env:vt(ce.apiUrl),file:vt(De.apiUrl)};return ZQ([Fe.env,Fe.file]).pipe(Ue(()=>new URL(cq)))}),Me=W("getAppUrl")(function*(){return yield*Ht("EXPAND_APP_URL").pipe(yr(YBt))}),He=W("getPlaygroundHost")(function*(){return yield*Ht("EXPAND_PLAYGROUND_HOST").pipe(yr(VC))});return{configPath:n,inspectSecureStorage:B,ensureSecureStorage:Q,loadConfig:T,saveConfig:j,updateConfig:C,clearConfig:G,readConfigFile:R,getApiUrl:ae,getAppUrl:Me,getPlaygroundHost:He}})}){}var ZC="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.",dq="Authorization complete. That setup code has been consumed and cannot be reused.",Aq="Expand is already authorized. Agent setup is complete.",pee="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.",fee="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.",dee="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.",ii=V("claude-code","cursor","opencode","codex","fx");class hq extends Ne("InitDetectionResult")({schemaVersion:V(1),status:V("detected"),harnesses:ve(ii),current:z(ii),userMessage:V(fee,dee)}){}var Aee=eB(ii),Va=V("project","global"),i0t=V("webfetch-hook","runtime-skill","mcp"),s0t=V("unverified","observed","reload_required","blocked"),zhr=V("authorization_required","completed"),a0t=E.pipe(yn(20),wP(256)),c0t=uh(a0t,fh(E),{strict:!0,decode:(e)=>e,encode:()=>"<redacted-redacted-setup-token>"});class mq extends Ne("InitRequest")({harnesses:Aee,scope:Va,setupToken:z(c0t)}){}var l0t=q({schemaVersion:V(1),status:V("authorization_required"),harnesses:Aee,scope:Va,userMessage:V(ZC),authorization:q({url:Kg,userCode:E,approvalExpiresAt:id})}),u0t=q({runtimeState:s0t,nextAction:E}),p0t=q({harness:ii,configured:Ie,changed:Ie,components:ve(i0t),version:E,verification:u0t}),f0t=q({harness:ii,code:E,recoverable:Ie}),d0t=q({schemaVersion:V(1),status:V("completed"),harnesses:Aee,scope:Va,userMessage:V(dq,Aq,pee),auth:q({healthy:Ie}),projectPath:z(E),installations:eB(p0t),failures:z(ve(f0t))}),EO=Je(l0t,d0t);class hy extends Ne("InitErrorEnvelope")({schemaVersion:V(1),status:V("error"),code:E,message:E,recoverable:Ie}){}var Zu="expandai-cli-browser",A0t=q({apiOrigin:E,clientId:V(Zu),purpose:z(V("login","agent-setup")),harness:V("agent-harnesses"),scope:V("project","global"),canonicalScopeRoot:E});class K0 extends Ne("PendingInitRecord")({key:A0t,deviceCode:fh(E),userCode:E,verificationUri:E,intervalSeconds:de,nextPollAt:id,approvalExpiresAt:id}){}class im extends et()("PendingInitCorrupt",{path:E,error:Vt}){recoverable=!0;get message(){return`Pending authorization state at ${this.path} is corrupt and was left unchanged.`}}class hee extends et()("PendingInitStorageError",{path:E,error:Vt}){recoverable=!0;get message(){return`Could not access pending authorization state at ${this.path}.`}}class mee extends Ne("DeviceAuthorizationCreated")({deviceCode:fh(fs),userCode:fs,verificationUri:Kg,expiresIn:hr.pipe(xK()),interval:hr.pipe(o6e())}){}var h0t=q({access_token:fh(fs),refresh_token:fh(fs),token_type:fs,expires_in:de.pipe(xK()),scope:z(E)}),m0t=V("create","poll");class Xu extends et()("DeviceAuthorizationApiError",{operation:m0t,kind:V("request_failed","rejected","invalid_response"),status:z(de),recoverable:Ie}){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 gq extends Ct()("@expandai/cli/Auth/DeviceAuthorizationClient",{dependencies:[Yd,Bt.Default],effect:Y(function*(){let e=yield*Mh,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*FB(new URL("/v1/cli-authorization/device",c)).pipe(yl(a),fe(()=>r("create","request_failed")));return yield*e.execute(l).pipe(N((u)=>Wt(u.status).pipe(Qe((p)=>p>=200&&p<300,()=>Ws(mee)(u).pipe(fe(()=>r("create","invalid_response")))),hd(()=>u.text.pipe(tn,be(r("create","rejected",u.status)))))),Ft((u)=>u instanceof Xu?u:r("create","request_failed")))}),o=q({error:E,error_description:z(E)}),i=new Set(["invalid_target","invalid_client","invalid_scope","unsupported_grant_type","unauthorized_client","invalid_request"]),s=W("DeviceAuthorizationClient.poll")(function*(a){let c=yield*t.getApiUrl(),l=FB(new URL("/api/auth/oauth2/token",c)).pipe(rwe({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:oa(a),client_id:Zu,resource:c.toString()}));return yield*e.execute(l).pipe(N(Ce(function*(u){return yield*Wt(u.status).pipe(Qe((p)=>p>=200&&p<300,()=>Ws(h0t)(u).pipe(fe(()=>r("poll","invalid_response")),K((p)=>({_tag:"Tokens",token:p})))),Qe((p)=>p>=500,()=>u.text.pipe(tn,be(r("poll","rejected",u.status)))),hd(()=>Ws(o)(u).pipe(fe(()=>r("poll","invalid_response")),K((p)=>Wt(p.error).pipe(Qe("authorization_pending",()=>({_tag:"Pending"})),Qe("slow_down",()=>({_tag:"SlowDown"})),Qe("access_denied",()=>({_tag:"Denied"})),Qe("expired_token",()=>({_tag:"Expired"})),hd(()=>i.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:s}})}){}var Si="0.1.6";class DPe extends DS()("DeviceAuthorizationTokensSaved",{}){}class RPe extends DS()("DeviceAuthorizationPending",{}){}class vPe extends DS()("DeviceAuthorizationSlowDown",{}){}class TPe extends DS()("DeviceAuthorizationExpired",{}){}class OPe extends DS()("DeviceAuthorizationInvalid",{}){}class gf extends et()("DeviceAuthorizationDenied",{recoverable:V(!0)}){get message(){return"The authorization request was denied in the browser. Run the same command again to start a new one."}}class sm extends et()("DeviceAuthorizationRefused",{error:E,description:z(E),recoverable:V(!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 am extends et()("DeviceAuthorizationCredentialSaveFailed",{recoverable:V(!1)}){get message(){return"Authorization succeeded, but credentials could not be saved. Start authorization again."}}function kPe(e){return e.platform??process.platform}class XC extends Ct()("@expandai/cli/Auth/DeviceAuthorization",{dependencies:[Bt.Default,gq.Default],effect:Y(function*(){let e=yield*Bt,t=yield*gq,r=W("DeviceAuthorization.create")(function*(i){yield*e.ensureSecureStorage();let s={platform:kPe(i),machineLabel:`${kPe(i)}-${process.arch}`,cliVersion:Si};return yield*i.purpose==="login"?t.create({purpose:"login",harness:"agent-harnesses",scope:"global",...s}):t.create({purpose:"agent-setup",harness:i.harness,scope:i.scope,...s})}),n=Ce(function*(i){let s=yield*fc,a=yield*jt(e.updateConfig({authMethod:mO.make({accessToken:i.access_token,refreshToken:i.refresh_token,expiresAt:zw(s,Yc(i.expires_in)),clientId:Zu})}));return yield*Wn(a,{onLeft:()=>new am({recoverable:!1}),onRight:()=>Z})}),o=W("DeviceAuthorization.poll")(function*(i){let s=yield*t.poll(i);return yield*Wt(s).pipe(xr("Tokens",({token:a})=>n(a).pipe(un(new DPe))),xr("Pending",()=>M(new RPe)),xr("SlowDown",()=>M(new vPe)),xr("Denied",()=>new gf({recoverable:!0})),xr("Expired",()=>M(new TPe)),xr("Invalid",()=>M(new OPe)),xr("Refused",({error:a,description:c})=>new sm({error:a,...c===void 0?{}:{description:c},recoverable:!1})),Sr)});return{create:r,poll:o}})}){}import{createHash as g0t}from"node:crypto";var gee=Nt(K0),E0t=300000,MPe=Nt(Je(BS(E,V(Zu),V("agent-harnesses"),V("project","global"),E),BS(E,V(Zu),V("login"))));function Eee(e,t){return typeof e==="object"&&e!==null&&"code"in e&&e.code===t}function y0t(e){return e instanceof ji&&(e.reason==="AlreadyExists"||Eee(e.cause,"EEXIST"))}function x0t(e){return e instanceof ji&&(e.reason==="NotFound"||Eee(e.cause,"ENOENT"))}function S0t(e){return e.purpose==="login"?Do(MPe)([e.apiOrigin,e.clientId,e.purpose]):Do(MPe)([e.apiOrigin,e.clientId,e.harness,e.scope,e.canonicalScopeRoot])}function _Pe(e,t){let r=e.dirname(t);return r===t?[t]:[t,..._Pe(e,r)]}class cm extends Ct()("@expandai/cli/Auth/PendingInitStore",{dependencies:[Uv],effect:Y(function*(){let e=yield*lr,t=yield*sr,r=t.join(yield*J0,"expandai"),n=t.join(r,"pending-init"),o=(S,Q)=>new hee({path:S,error:Q}),i=(S,Q)=>Q.pipe(fe((I)=>o(S,I))),s=Ce(function*(S){let Q=yield*jt(e.readLink(S));if(vn(Q))return yield*o(S,Error("Symbolic links are not allowed for pending authorization"));let I=Q.left;if(I instanceof ji&&(I.reason==="InvalidData"||I.reason==="NotFound"||I.method==="readLink"&&Eee(I.cause,"EINVAL")))return;return yield*o(S,I)}),a=Ce(function*(){if(yield*s(r),yield*s(n),yield*i(n,e.makeDirectory(n,{recursive:!0,mode:448})),yield*s(r),yield*s(n),(yield*i(n,e.stat(n))).type!=="Directory")return yield*o(n,Error("Pending authorization path is not a directory"));if(process.platform!=="win32")yield*i(r,e.chmod(r,448)),yield*i(n,e.chmod(n,448))}),c=(S)=>{let Q=g0t("sha256").update(S0t(S)).digest("hex");return t.join(n,`${Q}.json`)},l=Ce(function*(S,Q){let I=yield*Tu(gee)(Q).pipe(fe(()=>new im({path:S,error:Error("Stored pending authorization did not match the expected schema")})));if(c(I.key)!==S)return yield*new im({path:S,error:Error("Stored pending authorization key did not match its file")});return I}),u=Ce(function*(S){if(yield*s(S),!(yield*i(S,e.exists(S))))return U();let I=yield*i(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 O=yield*i(S,e.readFileString(S));return P(yield*l(S,O))}),p=(S)=>u(c(S)),f=Ce(function*(S){let Q=wR(yield*fc);return wR(S.approvalExpiresAt)+E0t<=Q}),d=Ce(function*(S){yield*a();let Q=c(S.key),I=yield*vo(gee)(S).pipe(fe((v)=>o(Q,v))),O=yield*jt(Tr(Y(function*(){let v=yield*e.open(Q,{flag:"wx",mode:384});yield*v.writeAll(new TextEncoder().encode(I)),yield*v.sync})));if(qt(O)){if(y0t(O.left))return!1;return yield*e.remove(Q).pipe(tn),yield*o(Q,O.left)}if(process.platform!=="win32"){let v=yield*jt(e.chmod(Q,384));if(qt(v))return yield*e.remove(Q).pipe(tn),yield*o(Q,v.left)}return!0}),A=W("PendingInitStore.replaceIfMatch")(function*(S,Q){yield*a();let I=c(Q.key);if(c(S.key)!==I)return yield*o(I,Error("Pending authorization replacement changed its key"));let O=yield*u(I);if(ze(O)||O.value.userCode!==S.userCode)return!1;let v=yield*vo(gee)(Q).pipe(fe((j)=>o(I,j))),H=`${I}.${process.pid}.${Math.random().toString(36).slice(2,10)}.tmp`,T=yield*Tr(vr(M(H),()=>e.remove(H).pipe(tn)).pipe(be(Y(function*(){yield*s(H),yield*Tr(Y(function*(){let j=yield*e.open(H,{flag:"wx",mode:384});yield*j.writeAll(new TextEncoder().encode(v)),yield*j.sync})),yield*e.rename(H,I)})))).pipe(jt);if(qt(T))return yield*o(I,T.left);return!0}),m=Ce(function*(S){let Q=c(S.key),I=yield*u(Q);if(ze(I)||I.value.userCode!==S.userCode)return!1;return yield*i(Q,e.remove(Q)),!0}),g=W("PendingInitStore.get")(function*(S){let Q=yield*p(S);if(ze(Q)||!(yield*f(Q.value)))return Q;return yield*m(Q.value),U()}),y=W("PendingInitStore.peek")(function*(S){return yield*p(S)}),w=W("PendingInitStore.putIfAbsent")(function*(S){let Q=yield*p(S.key);if(ne(Q)&&!(yield*f(Q.value)))return Q.value;if(ne(Q))yield*m(Q.value);if(yield*d(S))return S;let I=yield*p(S.key);return yield*Te(I,{onNone:()=>o(c(S.key),Error("Pending record creation lost without a winner")),onSome:M})}),b=W("PendingInitStore.removeIfMatch")((S)=>m(S)),D=W("PendingInitStore.removeCorrupt")(function*(S){let Q=c(S),I=yield*jt(u(Q));if(vn(I))return!1;if(!(I.left instanceof im))return yield*I.left;let O=yield*jt(e.remove(Q));if(qt(O)&&x0t(O.left))return!1;if(qt(O))return yield*o(Q,O.left);return!0}),k=W("PendingInitStore.pruneExpired")(function*(){if(yield*s(n),!(yield*i(n,e.exists(n))))return 0;let Q=yield*i(n,e.readDirectory(n));return(yield*ot(Q.filter((O)=>O.endsWith(".json")),(O)=>Y(function*(){let v=yield*u(t.join(n,O));if(ze(v)||!(yield*f(v.value)))return 0;return(yield*m(v.value))?1:0}).pipe(nl(()=>0)))).reduce((O,v)=>O+v,0)}),B=W("PendingInitStore.canonicalScopeRoot")(function*(S,Q=process.cwd()){if(S==="global")return"global";let I=yield*i(Q,e.realPath(Q)),v=(yield*ot(_Pe(t,I),(H)=>i(H,e.exists(t.join(H,".git"))).pipe(K((T)=>({candidate:H,exists:T}))))).find(({exists:H})=>H)?.candidate;return v===void 0?I:yield*i(v,e.realPath(v))});return{pendingPath:n,get:g,peek:y,putIfAbsent:w,replaceIfMatch:A,removeIfMatch:b,removeCorrupt:D,pruneExpired:k,canonicalScopeRoot:B}})}){}var C0t=Zu,I0t=5;class yO extends Ne("ManualAuthorizationInput")({purpose:_(V("login","agent-setup"),{default:()=>"agent-setup"}),harness:V("agent-harnesses"),scope:Va,cwd:z(E),platform:z(E)}){}class yee extends Ne("ManualAuthorizationRequired")({verificationUri:E,userCode:fs,approvalExpiresAt:id}){}class xee extends DS()("TokensSaved",{}){}class my extends DS()("AuthorizationPending",{pending:yee}){}var bmr=Je(xee,my);function Z0(e){return new yee({verificationUri:e.verificationUri,userCode:e.userCode,approvalExpiresAt:e.approvalExpiresAt})}class ep extends Ct()("@expandai/cli/Auth/ManualAuthorization",{dependencies:[Bt.Default,cm.Default,XC.Default],effect:Y(function*(){let e=yield*Bt,t=yield*cm,r=yield*XC,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:C0t,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*fc,A=new K0({key:u,deviceCode:f.deviceCode,userCode:f.userCode,verificationUri:f.verificationUri.toString(),intervalSeconds:f.interval,nextPollAt:zw(d,Yc(f.interval)),approvalExpiresAt:zw(d,Yc(f.expiresIn))}),m=yield*jt(t.putIfAbsent(A));if(qt(m))return yield*m.left;return m.right}),i=Ce(function*(l,u){let p=yield*fc,f=l.intervalSeconds+(u?I0t:0),d=new K0({...l,intervalSeconds:f,nextPollAt:zw(p,Yc(f))}),A=yield*jt(t.replaceIfMatch(l,d));if(qt(A))return l;return A.right?d:l}),s=Ce(function*(l,u){let p=yield*jt(t.get(u));if(vn(p))return p.right;if(l.purpose!=="login"||!(p.left instanceof im))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*s(l,u);if(ze(p)){let g=yield*o(l,u);return new my({pending:Z0(g)})}let f=p.value,d=yield*fc;if(BXe(d,f.approvalExpiresAt)){yield*t.removeIfMatch(f);let g=yield*o(l,u);return new my({pending:Z0(g)})}if(AP(d,f.nextPollAt))return new my({pending:Z0(f)});let A=yield*jt(r.poll(f.deviceCode)),m=Ce(function*(){yield*t.removeIfMatch(f);let g=yield*o(l,u);return new my({pending:Z0(g)})});return yield*Wn(A,{onLeft:(g)=>t.removeIfMatch(f).pipe(Ms(()=>g instanceof gf),be(se(g))),onRight:(g)=>Wt(g).pipe(xr("DeviceAuthorizationTokensSaved",()=>t.removeIfMatch(f).pipe(un(new xee))),xr("DeviceAuthorizationPending",()=>i(f,!1).pipe(K((y)=>new my({pending:Z0(y)})))),xr("DeviceAuthorizationSlowDown",()=>i(f,!0).pipe(K((y)=>new my({pending:Z0(y)})))),xr("DeviceAuthorizationExpired",m),xr("DeviceAuthorizationInvalid",m),Sr)})}),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*Wt(u).pipe(xr("DeviceAuthorizationTokensSaved",()=>Z),xr("DeviceAuthorizationPending",p),xr("DeviceAuthorizationSlowDown",p),xr("DeviceAuthorizationExpired",p),xr("DeviceAuthorizationInvalid",p),Sr)});return{advance:a,redeemPreApproved:c}})}){}var FPe="Authorization complete. Expand is ready to use; retry the command that required authentication.",b0t=V("authorization_internal_error","authorization_unreachable","authorization_rejected","authorization_service_unavailable","authorization_invalid_response","authorization_denied","authorization_refused","credential_save_failed","credential_storage_insecure");class Tc extends et()("DeviceLoginError",{code:b0t,recoverable:Ie,httpStatus:z(de)}){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 yq extends Ne("DeviceLoginErrorEnvelope")({schemaVersion:V(1),status:V("error"),code:E,message:E,recoverable:Ie}){}var w0t=q({schemaVersion:V(1),status:V("authorization_required"),userMessage:V(ZC),authorization:q({url:Kg,userCode:fs,approvalExpiresAt:id})}),B0t=q({schemaVersion:V(1),status:V("completed"),userMessage:V(FPe),auth:q({healthy:V(!0)})}),Eq=Je(w0t,B0t);function Q0t(e){if(e instanceof vc)return new Tc({code:"credential_storage_insecure",recoverable:!1});if(e instanceof gf)return new Tc({code:"authorization_denied",recoverable:!0});if(e instanceof sm)return new Tc({code:"authorization_refused",recoverable:!1});if(e instanceof am)return new Tc({code:"credential_save_failed",recoverable:!1});if(e instanceof Xu)switch(e.kind){case"request_failed":return new Tc({code:"authorization_unreachable",recoverable:!0});case"rejected":if(e.status!==void 0&&e.status>=500)return new Tc({code:"authorization_service_unavailable",recoverable:!0,httpStatus:e.status});return new Tc({code:"authorization_rejected",recoverable:e.recoverable});case"invalid_response":return new Tc({code:"authorization_invalid_response",recoverable:!1})}return new Tc({code:"authorization_internal_error",recoverable:!1})}class xO extends Ct()("@expandai/cli/Auth/DeviceLogin",{dependencies:[ep.Default],effect:Y(function*(){let e=yield*ep;return{run:W("DeviceLogin.run")(function*(){let r=yield*e.advance(new yO({purpose:"login",harness:"agent-harnesses",scope:"global"})).pipe(fe(Q0t));return yield*Wt(r).pipe(xr("TokensSaved",()=>ir(Eq)({schemaVersion:1,status:"completed",userMessage:FPe,auth:{healthy:!0}}).pipe(fe(()=>new Tc({code:"authorization_internal_error",recoverable:!1})))),xr("AuthorizationPending",({pending:n})=>ir(Eq)({schemaVersion:1,status:"authorization_required",userMessage:ZC,authorization:{url:n.verificationUri,userCode:n.userCode,approvalExpiresAt:SS(n.approvalExpiresAt)}}).pipe(fe(()=>new Tc({code:"authorization_internal_error",recoverable:!1})))),Sr)})}})}){}class xq extends et()("SetupGrantAuthorizationError",{code:V("invalid_or_expired","stored_credential_conflict","request_failed","denied","credential_save_failed","refused","config_unreadable"),recoverable:Ie}){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 eI(e){return new xq({code:e,recoverable:e!=="denied"&&e!=="credential_save_failed"&&e!=="refused"})}class X0 extends Ct()("@expandai/cli/Auth/SetupGrantAuthorization",{dependencies:[Bt.Default,ep.Default],effect:Y(function*(){let e=yield*Bt,t=yield*ep;return{authorize:W("SetupGrantAuthorization.authorize")(function*(n){let o=yield*e.readConfigFile();if(o.parseFailed)return yield*eI("config_unreadable");if(o.config.authMethod?._tag==="ApiKey")return yield*eI("stored_credential_conflict");yield*Kx({harness:n.harness,scope:n.scope}),yield*t.redeemPreApproved(n.setupToken).pipe(fe((i)=>{if(i instanceof gf)return eI("denied");if(i instanceof am)return eI("credential_save_failed");if(i instanceof sm)return eI("refused");if(i instanceof Xu&&i.kind==="request_failed")return eI("request_failed");return eI("invalid_or_expired")}))})}})}){}import oHe from"node:process";import _ee from"node:path";import{fileURLToPath as uQt}from"node:url";import pQt from"node:child_process";import fQt,{constants as dQt}from"node:fs/promises";import U0t from"node:path";import{promisify as P0t}from"node:util";import H0t from"node:child_process";import Bee,{constants as zPe}from"node:fs/promises";import UPe from"node:process";import T0t from"node:os";import bee from"node:fs";import R0t from"node:fs";import NPe from"node:fs";var See;function k0t(){try{return NPe.statSync("/.dockerenv"),!0}catch{return!1}}function D0t(){try{return NPe.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}function Cee(){if(See===void 0)See=k0t()||D0t();return See}var Iee,v0t=()=>{try{return R0t.statSync("/run/.containerenv"),!0}catch{return!1}};function tI(){if(Iee===void 0)Iee=v0t()||Cee();return Iee}var LPe=()=>{if(UPe.platform!=="linux")return!1;if(T0t.release().toLowerCase().includes("microsoft")){if(tI())return!1;return!0}try{if(bee.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft"))return!tI()}catch{}if(bee.existsSync("/proc/sys/fs/binfmt_misc/WSLInterop")||bee.existsSync("/run/WSL"))return!tI();return!1},jd=UPe.env.__IS_WSL_TEST__?LPe:LPe();import PPe from"node:process";import{Buffer as O0t}from"node:buffer";import{promisify as M0t}from"node:util";import _0t from"node:child_process";var F0t=M0t(_0t.execFile),wee=()=>`${PPe.env.SYSTEMROOT||PPe.env.windir||String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;var HPe=["-NoProfile","-NonInteractive","-ExecutionPolicy","Bypass","-EncodedCommand"],WPe=(e)=>O0t.from(e,"utf16le").toString("base64"),N0t=(e)=>`'${String(e).replaceAll(/['‘’‚‛]/g,(t)=>t+t)}'`,qPe=(e)=>[...HPe,WPe(e)],L0t=(e)=>({encoding:"utf8",...e,shell:!1}),tp=async(e,t={})=>{let{powerShellPath:r,...n}=t;return F0t(r??wee(),qPe(e),L0t(n))};tp.argumentsPrefix=HPe;tp.encodeCommand=WPe;tp.escapeArgument=N0t;tp.createArguments=qPe;function GPe(e){for(let t of e.split(`
|
|
302
302
|
`)){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 W0t=P0t(H0t.execFile),q0t=(()=>{let t;return async function(){if(t)return t;let r="/etc/wsl.conf",n=!1;try{await Bee.access(r,zPe.F_OK),n=!0}catch{}if(!n)return"/mnt/";let o=await Bee.readFile(r,{encoding:"utf8"}),i=GPe(o);if(i===void 0)return"/mnt/";return t=i,t=t.endsWith("/")?t:`${t}/`,t}})(),G0t=async()=>`${await q0t()}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,Sq=jd?G0t:wee,VPe,YPe=async()=>(VPe??=(async()=>{try{let e=await Sq();return await Bee.access(e,zPe.X_OK),!0}catch{return!1}})(),VPe),jPe=async()=>{let e=await Sq(),t=String.raw`(Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\http\UserChoice").ProgId`,{stdout:r}=await tp(t,{powerShellPath:e,cwd:U0t.dirname(e)});return r.trim()},V0t=(e)=>/^[a-z]+:\/\//i.test(e),z0t=async(e,t)=>{let r=t.startsWith("-")?[e,"--",t]:[e,t];try{let{stdout:n}=await W0t("wslpath",r,{encoding:"utf8"});return n.replace(/\r?\n$/,"")||t}catch{return t}},$Pe=async(e)=>{let t=Array.isArray(e),n=await Promise.all((t?e:[e]).map((o)=>V0t(o)?o:z0t("-aw",o)));return t?n:n[0]};function rI(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 iQt}from"node:util";import vee from"node:process";import{execFile as sQt}from"node:child_process";import{promisify as Y0t}from"node:util";import j0t from"node:process";import{execFile as $0t}from"node:child_process";var J0t=Y0t($0t);async function Qee(){if(j0t.platform!=="darwin")throw Error("macOS only");let{stdout:e}=await J0t("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 K0t from"node:process";import{promisify as Z0t}from"node:util";import{execFile as X0t,execFileSync as ygr}from"node:child_process";var eQt=Z0t(X0t);async function JPe(e,{humanReadableOutput:t=!0,signal:r}={}){if(K0t.platform!=="darwin")throw Error("macOS only");let n=t?[]:["-ss"],o={};if(r)o.signal=r;let{stdout:i}=await eQt("osascript",["-e",e,n],o);return i.trim()}var tQt=/^[^\n\r"\\]+$/u;async function kee(e){if(typeof e!=="string")throw TypeError("Expected a string bundle identifier");if(!tQt.test(e))throw TypeError(`Invalid bundle identifier: ${JSON.stringify(e)}`);return JPe(`tell application "Finder" to set app_path to application file id "${e}" as string
|
|
303
303
|
tell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`)}import KPe from"node:process";import{promisify as rQt}from"node:util";import{execFile as nQt}from"node:child_process";var oQt=rQt(nQt),Cq={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"}},Dee=new Map(Object.entries(Cq));class ZPe extends Error{}async function Ree(e=oQt){let t=`${KPe.env.SYSTEMROOT??KPe.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 ZPe(`Cannot find Windows browser in stdout: ${JSON.stringify(r)}`);let{id:o}=n.groups,i=o.lastIndexOf("."),s=o.lastIndexOf("-"),a=i===-1?void 0:o.slice(0,i),c=s===-1?void 0:o.slice(0,s);return Cq[o]??Cq[a]??Cq[c]??{name:o,id:o}}var aQt=iQt(sQt),cQt=(e)=>e.toLowerCase().replaceAll(/(?:^|\s|-)\S/g,(t)=>t.toUpperCase());async function Tee(){if(vee.platform==="darwin"){let e=await Qee();return{name:await kee(e),id:e}}if(vee.platform==="linux"){let{stdout:e}=await aQt("xdg-mime",["query","default","x-scheme-handler/http"]),t=e.trim();return{name:cQt(t.replace(/.desktop$/,"").replace("-"," ")),id:t}}if(vee.platform==="win32")return Ree();throw Error("Only macOS, Linux, and Windows are supported")}import Oee from"node:process";var lQt=Boolean(Oee.env.SSH_CONNECTION||Oee.env.SSH_CLIENT||Oee.env.SSH_TTY),XPe=lQt;var Iq=Symbol("fallbackAttempt"),Mee=import.meta.url?_ee.dirname(uQt(import.meta.url)):"",eHe=_ee.join(Mee,"xdg-open"),{platform:nI,arch:tHe}=oHe,rHe=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")},bq=async(e)=>{e={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...e};let t=e[Iq]===!0;if(delete e[Iq],Array.isArray(e.app))return rHe(e.app,(l)=>bq({...e,app:l,[Iq]:!0}));let{name:r,arguments:n=[]}=e.app??{};if(n=[...n],Array.isArray(r))return rHe(r,(l)=>bq({...e,app:{name:l,arguments:n},[Iq]:!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(jd){let d=await jPe();p=Dee.get(d)??{}}else p=await Tee();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 bq({...e,app:{name:eQ[d],arguments:n}})}throw Error(`${p.name} is not supported as a default browser`)}let o,i=[],s={},a=!1;if(jd&&!tI()&&!XPe&&!r)a=await YPe();if(nI==="darwin"){if(o="open",e.wait)i.push("--wait-apps");if(e.background)i.push("--background");if(e.newInstance)i.push("--new");if(r)i.push("-a",r)}else if(nI==="win32"||a){if(o=await Sq(),i.push(...tp.argumentsPrefix),!jd)s.windowsVerbatimArguments=!0;if(jd&&e.target)e.target=await $Pe(e.target);let l=["$ProgressPreference = 'SilentlyContinue';","Start"];if(e.wait)l.push("-Wait");if(r){if(l.push(tp.escapeArgument(r)),e.target)n.push(e.target)}else if(e.target)l.push(tp.escapeArgument(e.target));if(n.length>0)n=n.map((u)=>tp.escapeArgument(u)),l.push("-ArgumentList",n.join(","));if(e.target=tp.encodeCommand(l.join(" ")),!e.wait)s.stdio="ignore";if(jd)s.cwd=_ee.dirname(o)}else{if(r)o=r;else{let l=!Mee||Mee==="/",u=!1;try{await fQt.access(eHe,dQt.X_OK),u=!0}catch{}o=oHe.versions.electron??(nI==="android"||l||!u)?"xdg-open":eHe}if(n.length>0)i.push(...n);if(!e.wait)s.stdio="ignore",s.detached=!0}if(nI==="darwin"&&n.length>0)i.push("--args",...n);if(e.target)i.push(e.target);let c=pQt.spawn(o,i,s);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||nI==="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)})})},AQt=(e,t)=>{if(typeof e!=="string")throw TypeError("Expected a `target`");return bq({...t,target:e})};function nHe(e){if(typeof e==="string"||Array.isArray(e))return e;let{[tHe]:t}=e;if(!t)throw Error(`${tHe} is not supported`);return t}function SO({[nI]:e},{wsl:t}={}){if(t&&jd)return nHe(t);if(!e)throw Error(`${nI} is not supported`);return nHe(e)}var eQ={browser:"browser",browserPrivate:"browserPrivate"};rI(eQ,"chrome",()=>SO({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"]}}));rI(eQ,"brave",()=>SO({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"]}}));rI(eQ,"firefox",()=>SO({darwin:"firefox",win32:String.raw`C:\Program Files\Mozilla Firefox\firefox.exe`,linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));rI(eQ,"edge",()=>SO({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));rI(eQ,"safari",()=>SO({darwin:"Safari"}));var iHe=AQt;class sHe extends V("off","compact","detailed"){}class hQt extends q({include:_(E,{nullable:!0}),appendixMarkers:_(sHe,{nullable:!0})}){}class aHe extends V("off","compact","detailed"){}class cHe extends V("auto","never","always"){}class mQt extends Ne("FetchFetchRequest")({url:E,include:_(q({html:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),markdown:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),screenshot:_(Je(Ie,q({fullPage:_(Ie,{nullable:!0})})),{nullable:!0}),links:_(Je(Ie,q({sameDomainOnly:_(Ie,{nullable:!0,default:()=>!0}),includePatterns:_(ve(E),{nullable:!0}),excludePatterns:_(ve(E),{nullable:!0})})),{nullable:!0}),meta:_(Ie,{nullable:!0,default:()=>!0}),response:_(q({includeHeaders:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:_(Ie,{nullable:!0,default:()=>!1}),appendix:_(Ie,{nullable:!0}),appendixMarkers:_(aHe,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),highlights:_(q({query:E,maxResults:_(hr.pipe(Pr(1),sa(50)),{nullable:!0,default:()=>5}),minScore:_(de.pipe(Pr(0),sa(1)),{nullable:!0,default:()=>0.6})}),{nullable:!0}),browserConfig:_(q({scrollFullPage:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:_(q({maxPages:_(hr.pipe(Pr(1)),{nullable:!0}),maxAudioSeconds:_(hr.pipe(Pr(1),sa(14400)),{nullable:!0,default:()=>3600}),ocr:_(cHe,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class lHe extends V("Pointer","Unexpected","Missing","Composite","Refinement","Transformation","Type","Forbidden"){}class uHe extends V("symbol"){}class pHe extends Je(E,de,q({_tag:uHe,key:E})){}class fHe extends q({_tag:lHe,path:ve(pHe),message:E}){}class dHe extends V("HttpApiDecodeError"){}class Ey extends q({issues:ve(fHe),message:E,_tag:dHe}){}class AHe extends V("BadRequest"){}class bO extends q({message:E,_tag:AHe}){}class wq extends Je(Ey,bO){}class hHe extends V("InvalidApiKey","InvalidToken","InvalidSession","InvalidTenant"){}class mHe extends V("AuthFailed"){}class rp extends Ne("AuthFailed")({reason:hHe,description:_(Je(E,q({message:E})),{nullable:!0}),_tag:mHe}){}class wO extends E{}class gHe extends V("FetchBlocked"){}class Bq extends q({url:E,blockedType:_(E,{nullable:!0}),_tag:gHe}){}class Qq extends Je(q({organizationId:E.pipe(yn(1)),blockedUntil:_(Je(wO,Jg),{nullable:!0}),_tag:V("AccessBlocked")}),Bq){}class EHe extends V("FetchOriginHttpError"){}class yHe extends V(404){}class CO extends Ne("FetchOriginNotFound")({_tag:EHe,url:E,statusCode:yHe,contentType:_(E,{nullable:!0})}){}class xHe extends V("FetchOriginHttpError"){}class SHe extends V(410){}class IO extends Ne("FetchOriginGone")({_tag:xHe,url:E,statusCode:SHe,contentType:_(E,{nullable:!0})}){}class CHe extends V("PayloadTooLarge"){}class np extends q({_tag:CHe}){}class IHe extends V("transfer_bytes","domsnapshot_bytes","ast_bytes","document_frame_bytes","document_pages","audio_seconds"){}class bHe extends V("FetchPageTooLarge"){}class kq extends q({url:E,limitKind:_(IHe,{nullable:!0}),limitBytes:_(de,{nullable:!0}),measuredBytes:_(de,{nullable:!0}),limit:_(de,{nullable:!0}),measured:_(de,{nullable:!0}),_tag:bHe}){}class wHe extends Je(np,kq){}class BHe extends V("FetchUnsupportedContentType"){}class tQ extends Ne("FetchUnsupportedContentType")({url:E,contentType:_(E,{nullable:!0}),_tag:BHe}){}class QHe extends V("private","removed","geoRestricted","ageRestricted","membersOnly","live","upcoming","unknown"){}class kHe extends V("FetchVideoUnavailable"){}class rQ extends Ne("FetchVideoUnavailable")({url:E,availability:QHe,message:_(E,{nullable:!0}),_tag:kHe}){}class DHe extends V(!0){}class RHe extends V("TooManyRequests"){}class gy extends q({retryable:_(DHe,{default:()=>!0}),retryAfterSeconds:_(de,{nullable:!0}),_tag:RHe}){}class vHe extends V(!0){}class THe extends V("FetchConcurrencyLimitExceeded"){}class Dq extends q({retryable:_(vHe,{default:()=>!0}),retryAfterSeconds:de,maxConcurrency:de,message:_(E,{nullable:!0}),requestId:_(E,{nullable:!0}),_tag:THe}){}class Rq extends Je(gy,Dq){}class OHe extends V(!0){}class MHe extends V("InternalError"){}class _l extends Ne("InternalError")({retryable:_(OHe,{default:()=>!0}),_tag:MHe}){}class _He extends V("pageNeverSettled","capabilityFailed"){}class FHe extends V(!1){}class NHe extends V("FetchCaptureFailed"){}class vq extends q({url:E,failureType:_He,retryable:_(FHe,{default:()=>!1}),_tag:NHe}){}class LHe extends V("browserInternalDocument"){}class UHe extends V(!1){}class PHe extends V("FetchNavigationFailed"){}class nQ extends q({url:E,failureType:LHe,retryable:_(UHe,{default:()=>!1}),_tag:PHe}){}class HHe extends V("FetchOriginHttpError"){}class Tq extends q({url:E,statusCode:de,contentType:_(E,{nullable:!0}),_tag:HHe}){}class WHe extends Je(vq,nQ,Tq){}class qHe extends V("cancelled_before_start","cancelled_after_start","unknown"){}class GHe extends V(!0){}class VHe extends V("ServiceUnavailable"){}class op extends q({message:_(E,{nullable:!0}),requestId:_(E,{nullable:!0}),dispatchOutcome:_(qHe,{nullable:!0}),retryable:_(GHe,{default:()=>!0}),_tag:VHe}){}class zHe extends V("ocr","transcription","video"){}class YHe extends V("FetchDocumentProcessingUnavailable"){}class Oq extends q({url:E,operation:zHe,message:E,_tag:YHe}){}class jHe extends Je(op,Oq){}class $He extends V(!1){}class JHe extends V("FetchCaptureTimeout"){}class yy extends Ne("FetchCaptureTimeout")({url:E,timeoutMs:_(de,{nullable:!0}),retryable:_($He,{default:()=>!1}),_tag:JHe}){}class KHe extends V(!0){}class ZHe extends V("FetchCapacityTimeout"){}class xy extends Ne("FetchCapacityTimeout")({url:E,timeoutMs:_(de,{nullable:!0}),retryable:_(KHe,{default:()=>!0}),_tag:ZHe}){}class XHe extends V("off","compact","detailed"){}class gQt extends q({include:_(E,{nullable:!0}),appendixMarkers:_(XHe,{nullable:!0})}){}class e1e extends V("off","compact","detailed"){}class t1e extends V("auto","never","always"){}class EQt extends Ne("FetchFetchJsonRequest")({url:E,include:_(q({html:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),markdown:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),screenshot:_(Je(Ie,q({fullPage:_(Ie,{nullable:!0})})),{nullable:!0}),links:_(Je(Ie,q({sameDomainOnly:_(Ie,{nullable:!0,default:()=>!0}),includePatterns:_(ve(E),{nullable:!0}),excludePatterns:_(ve(E),{nullable:!0})})),{nullable:!0}),meta:_(Ie,{nullable:!0,default:()=>!0}),response:_(q({includeHeaders:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:_(Ie,{nullable:!0,default:()=>!1}),appendix:_(Ie,{nullable:!0}),appendixMarkers:_(e1e,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),highlights:_(q({query:E,maxResults:_(hr.pipe(Pr(1),sa(50)),{nullable:!0,default:()=>5}),minScore:_(de.pipe(Pr(0),sa(1)),{nullable:!0,default:()=>0.6})}),{nullable:!0}),browserConfig:_(q({scrollFullPage:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:_(q({maxPages:_(hr.pipe(Pr(1)),{nullable:!0}),maxAudioSeconds:_(hr.pipe(Pr(1),sa(14400)),{nullable:!0,default:()=>3600}),ocr:_(t1e,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class r1e extends V(1){}class lm extends hr{}class n1e extends q({sameDomain:de,external:de}){}class o1e extends q({blocks:de,approxTokens:de}){}class i1e extends q({evidenceId:_(de,{nullable:!0}),links:de,approxTokens:de,label:_(E,{nullable:!0}),preview:_(E,{nullable:!0}),moreBlocks:_(de,{nullable:!0})}){}class s1e extends q({url:E,links:n1e,omitted:_(o1e,{nullable:!0}),markers:_(ve(i1e),{nullable:!0})}){}class a1e extends q({moreTokens:de}){}class c1e extends q({url:E,moreTokens:_(de,{nullable:!0})}){}class l1e extends V(1){}class u1e extends q({version:l1e,snapshotId:E,url:E,markdownUrl:E}){}class Mq extends q({version:r1e,url:E,capturedAt:E,snapshotId:E,lang:E,pageType:E,playground:E,citationEvidenceIds:_(ve(lm).pipe(QP(3)),{nullable:!0}),title:_(E,{nullable:!0}),finalUrl:_(E,{nullable:!0}),contentType:_(E,{nullable:!0}),canonical:_(E,{nullable:!0}),description:_(E,{nullable:!0}),author:_(E,{nullable:!0}),createdAt:_(E,{nullable:!0}),updatedAt:_(E,{nullable:!0}),image:_(E,{nullable:!0}),paginationNext:_(E,{nullable:!0}),appendix:_(s1e,{nullable:!0}),stateJson:_(a1e,{nullable:!0}),markdown:_(c1e,{nullable:!0}),resources:_(u1e,{nullable:!0}),blocked:_(E,{nullable:!0}),loadingStatus:_(E,{nullable:!0})}){}class p1e extends V("inline","network"){}class f1e extends V("ld+json","next-data","nuxt","apollo-state","initial-state","application-json","script-tag","data-attribute","network-json","network-response","other"){}class d1e extends V(!0){}class A1e extends V("invalid","unsafe","too-long"){}class oQ extends q({id:de,kind:p1e,role:f1e,score:de.pipe(Pr(0)),url:_(E,{nullable:!0}),method:_(E,{nullable:!0}),moreTokens:_(de,{nullable:!0}),keys:_(ve(E),{nullable:!0}),urlRedacted:_(d1e,{nullable:!0}),urlOmitted:_(A1e,{nullable:!0})}){}class h1e extends V("data-url"){}class BO extends q({id:E,kind:h1e,placeholder:E,archiveKey:E,mimeType:E,sha256:E,bytes:de}){}class m1e extends V("pageTooLarge","modelInputTooLarge"){}class g1e extends V("domsnapshot_bytes","ast_bytes","document_frame_bytes","hfc_tokens"){}class Fee extends q({reason:m1e,skipped:ve(V("hfc")),limitKind:g1e,measuredBytes:_(hr.pipe(Pr(0)),{nullable:!0}),thresholdBytes:_(hr.pipe(Pr(0)),{nullable:!0}),measuredTokens:_(hr.pipe(Pr(0)),{nullable:!0}),thresholdTokens:_(hr.pipe(Pr(0)),{nullable:!0})}){}class _q extends q({evidenceId:_(lm,{nullable:!0}),markdownBlockId:_(E,{nullable:!0}),nodeIds:_(ve(de),{nullable:!0}),stateJsonSourceId:_(de,{nullable:!0}),jsonPath:_(E,{nullable:!0})}){}class E1e extends V("markdown","appendix","statejson"){}class y1e extends V("zeroentropy","mixedbread","local_lexical"){}class x1e extends V("timeout","error"){}class S1e extends q({source:E1e,chunkCount:hr.pipe(Pr(0)),batchCount:hr.pipe(Pr(0)),ranker:y1e,fallback:Ie,fallbackReason:_(x1e,{nullable:!0}),durationMs:de.pipe(Pr(0))}){}class Fq extends q({durationMs:de.pipe(Pr(0)),sources:ve(S1e)}){}class iQ extends q({query:E,snippets:ve(q({type:_(V("text"),{nullable:!0,default:()=>"text"}),source:V("markdown","appendix","statejson"),text:E,score:de.pipe(Pr(0),sa(1)),location:_(_q,{nullable:!0})})),meta:_(Fq,{nullable:!0})}){}class C1e extends V("youtube"){}class I1e extends V("captions","transcription"){}class b1e extends V("manual","auto"){}class w1e extends V("http"){}class B1e extends V(!1){}class Q1e extends V(!0){}class k1e extends V("FetchOriginError"){}class QO extends q({url:E,kind:w1e,contentAvailable:_(B1e,{nullable:!0}),finalUrl:_(E,{nullable:!0}),redirectLimitReached:_(Q1e,{nullable:!0}),originStatusCode:de,retryable:Ie,_tag:k1e}){}class kO extends q({meta:Mq,markdown:E,json:ve(oQ),data:_(q({assets:_(ve(BO),{nullable:!0}),degraded:_(Fee,{nullable:!0}),highlights:_(iQ,{nullable:!0}),screenshot:_(q({url:E,fullPage:Ie}),{nullable:!0}),document:_(q({url:E,contentType:E,sizeBytes:de}),{nullable:!0}),usage:_(q({documentPages:lm,ocrPages:lm,audioSeconds:de.pipe(Pr(0)),videos:_(lm,{nullable:!0})}),{nullable:!0}),video:_(q({provider:C1e,videoId:E,title:E,channel:_(E,{nullable:!0}),channelUrl:_(E,{nullable:!0}),durationSeconds:_(de,{nullable:!0}),publishedAt:_(E,{nullable:!0}),viewCount:_(de,{nullable:!0}),language:_(E,{nullable:!0}),transcript:q({source:I1e,kind:_(b1e,{nullable:!0}),language:_(E,{nullable:!0})}),segments:_(ve(q({startSeconds:de,text:E})),{nullable:!0}),chapters:_(ve(q({title:E,startSeconds:de})),{nullable:!0}),storyboard:_(q({frameWidth:hr,frameHeight:hr,rows:hr,columns:hr,sheets:ve(q({url:E,durationSeconds:de}))}),{nullable:!0})}),{nullable:!0})}),{nullable:!0}),originError:_(QO,{nullable:!0})}){}class D1e extends V("dns","tls","connectionRefused","connectionReset","connectionClosed","addressUnreachable","emptyResponse","connectionTimeout"){}class R1e extends V("FetchOriginError"){}class DO extends q({url:E,kind:D1e,upstreamError:_(E,{nullable:!0}),retryable:Ie,_tag:R1e}){}class v1e extends V("FetchOriginError"){}class T1e extends V("http"){}class O1e extends V(!1){}class M1e extends V(!0){}class RO extends q({_tag:v1e,url:E,kind:T1e,contentAvailable:O1e,finalUrl:_(E,{nullable:!0}),redirectLimitReached:_(M1e,{nullable:!0}),originStatusCode:de,retryable:Ie}){}class _1e extends Je(kO,DO,RO){}class Nq extends Je(Ey,bO){}class Lq extends Je(q({organizationId:E.pipe(yn(1)),blockedUntil:_(Je(wO,Jg),{nullable:!0}),_tag:V("AccessBlocked")}),Bq){}class Uq extends Je(np,kq){}class Pq extends Je(gy,Dq){}class Hq extends Je(vq,nQ,Tq){}class Wq extends Je(op,Oq){}class yQt extends q({"x-idempotency-key":_(E.pipe(yn(1),wP(255)),{nullable:!0})}){}class F1e extends V("off","compact","detailed"){}class N1e extends V("auto","never","always"){}class xQt extends Ne("FetchBatchedRequest")({urls:eB(E),include:_(q({html:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),markdown:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),screenshot:_(Je(Ie,q({fullPage:_(Ie,{nullable:!0})})),{nullable:!0}),links:_(Je(Ie,q({sameDomainOnly:_(Ie,{nullable:!0,default:()=>!0}),includePatterns:_(ve(E),{nullable:!0}),excludePatterns:_(ve(E),{nullable:!0})})),{nullable:!0}),meta:_(Ie,{nullable:!0,default:()=>!0}),response:_(q({includeHeaders:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:_(Ie,{nullable:!0,default:()=>!1}),appendix:_(Ie,{nullable:!0}),appendixMarkers:_(F1e,{nullable:!0,default:()=>"compact"})}),{nullable:!0}),browserConfig:_(q({scrollFullPage:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),documentConfig:_(q({maxPages:_(hr.pipe(Pr(1)),{nullable:!0}),maxAudioSeconds:_(hr.pipe(Pr(1),sa(14400)),{nullable:!0,default:()=>3600}),ocr:_(N1e,{nullable:!0,default:()=>"auto"})}),{nullable:!0})}){}class L1e extends Ne("BatchedRun")({id:E}){}class U1e extends Je(Ey,bO){}class P1e extends V("AccessBlocked"){}class H1e extends q({organizationId:E.pipe(yn(1)),blockedUntil:_(Je(wO,Jg),{nullable:!0}),_tag:P1e}){}class W1e extends V("payload_mismatch"){}class q1e extends V("BatchedIdempotencyConflict"){}class G1e extends Ne("BatchedIdempotencyConflict")({existingRunId:E,reason:W1e,_tag:q1e}){}class SQt extends q({limit:_(E,{nullable:!0}),offset:_(E,{nullable:!0}),include:_(E,{nullable:!0})}){}class V1e extends V("QUEUED","RUNNING","CANCELLING","COMPLETED","FAILED","CANCELLED"){}class z1e extends V("QUEUED","RUNNING","CANCELLING","COMPLETED","FAILED","CANCELLED"){}class Y1e extends V("QUEUED","RUNNING","SUCCEEDED","FAILED","CANCELLED"){}class j1e extends E{}class oI extends q({url:E,requestedUrl:_(j1e,{nullable:!0}),originStatusCode:_(de,{nullable:!0}),redirectStatusCode:_(de,{nullable:!0}),contentType:_(E,{nullable:!0}),headers:_(q({}),{nullable:!0})}){}class $1e extends q({href:E.pipe(yn(1)),rel:E.pipe(yn(1)),type:_(E.pipe(yn(1)),{nullable:!0}),sizes:_(E.pipe(yn(1)),{nullable:!0})}){}class J1e extends q({url:E.pipe(yn(1)),width:_(de,{nullable:!0}),height:_(de,{nullable:!0}),alt:_(E,{nullable:!0})}){}class K1e extends q({title:_(E,{nullable:!0}),description:_(E,{nullable:!0}),type:_(E.pipe(yn(1)),{nullable:!0}),url:_(E.pipe(yn(1)),{nullable:!0}),siteName:_(E,{nullable:!0}),locale:_(E,{nullable:!0}),images:_(ve(J1e),{nullable:!0})}){}class Z1e extends q({card:_(E.pipe(yn(1)),{nullable:!0}),site:_(E,{nullable:!0}),creator:_(E,{nullable:!0}),title:_(E,{nullable:!0}),description:_(E,{nullable:!0}),image:_(E.pipe(yn(1)),{nullable:!0})}){}class X1e extends q({title:_(E,{nullable:!0}),description:_(E,{nullable:!0}),canonicalUrl:_(E.pipe(yn(1)),{nullable:!0}),language:_(E.pipe(yn(1)),{nullable:!0}),charset:_(E.pipe(yn(1)),{nullable:!0}),favicon:_(E.pipe(yn(1)),{nullable:!0}),icons:_(ve($1e),{nullable:!0}),openGraph:_(K1e,{nullable:!0}),twitter:_(Z1e,{nullable:!0})}){}class Nee extends E.pipe(yn(1)){}class e2e extends V("youtube"){}class t2e extends V("captions","transcription"){}class r2e extends V("manual","auto"){}class n2e extends q({url:E,text:_(E,{nullable:!0})}){}class o2e extends V("rust"){}class i2e extends V("rust"){}class s2e extends V("rust"){}class a2e extends q({capture:_(o2e,{nullable:!0}),markdown:_(i2e,{nullable:!0}),tree:_(s2e,{nullable:!0})}){}class c2e extends q({status:Y1e,data:_(q({response:oI,meta:_(X1e,{nullable:!0}),json:_(ve(q({})),{nullable:!0}),snapshotId:_(Nee,{nullable:!0}),html:_(E.pipe(yn(1)),{nullable:!0}),markdown:_(E.pipe(yn(1)),{nullable:!0}),screenshot:_(q({url:E,fullPage:Ie}),{nullable:!0}),document:_(q({url:E,contentType:E,sizeBytes:de}),{nullable:!0}),usage:_(q({documentPages:lm,ocrPages:lm,audioSeconds:de.pipe(Pr(0)),videos:_(lm,{nullable:!0})}),{nullable:!0}),video:_(q({provider:e2e,videoId:E,title:E,channel:_(E,{nullable:!0}),channelUrl:_(E,{nullable:!0}),durationSeconds:_(de,{nullable:!0}),publishedAt:_(E,{nullable:!0}),viewCount:_(de,{nullable:!0}),language:_(E,{nullable:!0}),transcript:q({source:t2e,kind:_(r2e,{nullable:!0}),language:_(E,{nullable:!0})}),segments:_(ve(q({startSeconds:de,text:E})),{nullable:!0}),chapters:_(ve(q({title:E,startSeconds:de})),{nullable:!0}),storyboard:_(q({frameWidth:hr,frameHeight:hr,rows:hr,columns:hr,sheets:ve(q({url:E,durationSeconds:de}))}),{nullable:!0})}),{nullable:!0}),links:_(ve(n2e),{nullable:!0}),appendix:_(E.pipe(yn(1)),{nullable:!0}),renderEngines:_(a2e,{nullable:!0}),assets:_(ve(BO),{nullable:!0}),degraded:_(Fee,{nullable:!0})}),{nullable:!0}),error:_(Je(Bq,kq,nQ,tQ,Tq,Je(DO,RO),Oq,rQ,vq,yy,xy),{nullable:!0}),originError:_(QO,{nullable:!0})}){}class l2e extends q({total:de,limit:de,offset:de,hasMore:Ie}){}class u2e extends Ne("BatchedStatus")({id:E,status:V1e,batchedStatus:z1e,totalUrls:de,results:ve(c2e),pagination:l2e}){}class p2e extends V("BatchedIncludeUnsupported"){}class f2e extends q({unsupportedFields:ve(E),_tag:p2e}){}class d2e extends Je(Ey,f2e){}class A2e extends V("CANCELLING","CANCELLED"){}class h2e extends Ne("BatchedCancellation")({id:E,status:A2e}){}class m2e extends V("COMPLETED","FAILED"){}class g2e extends V("BatchedCancellationConflict"){}class E2e extends Ne("BatchedCancellationConflict")({id:E,status:m2e,_tag:g2e}){}class y2e extends V("off","compact","detailed"){}class CQt extends Ne("SnapshotHighlightsInput")({highlights:q({query:E,maxResults:_(hr.pipe(Pr(1),sa(50)),{nullable:!0,default:()=>5}),minScore:_(de.pipe(Pr(0),sa(1)),{nullable:!0,default:()=>0.6})}),include:_(q({html:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),markdown:_(Je(Ie,Or({key:E,value:Zt})),{nullable:!0}),screenshot:_(Je(Ie,q({fullPage:_(Ie,{nullable:!0})})),{nullable:!0}),links:_(Je(Ie,q({sameDomainOnly:_(Ie,{nullable:!0,default:()=>!0}),includePatterns:_(ve(E),{nullable:!0}),excludePatterns:_(ve(E),{nullable:!0})})),{nullable:!0}),meta:_(Ie,{nullable:!0,default:()=>!0}),response:_(q({includeHeaders:_(Ie,{nullable:!0,default:()=>!1})}),{nullable:!0}),json:_(Ie,{nullable:!0,default:()=>!1}),appendix:_(Ie,{nullable:!0}),appendixMarkers:_(y2e,{nullable:!0,default:()=>"compact"})}),{nullable:!0})}){}class x2e extends Ne("FetchSnapshotHighlightsResult")({snapshotId:E.pipe(yn(1)),response:oI,highlights:iQ,durationMs:de.pipe(Pr(0)),playground:E}){}class qq extends Je(Ey,bO){}class S2e extends V("AccessBlocked"){}class Gq extends q({organizationId:E.pipe(yn(1)),blockedUntil:_(Je(wO,Jg),{nullable:!0}),_tag:S2e}){}class C2e extends V("FetchSnapshotHighlightsNotFound"){}class Vq extends Ne("FetchSnapshotHighlightsNotFound")({snapshotId:Nee,_tag:C2e}){}class zq extends Je(gy,Dq){}class I2e extends V("json","markdown"){}class IQt extends q({format:_(I2e,{nullable:!0})}){}class b2e extends V(1){}class sQ extends Ne("SnapshotCatalog")({version:b2e,snapshotId:E,collections:q({evidence:E,network:E,assets:E,artifacts:E}),artifacts:ve(q({id:E,kind:E,url:E,preview:_(E,{nullable:!0})})),links:q({markdown:E,json:E})}){}class w2e extends V("SnapshotNotFound"){}class B2e extends Ne("SnapshotNotFound")({snapshotId:E,_tag:w2e}){}var Yq=(e,t={})=>{let r=(i,s)=>N(nl(s.text,()=>"Unexpected status code"),(a)=>se(new Xo({request:i,response:s,reason:"StatusCode",description:a}))),n=(i)=>t.transformClient?t.transformClient(i):M(i),o=(i,s)=>N(Ws(s)(i),se);return{fetchFetch:(i)=>El("POST")("/v1/fetch").pipe(_h({include:i.params.include,appendixMarkers:i.params.appendixMarkers}),(s)=>tr(yl(s,i.payload)),N((s)=>N(n(e),(a)=>N(a.execute(s),xl({"400":(c)=>o(c,wq),"401":(c)=>o(c,rp),"403":(c)=>o(c,Qq),"404":(c)=>o(c,CO),"410":(c)=>o(c,IO),"413":(c)=>o(c,wHe),"415":(c)=>o(c,tQ),"422":(c)=>o(c,rQ),"429":(c)=>o(c,Rq),"500":(c)=>o(c,_l),"502":(c)=>o(c,WHe),"503":(c)=>o(c,jHe),"504":(c)=>o(c,yy),"529":(c)=>o(c,xy),orElse:(c)=>r(s,c)}))))),fetchFetchJson:(i)=>El("POST")("/v1/fetch/json").pipe(_h({include:i.params.include,appendixMarkers:i.params.appendixMarkers}),(s)=>tr(yl(s,i.payload)),N((s)=>N(n(e),(a)=>N(a.execute(s),xl({"200":(c)=>Ws(_1e)(c),"400":(c)=>o(c,Nq),"401":(c)=>o(c,rp),"403":(c)=>o(c,Lq),"404":(c)=>o(c,CO),"410":(c)=>o(c,IO),"413":(c)=>o(c,Uq),"415":(c)=>o(c,tQ),"422":(c)=>o(c,rQ),"429":(c)=>o(c,Pq),"500":(c)=>o(c,_l),"502":(c)=>o(c,Hq),"503":(c)=>o(c,Wq),"504":(c)=>o(c,yy),"529":(c)=>o(c,xy),orElse:(c)=>r(s,c)}))))),fetchBatched:(i)=>El("POST")("/v1/fetch/batched").pipe(d8({"x-idempotency-key":i.params["x-idempotency-key"]??void 0}),(s)=>tr(yl(s,i.payload)),N((s)=>N(n(e),(a)=>N(a.execute(s),xl({"200":(c)=>Ws(L1e)(c),"400":(c)=>o(c,U1e),"401":(c)=>o(c,rp),"403":(c)=>o(c,H1e),"409":(c)=>o(c,G1e),"413":(c)=>o(c,np),"429":(c)=>o(c,gy),"500":(c)=>o(c,_l),"503":(c)=>o(c,op),orElse:(c)=>r(s,c)}))))),fetchGetBatched:(i,s)=>El("GET")(`/v1/fetch/batched/${i}`).pipe(_h({limit:s.limit,offset:s.offset,include:s.include}),M,N((a)=>N(n(e),(c)=>N(c.execute(a),xl({"200":(l)=>Ws(u2e)(l),"400":(l)=>o(l,d2e),"401":(l)=>o(l,rp),"413":(l)=>o(l,np),"429":(l)=>o(l,gy),"500":(l)=>o(l,_l),"503":(l)=>o(l,op),orElse:(l)=>r(a,l)}))))),fetchCancelBatched:(i)=>El("POST")(`/v1/fetch/batched/${i}/cancel`).pipe(M,N((s)=>N(n(e),(a)=>N(a.execute(s),xl({"200":(c)=>Ws(h2e)(c),"400":(c)=>o(c,Ey),"401":(c)=>o(c,rp),"409":(c)=>o(c,E2e),"413":(c)=>o(c,np),"429":(c)=>o(c,gy),"500":(c)=>o(c,_l),"503":(c)=>o(c,op),orElse:(c)=>r(s,c)}))))),snapshotsHighlights:(i,s)=>El("POST")(`/v1/snapshots/${i}/highlights`).pipe((a)=>tr(yl(a,s)),N((a)=>N(n(e),(c)=>N(c.execute(a),xl({"200":(l)=>Ws(x2e)(l),"400":(l)=>o(l,qq),"401":(l)=>o(l,rp),"403":(l)=>o(l,Gq),"404":(l)=>o(l,Vq),"413":(l)=>o(l,np),"429":(l)=>o(l,zq),"500":(l)=>o(l,_l),"503":(l)=>o(l,op),orElse:(l)=>r(a,l)}))))),publicSnapshotsGetCatalog:(i,s)=>El("GET")(`/v1/public/snapshots/${i}`).pipe(_h({format:s.format}),M,N((a)=>N(n(e),(c)=>N(c.execute(a),xl({"200":(l)=>Ws(sQ)(l),"400":(l)=>o(l,Ey),"404":(l)=>o(l,B2e),"413":(l)=>o(l,np),"429":(l)=>o(l,gy),"500":(l)=>o(l,_l),"503":(l)=>o(l,op),orElse:(l)=>r(a,l)})))))}};var bQt=Symbol("DecodedErrorStatus");function aQ(e,t){return N(nl(t.text,()=>"Unexpected status code"),(r)=>se(new Xo({request:e,response:t,reason:"StatusCode",description:r})))}function Wr(e,t){let r=Ws(t)(e),n=e.status===404||e.status===410?r.pipe(Wi("ParseError",()=>aQ(e.request,e))):r;return N(n,(o)=>{if(typeof o==="object"&&o!==null)Object.defineProperty(o,bQt,{value:e.status});return se(o)})}function Lee(e,t){return Ws(t)(e).pipe(Wi("ParseError",(r)=>new cO({message:"Failed to decode the API response",cause:r})))}var wQt=q({...iQ.fields.snippets.value.fields,json:_(Zt,{nullable:!0})}),Q2e=q({...iQ.fields,snippets:ve(wQt)}),BQt=q({...oQ.fields,body:_(Zt,{nullable:!0})});class k2e extends Ne("FetchObjectModeResultWithJson")({...kO.fields,json:ve(BQt),data:_(q({...kO.fields.data.from.fields,highlights:_(Q2e,{nullable:!0})}),{nullable:!0}),originError:_(QO,{nullable:!0})}){}var QQt=Je(k2e,DO,RO);function Sy(e){return"_tag"in e&&e._tag==="FetchOriginError"}class D2e extends Ne("FetchSnapshotHighlightsResultWithJson")({snapshotId:E.pipe(yn(1)),response:oI,highlights:Q2e,durationMs:de.pipe(Pr(0)),playground:E}){}var Uee=(e,t)=>El("POST")("/v1/fetch/json").pipe(_h(t.params.include!==void 0?{include:t.params.include}:{}),(r)=>tr(yl(r,t.payload)),N((r)=>N(e.execute(r),xl({"200":(n)=>Lee(n,QQt),"400":(n)=>Wr(n,Nq),"401":(n)=>Wr(n,rp),"403":(n)=>Wr(n,Lq),"404":(n)=>Wr(n,CO),"410":(n)=>Wr(n,IO),"413":(n)=>Wr(n,Uq),"415":(n)=>Wr(n,tQ),"422":(n)=>Wr(n,rQ),"429":(n)=>Wr(n,Pq),"500":(n)=>Wr(n,_l),"502":(n)=>Wr(n,Hq),"503":(n)=>Wr(n,Wq),"504":(n)=>Wr(n,yy),"529":(n)=>Wr(n,xy),orElse:(n)=>aQ(r,n)})))),R2e=(e,t,r)=>El("POST")(`/v1/snapshots/${encodeURIComponent(t)}/highlights`).pipe((n)=>tr(yl(n,r)),N((n)=>N(e.execute(n),xl({"200":(o)=>Lee(o,D2e),"400":(o)=>Wr(o,qq),"401":(o)=>Wr(o,rp),"403":(o)=>Wr(o,Gq),"404":(o)=>Wr(o,Vq),"413":(o)=>Wr(o,np),"429":(o)=>Wr(o,zq),"500":(o)=>Wr(o,_l),"503":(o)=>Wr(o,op),orElse:(o)=>aQ(n,o)}))));var Pee=class e extends Error{status;text;json;headers;constructor(t,r,n,o,i,s){super(s||`HTTP Error ${t} at ${i}: ${r??JSON.stringify(n)}`);this.url=i,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()]),i=void 0,s=void 0,a=t.headers.get("content-type");if(!t.bodyUsed&&t.body!==null)if(a&&a.includes("application/json"))try{s=await t.json()}catch{i=await t.text()}else i=await t.text();return new e(n,i,s,o,r)}},_2e=class extends Error{constructor(){super("Fetch with backoff aborted");this.name="FetchBackoffAbortError"}},ha=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,i=t.headers.get("content-type");if(!t.bodyUsed&&t.body!==null)if(i&&i.includes("application/json"))try{o=await t.json()}catch{o=await t.text()}else o=await t.text();let s=v2e(n),a=`Durable stream error at ${r}: ${t.statusText||n}`;return new e(a,s,n,o)}static fromFetchError(t){let r=v2e(t.status);return new e(t.message,r,t.status,t.json??t.text)}};function v2e(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 kQt=class extends ha{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 DQt=[429,503],jq={initialDelay:100,maxDelay:60000,multiplier:1.3,maxRetries:1/0};function RQt(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 vQt(e,t=jq){let{initialDelay:r,maxDelay:n,multiplier:o,debug:i=!1,onFailedAttempt:s,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 Pee.fromResponse(d,l.toString())}catch(d){if(s?.(),u?.signal?.aborted)throw new _2e;else if(d instanceof Pee&&!DQt.includes(d.status)&&d.status>=400&&d.status<500)throw d;else{if(f++,f>a){if(i)console.log(`Max retries reached (${f}/${a}), giving up`);throw d}let A=d instanceof Pee?RQt(d.headers["retry-after"]):0,m=Math.random()*p,g=Math.min(m,n),y=Math.max(A,g);if(i){let w=A>0?"server+client":"client";console.log(`Retry attempt #${f} after ${y}ms (${w}, serverMin=${A}ms, clientBackoff=${g}ms)`)}await new Promise((w)=>setTimeout(w,y)),p=Math.min(p*o,n)}}}}function TQt(e){return typeof Symbol<"u"&&typeof Symbol.asyncIterator==="symbol"&&typeof e[Symbol.asyncIterator]==="function"}function OQt(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:s,done:a}=await r.read();if(a)return n=!0,r.releaseLock(),{done:!0,value:void 0};return{done:!1,value:s}}catch(s){n=!0;try{r.releaseLock()}catch{}throw s}finally{o--}},async return(s){if(o>0)throw TypeError("Cannot close a readable stream reader when it has pending read requests");n=!0;let a=r.cancel(s);return r.releaseLock(),await a,{done:!0,value:void 0}},async throw(s){if(o>0)throw TypeError("Cannot close a readable stream reader when it has pending read requests");n=!0;let a=r.cancel(s);throw r.releaseLock(),await a,s},[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 Hee(e){if(!TQt(e))OQt(e);return e}async function*Wee(e,t){let r=e.getReader(),n=new TextDecoder,o="",i={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,`
|
|
304
304
|
`).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.
|
|
4
|
+
"version": "0.1.6",
|
|
5
5
|
"private": false,
|
|
6
6
|
"description": "Unified CLI and MCP server for ExpandAI",
|
|
7
7
|
"author": "ExpandAI",
|
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
"@effect/platform-node": "0.106.0",
|
|
70
70
|
"@effect/vitest": "0.29.0",
|
|
71
71
|
"@expandai/schema-utils": "file:./vendor/schema-utils",
|
|
72
|
-
"@expandai/sdk": "0.20.
|
|
72
|
+
"@expandai/sdk": "0.20.4",
|
|
73
73
|
"@modelcontextprotocol/sdk": "1.29.0",
|
|
74
74
|
"@openai/codex-sdk": "^0.133.0",
|
|
75
75
|
"@opencode-ai/sdk": "1.15.10",
|
|
@@ -86,5 +86,5 @@
|
|
|
86
86
|
"mime": "^4.1.0",
|
|
87
87
|
"ws": "^8.21.0"
|
|
88
88
|
},
|
|
89
|
-
"expandSourceSha": "
|
|
89
|
+
"expandSourceSha": "7882e4eb2760e446c5ce20b83cb9a09f9017e639"
|
|
90
90
|
}
|