shellbell 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,29 @@
1
+ import{spawn as e}from"node:child_process";import t,{accessSync as n,appendFileSync as r,chmodSync as i,closeSync as a,constants as o,existsSync as s,fchmodSync as c,fstatSync as l,fsyncSync as u,ftruncateSync as d,linkSync as f,lstatSync as p,mkdirSync as m,openSync as h,readFileSync as g,readSync as _,readdirSync as v,realpathSync as y,renameSync as b,rmSync as ee,rmdirSync as x,statSync as S,statfsSync as C,unlinkSync as w,writeFileSync as T,writeSync as E}from"node:fs";import{homedir as D,hostname as O,tmpdir as k,userInfo as te}from"node:os";import{basename as A,dirname as j,isAbsolute as M,join as N,normalize as ne,relative as re,resolve as P,sep as ie}from"node:path";import{z as F}from"zod";import{createHash as ae,createHmac as oe,randomBytes as se,randomUUID as ce}from"node:crypto";import{createConnection as le,createServer as ue}from"node:net";import{performance as de}from"node:perf_hooks";const fe=[`Object`,`RegExp`,`Date`,`Error`,`Map`,`Set`,`WeakMap`,`WeakSet`,`ArrayBuffer`,`SharedArrayBuffer`,`DataView`,`Promise`,`URL`,`HTMLElement`,`Int8Array`,`Uint8ClampedArray`,`Int16Array`,`Uint16Array`,`Int32Array`,`Uint32Array`,`Float32Array`,`Float64Array`,`BigInt64Array`,`BigUint64Array`,`Tagged`];function pe(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(e===!0||e===!1)return`boolean`;let t=typeof e;return t===`string`||t===`number`||t===`bigint`||t===`symbol`?t:t===`function`?`Function`:Array.isArray(e)?`Array`:e instanceof Uint8Array?`Uint8Array`:e.constructor===Object?`Object`:me(e)||`Object`}function me(e){let t=Object.prototype.toString.call(e).slice(8,-1);if(fe.includes(t))return t}var I=class{constructor(e,t,n){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=n}toString(){return`Type[${this.major}].${this.name}`}compare(e){return this.major<e.major?-1:+(this.major>e.major)}static equals(e,t){return e===t||e.major===t.major&&e.name===t.name}};I.uint=new I(0,`uint`,!0),I.negint=new I(1,`negint`,!0),I.bytes=new I(2,`bytes`,!0),I.string=new I(3,`string`,!0),I.array=new I(4,`array`,!1),I.map=new I(5,`map`,!1),I.tag=new I(6,`tag`,!1),I.float=new I(7,`float`,!0),I.false=new I(7,`false`,!0),I.true=new I(7,`true`,!0),I.null=new I(7,`null`,!0),I.undefined=new I(7,`undefined`,!0),I.break=new I(7,`break`,!0);var L=class{constructor(e,t,n){this.type=e,this.value=t,this.encodedLength=n,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return`Token[${this.type}].${this.value}`}};const he=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&typeof globalThis.Buffer.isBuffer==`function`,ge=new TextEncoder;function _e(e){return he&&globalThis.Buffer.isBuffer(e)}function ve(e){return e instanceof Uint8Array?_e(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}const ye=he?e=>e.length>=24?globalThis.Buffer.from(e):Te(e):e=>e.length>=200?ge.encode(e):Te(e),be=e=>Uint8Array.from(e),xe=he?(e,t,n)=>_e(e)?new Uint8Array(e.subarray(t,n)):e.slice(t,n):(e,t,n)=>e.slice(t,n),Se=he?(e,t)=>(e=e.map(e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e)),ve(globalThis.Buffer.concat(e,t))):(e,t)=>{let n=new Uint8Array(t),r=0;for(let t of e)r+t.length>n.length&&(t=t.subarray(0,n.length-r)),n.set(t,r),r+=t.length;return n},Ce=he?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function we(e,t){if(_e(e)&&_e(t))return e.compare(t);for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]<t[n]?-1:1;return 0}function Te(e){let t=[],n=0;for(let r=0;r<e.length;r++){let i=e.charCodeAt(r);i<128?t[n++]=i:i<2048?(t[n++]=i>>6|192,t[n++]=i&63|128):(i&64512)==55296&&r+1<e.length&&(e.charCodeAt(r+1)&64512)==56320?(i=65536+((i&1023)<<10)+(e.charCodeAt(++r)&1023),t[n++]=i>>18|240,t[n++]=i>>12&63|128,t[n++]=i>>6&63|128,t[n++]=i&63|128):(i>=55296&&i<=57343&&(i=65533),t[n++]=i>>12|224,t[n++]=i>>6&63|128,t[n++]=i&63|128)}return t}var Ee=class{constructor(e=256){this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),this._initReuseChunk!==null&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}pushByte(e){let t=this.chunks[this.chunks.length-1];this.cursor>this.maxCursor&&(t=Ce(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t));let n=t.length-(this.maxCursor-this.cursor)-1;t[n]=e,this.cursor++}push(e){let t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){let n=t.length-(this.maxCursor-this.cursor)-1;t.set(e,n)}else{if(t){let e=t.length-(this.maxCursor-this.cursor)-1;e<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,e),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=Ce(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,this._initReuseChunk===null&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(e=!1){let t;if(this.chunks.length===1){let n=this.chunks[0];e&&this.cursor>n.length/2?(t=this.cursor===n.length?n:n.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):t=xe(n,0,this.cursor)}else t=Se(this.chunks,this.cursor);return e&&this.reset(),t}},De=class{constructor(e){this.dest=e,this.cursor=0,this.chunks=[e]}reset(){this.cursor=0}pushByte(e){if(this.cursor>=this.dest.length)throw Error(`write out of bounds, destination buffer is too small`);this.dest[this.cursor++]=e}push(e){if(this.cursor+e.length>this.dest.length)throw Error(`write out of bounds, destination buffer is too small`);this.dest.set(e,this.cursor),this.cursor+=e.length}toBytes(e=!1){let t=this.dest.subarray(0,this.cursor);return e&&this.reset(),t}};const R=`CBOR decode error:`,Oe=`CBOR encode error:`;function ke(e,t,n){if(e.length-t<n)throw Error(`${R} not enough data for type`)}const Ae=[24,256,65536,4294967296,BigInt(`18446744073709551616`)];function je(e,t,n){ke(e,t,1);let r=e[t];if(n.strict===!0&&r<Ae[0])throw Error(`${R} integer encoded in more bytes than necessary (strict decode)`);return r}function Me(e,t,n){ke(e,t,2);let r=e[t]<<8|e[t+1];if(n.strict===!0&&r<Ae[1])throw Error(`${R} integer encoded in more bytes than necessary (strict decode)`);return r}function Ne(e,t,n){ke(e,t,4);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(n.strict===!0&&r<Ae[2])throw Error(`${R} integer encoded in more bytes than necessary (strict decode)`);return r}function Pe(e,t,n){ke(e,t,8);let r=e[t]*16777216+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],i=e[t+4]*16777216+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],a=(BigInt(r)<<BigInt(32))+BigInt(i);if(n.strict===!0&&a<Ae[3])throw Error(`${R} integer encoded in more bytes than necessary (strict decode)`);if(a<=2**53-1)return Number(a);if(n.allowBigInt===!0)return a;throw Error(`${R} integers outside of the safe integer range are not supported`)}function Fe(e,t,n,r){return new L(I.uint,je(e,t+1,r),2)}function Ie(e,t,n,r){return new L(I.uint,Me(e,t+1,r),3)}function Le(e,t,n,r){return new L(I.uint,Ne(e,t+1,r),5)}function Re(e,t,n,r){return new L(I.uint,Pe(e,t+1,r),9)}function ze(e,t){return Be(e,0,t.value)}function Be(e,t,n){if(n<Ae[0]){let r=Number(n);e.pushByte(t|r)}else if(n<Ae[1]){let r=Number(n);e.push([t|24,r])}else if(n<Ae[2]){let r=Number(n);e.push([t|25,r>>>8,r&255])}else if(n<Ae[3]){let r=Number(n);e.push([t|26,r>>>24&255,r>>>16&255,r>>>8&255,r&255])}else{let r=BigInt(n);if(r<Ae[4]){let n=[t|27,0,0,0,0,0,0,0],i=Number(r&BigInt(4294967295)),a=Number(r>>BigInt(32)&BigInt(4294967295));n[8]=i&255,i>>=8,n[7]=i&255,i>>=8,n[6]=i&255,i>>=8,n[5]=i&255,n[4]=a&255,a>>=8,n[3]=a&255,a>>=8,n[2]=a&255,a>>=8,n[1]=a&255,e.push(n)}else throw Error(`${R} encountered BigInt larger than allowable range`)}}ze.encodedSize=function(e){return Be.encodedSize(e.value)},Be.encodedSize=function(e){return e<Ae[0]?1:e<Ae[1]?2:e<Ae[2]?3:e<Ae[3]?5:9},ze.compareTokens=function(e,t){return e.value<t.value?-1:+(e.value>t.value)};function Ve(e,t,n,r){return new L(I.negint,-1-je(e,t+1,r),2)}function He(e,t,n,r){return new L(I.negint,-1-Me(e,t+1,r),3)}function Ue(e,t,n,r){return new L(I.negint,-1-Ne(e,t+1,r),5)}const We=BigInt(-1),Ge=BigInt(1);function Ke(e,t,n,r){let i=Pe(e,t+1,r);if(typeof i!=`bigint`){let e=-1-i;if(e>=-(2**53-1))return new L(I.negint,e,9)}if(r.allowBigInt!==!0)throw Error(`${R} integers outside of the safe integer range are not supported`);return new L(I.negint,We-BigInt(i),9)}function qe(e,t){let n=t.value,r=typeof n==`bigint`?n*We-Ge:n*-1-1;Be(e,t.type.majorEncoded,r)}qe.encodedSize=function(e){let t=e.value,n=typeof t==`bigint`?t*We-Ge:t*-1-1;return n<Ae[0]?1:n<Ae[1]?2:n<Ae[2]?3:n<Ae[3]?5:9},qe.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0};function Je(e,t,n,r){ke(e,t,n+r);let i=e.slice(t+n,t+n+r);return new L(I.bytes,i,n+r)}function Ye(e,t,n,r){return Je(e,t,1,n)}function Xe(e,t,n,r){return Je(e,t,2,je(e,t+1,r))}function Ze(e,t,n,r){return Je(e,t,3,Me(e,t+1,r))}function Qe(e,t,n,r){return Je(e,t,5,Ne(e,t+1,r))}function $e(e,t,n,r){let i=Pe(e,t+1,r);if(typeof i==`bigint`)throw Error(`${R} 64-bit integer bytes lengths not supported`);return Je(e,t,9,i)}function et(e){return e.encodedBytes===void 0&&(e.encodedBytes=I.equals(e.type,I.string)?ye(e.value):e.value),e.encodedBytes}function tt(e,t){let n=et(t);Be(e,t.type.majorEncoded,n.length),e.push(n)}tt.encodedSize=function(e){let t=et(e);return Be.encodedSize(t.length)+t.length},tt.compareTokens=function(e,t){return nt(et(e),et(t))};function nt(e,t){return e.length<t.length?-1:e.length>t.length?1:we(e,t)}const rt=new TextDecoder;function it(e,t,n){if(n-t<32){let r=``;for(let i=t;i<n;i++){let a=e[i];if(a&128)return rt.decode(e.subarray(t,n));r+=String.fromCharCode(a)}return r}return rt.decode(e.subarray(t,n))}function at(e,t,n,r,i){let a=n+r;ke(e,t,a);let o=new L(I.string,it(e,t+n,t+a),a);return i.retainStringBytes===!0&&(o.byteValue=e.slice(t+n,t+a)),o}function ot(e,t,n,r){return at(e,t,1,n,r)}function st(e,t,n,r){return at(e,t,2,je(e,t+1,r),r)}function ct(e,t,n,r){return at(e,t,3,Me(e,t+1,r),r)}function lt(e,t,n,r){return at(e,t,5,Ne(e,t+1,r),r)}function ut(e,t,n,r){let i=Pe(e,t+1,r);if(typeof i==`bigint`)throw Error(`${R} 64-bit integer string lengths not supported`);return at(e,t,9,i,r)}const dt=tt;function ft(e,t,n,r){return new L(I.array,r,n)}function pt(e,t,n,r){return ft(e,t,1,n)}function mt(e,t,n,r){return ft(e,t,2,je(e,t+1,r))}function ht(e,t,n,r){return ft(e,t,3,Me(e,t+1,r))}function gt(e,t,n,r){return ft(e,t,5,Ne(e,t+1,r))}function _t(e,t,n,r){let i=Pe(e,t+1,r);if(typeof i==`bigint`)throw Error(`${R} 64-bit integer array lengths not supported`);return ft(e,t,9,i)}function vt(e,t,n,r){if(r.allowIndefinite===!1)throw Error(`${R} indefinite length items not allowed`);return ft(e,t,1,1/0)}function yt(e,t){Be(e,I.array.majorEncoded,t.value)}yt.compareTokens=ze.compareTokens,yt.encodedSize=function(e){return Be.encodedSize(e.value)};function bt(e,t,n,r){return new L(I.map,r,n)}function xt(e,t,n,r){return bt(e,t,1,n)}function St(e,t,n,r){return bt(e,t,2,je(e,t+1,r))}function Ct(e,t,n,r){return bt(e,t,3,Me(e,t+1,r))}function wt(e,t,n,r){return bt(e,t,5,Ne(e,t+1,r))}function Tt(e,t,n,r){let i=Pe(e,t+1,r);if(typeof i==`bigint`)throw Error(`${R} 64-bit integer map lengths not supported`);return bt(e,t,9,i)}function Et(e,t,n,r){if(r.allowIndefinite===!1)throw Error(`${R} indefinite length items not allowed`);return bt(e,t,1,1/0)}function Dt(e,t){Be(e,I.map.majorEncoded,t.value)}Dt.compareTokens=ze.compareTokens,Dt.encodedSize=function(e){return Be.encodedSize(e.value)};function Ot(e,t,n,r){return new L(I.tag,n,1)}function kt(e,t,n,r){return new L(I.tag,je(e,t+1,r),2)}function At(e,t,n,r){return new L(I.tag,Me(e,t+1,r),3)}function jt(e,t,n,r){return new L(I.tag,Ne(e,t+1,r),5)}function Mt(e,t,n,r){return new L(I.tag,Pe(e,t+1,r),9)}function Nt(e,t){Be(e,I.tag.majorEncoded,t.value)}Nt.compareTokens=ze.compareTokens,Nt.encodedSize=function(e){return Be.encodedSize(e.value)};function Pt(e,t,n,r){if(r.allowUndefined===!1)throw Error(`${R} undefined values are not supported`);return r.coerceUndefinedToNull===!0?new L(I.null,null,1):new L(I.undefined,void 0,1)}function Ft(e,t,n,r){if(r.allowIndefinite===!1)throw Error(`${R} indefinite length items not allowed`);return new L(I.break,void 0,1)}function It(e,t,n){if(n){if(n.allowNaN===!1&&Number.isNaN(e))throw Error(`${R} NaN values are not supported`);if(n.allowInfinity===!1&&(e===1/0||e===-1/0))throw Error(`${R} Infinity values are not supported`)}return new L(I.float,e,t)}function Lt(e,t,n,r){return It(Gt(e,t+1),3,r)}function Rt(e,t,n,r){return It(qt(e,t+1),5,r)}function zt(e,t,n,r){return It(Yt(e,t+1),9,r)}function Bt(e,t,n){let r=t.value;if(r===!1)e.pushByte(I.float.majorEncoded|20);else if(r===!0)e.pushByte(I.float.majorEncoded|21);else if(r===null)e.pushByte(I.float.majorEncoded|22);else if(r===void 0)e.pushByte(I.float.majorEncoded|23);else{let t,i=!1;(!n||n.float64!==!0)&&(Wt(r),t=Gt(Ut,1),r===t||Number.isNaN(r)?(Ut[0]=249,e.push(Ut.slice(0,3)),i=!0):(Kt(r),t=qt(Ut,1),r===t&&(Ut[0]=250,e.push(Ut.slice(0,5)),i=!0))),i||(Jt(r),t=Yt(Ut,1),Ut[0]=251,e.push(Ut.slice(0,9)))}}Bt.encodedSize=function(e,t){let n=e.value;if(n===!1||n===!0||n==null)return 1;if(!t||t.float64!==!0){Wt(n);let e=Gt(Ut,1);if(n===e||Number.isNaN(n))return 3;if(Kt(n),e=qt(Ut,1),n===e)return 5}return 9};const Vt=new ArrayBuffer(9),Ht=new DataView(Vt,1),Ut=new Uint8Array(Vt,0);function Wt(e){if(e===1/0)Ht.setUint16(0,31744,!1);else if(e===-1/0)Ht.setUint16(0,64512,!1);else if(Number.isNaN(e))Ht.setUint16(0,32256,!1);else{Ht.setFloat32(0,e);let t=Ht.getUint32(0),n=(t&2139095040)>>23,r=t&8388607;if(n===255)Ht.setUint16(0,31744,!1);else if(n===0)Ht.setUint16(0,(t&2147483648)>>16|r>>13,!1);else{let e=n-127;e<-24?Ht.setUint16(0,0):e<-14?Ht.setUint16(0,(t&2147483648)>>16|1<<24+e,!1):Ht.setUint16(0,(t&2147483648)>>16|e+15<<10|r>>13,!1)}}}function Gt(e,t){if(e.length-t<2)throw Error(`${R} not enough data for float16`);let n=(e[t]<<8)+e[t+1];if(n===31744)return 1/0;if(n===64512)return-1/0;if(n===32256)return NaN;let r=n>>10&31,i=n&1023,a;return a=r===0?i*2**-24:r===31?i===0?1/0:NaN:(i+1024)*2**(r-25),n&32768?-a:a}function Kt(e){Ht.setFloat32(0,e,!1)}function qt(e,t){if(e.length-t<4)throw Error(`${R} not enough data for float32`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,4).getFloat32(0,!1)}function Jt(e){Ht.setFloat64(0,e,!1)}function Yt(e,t){if(e.length-t<8)throw Error(`${R} not enough data for float64`);let n=(e.byteOffset||0)+t;return new DataView(e.buffer,n,8).getFloat64(0,!1)}function Xt(e,t){let n=e.value;if(n===!1)return Uint8Array.of(I.float.majorEncoded|20);if(n===!0)return Uint8Array.of(I.float.majorEncoded|21);if(n===null)return Uint8Array.of(I.float.majorEncoded|22);if(n===void 0)return Uint8Array.of(I.float.majorEncoded|23);if(!t){if(Wt(n),n===Gt(Ut,1)||Number.isNaN(n))return Ut[0]=249,Ut.slice(0,3);if(Kt(n),n===qt(Ut,1))return Ut[0]=250,Ut.slice(0,5)}return Jt(n),Ut[0]=251,Ut.slice(0,9)}function Zt(e,t){let n=e,r=t?.float64===!0,i=r?n._keyBytesFloat64:n._keyBytes;if(i!==void 0)return i;let a=Xt(e,r);return r?n._keyBytesFloat64=a:n._keyBytes=a,a}Bt.compareTokens=function(e,t,n){let r=Zt(e,n),i=Zt(t,n);return r.length===i.length?we(r,i):r.length<i.length?-1:1};function z(e,t,n){throw Error(`${R} encountered invalid minor (${n}) for major ${e[t]>>>5}`)}function Qt(e){return()=>{throw Error(`${R} ${e}`)}}const B=[];for(let e=0;e<=23;e++)B[e]=z;B[24]=Fe,B[25]=Ie,B[26]=Le,B[27]=Re,B[28]=z,B[29]=z,B[30]=z,B[31]=z;for(let e=32;e<=55;e++)B[e]=z;B[56]=Ve,B[57]=He,B[58]=Ue,B[59]=Ke,B[60]=z,B[61]=z,B[62]=z,B[63]=z;for(let e=64;e<=87;e++)B[e]=Ye;B[88]=Xe,B[89]=Ze,B[90]=Qe,B[91]=$e,B[92]=z,B[93]=z,B[94]=z,B[95]=Qt(`indefinite length bytes/strings are not supported`);for(let e=96;e<=119;e++)B[e]=ot;B[120]=st,B[121]=ct,B[122]=lt,B[123]=ut,B[124]=z,B[125]=z,B[126]=z,B[127]=Qt(`indefinite length bytes/strings are not supported`);for(let e=128;e<=151;e++)B[e]=pt;B[152]=mt,B[153]=ht,B[154]=gt,B[155]=_t,B[156]=z,B[157]=z,B[158]=z,B[159]=vt;for(let e=160;e<=183;e++)B[e]=xt;B[184]=St,B[185]=Ct,B[186]=wt,B[187]=Tt,B[188]=z,B[189]=z,B[190]=z,B[191]=Et;for(let e=192;e<=215;e++)B[e]=Ot;B[216]=kt,B[217]=At,B[218]=jt,B[219]=Mt,B[220]=z,B[221]=z,B[222]=z,B[223]=z;for(let e=224;e<=243;e++)B[e]=Qt(`simple values are not supported`);B[244]=z,B[245]=z,B[246]=z,B[247]=Pt,B[248]=Qt(`simple values are not supported`),B[249]=Lt,B[250]=Rt,B[251]=zt,B[252]=z,B[253]=z,B[254]=z,B[255]=Ft;const $t=[];for(let e=0;e<24;e++)$t[e]=new L(I.uint,e,1);for(let e=-1;e>=-24;e--)$t[31-e]=new L(I.negint,e,1);$t[64]=new L(I.bytes,new Uint8Array,1),$t[96]=new L(I.string,``,1),$t[128]=new L(I.array,0,1),$t[160]=new L(I.map,0,1),$t[244]=new L(I.false,!1,1),$t[245]=new L(I.true,!0,1),$t[246]=new L(I.null,null,1);function en(e){switch(e.type){case I.false:return be([244]);case I.true:return be([245]);case I.null:return be([246]);case I.bytes:return e.value.length?void 0:be([64]);case I.string:return e.value===``?be([96]):void 0;case I.array:return e.value===0?be([128]):void 0;case I.map:return e.value===0?be([160]):void 0;case I.uint:return e.value<24?be([Number(e.value)]):void 0;case I.negint:if(e.value>=-24)return be([31-Number(e.value)])}}const tn={float64:!1,mapSorter:fn,quickEncodeToken:en},nn=Object.freeze({mapSorter:pn,quickEncodeToken:en});function rn(){let e=[];return e[I.uint.major]=ze,e[I.negint.major]=qe,e[I.bytes.major]=tt,e[I.string.major]=dt,e[I.array.major]=yt,e[I.map.major]=Dt,e[I.tag.major]=Nt,e[I.float.major]=Bt,e}const an=rn(),on=new Ee;var sn=class e{constructor(e,t){this.obj=e,this.parent=t}includes(e){let t=this;do if(t.obj===e)return!0;while(t=t.parent);return!1}static createCheck(t,n){if(t&&t.includes(n))throw Error(`${Oe} object contains circular references`);return new e(n,t)}};const cn={null:new L(I.null,null),undefined:new L(I.undefined,void 0),true:new L(I.true,!0),false:new L(I.false,!1),emptyArray:new L(I.array,0),emptyMap:new L(I.map,0)},ln={number(e,t,n,r){return!Number.isInteger(e)||!Number.isSafeInteger(e)?new L(I.float,e):e>=0?new L(I.uint,e):new L(I.negint,e)},bigint(e,t,n,r){return e>=BigInt(0)?new L(I.uint,e):new L(I.negint,e)},Uint8Array(e,t,n,r){return new L(I.bytes,e)},string(e,t,n,r){return new L(I.string,e)},boolean(e,t,n,r){return e?cn.true:cn.false},null(e,t,n,r){return cn.null},undefined(e,t,n,r){return cn.undefined},ArrayBuffer(e,t,n,r){return new L(I.bytes,new Uint8Array(e))},DataView(e,t,n,r){return new L(I.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength))},Array(e,t,n,r){if(!e.length)return n.addBreakTokens===!0?[cn.emptyArray,new L(I.break)]:cn.emptyArray;r=sn.createCheck(r,e);let i=[],a=0;for(let t of e)i[a++]=un(t,n,r);return n.addBreakTokens?[new L(I.array,e.length),i,new L(I.break)]:[new L(I.array,e.length),i]},Object(e,t,n,r){let i=t!==`Object`,a=i?e.keys():Object.keys(e),o=i?e.size:a.length,s;if(o){s=Array(o),r=sn.createCheck(r,e);let t=!i&&n.ignoreUndefinedProperties,c=0;for(let o of a){let a=i?e.get(o):e[o];t&&a===void 0||(s[c++]=[un(o,n,r),un(a,n,r)])}c<o&&(s.length=c)}return s?.length?(dn(s,n),n.addBreakTokens?[new L(I.map,s.length),s,new L(I.break)]:[new L(I.map,s.length),s]):n.addBreakTokens===!0?[cn.emptyMap,new L(I.break)]:cn.emptyMap},Tagged(e,t,n,r){return[new L(I.tag,e.tag),un(e.value,n,r)]}};ln.Map=ln.Object,ln.Buffer=ln.Uint8Array;for(let e of`Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64`.split(` `))ln[`${e}Array`]=ln.DataView;function un(e,t={},n){let r=pe(e),i=t&&t.typeEncoders&&t.typeEncoders[r]||ln[r];if(typeof i==`function`){let a=i(e,r,t,n);if(a!=null)return a}let a=ln[r];if(!a)throw Error(`${Oe} unsupported type: ${r}`);return a(e,r,t,n)}function dn(e,t){let n=t.mapSorter;n&&e.sort((e,r)=>n(e,r,t))}function fn(e,t,n){let r=Array.isArray(e[0])?e[0][0]:e[0],i=Array.isArray(t[0])?t[0][0]:t[0];if(r.type.major!==i.type.major)return r.type.compare(i.type);let a=r.type.major,o=an[a].compareTokens(r,i,n);return o===0&&console.warn(`WARNING: complex key types used, CBOR key sorting guarantees are gone`),o}function pn(e,t){if(e[0]instanceof L&&t[0]instanceof L){let n=e[0],r=t[0];return n._keyBytes||=mn(n.value),r._keyBytes||=mn(r.value),we(n._keyBytes,r._keyBytes)}throw Error(`rfc8949MapSorter: complex key types are not supported yet`)}function mn(e){return Mn(e,an,nn)}function hn(e,t,n,r){if(Array.isArray(t))for(let i of t)hn(e,i,n,r);else n[t.type.major](e,t,r)}const gn=I.uint.majorEncoded,_n=I.negint.majorEncoded,vn=I.bytes.majorEncoded,yn=I.string.majorEncoded,bn=I.array.majorEncoded,xn=I.map.majorEncoded,Sn=I.float.majorEncoded|20,Cn=I.float.majorEncoded|21,wn=I.float.majorEncoded|22,Tn=I.float.majorEncoded|23,En=BigInt(-1),Dn=BigInt(1);function On(e,t,n){n<24?e.pushByte(t|Number(n)):Be(e,t,n)}function kn(e){return e.addBreakTokens!==!0}function An(e,t,n,r,i){let a=n===`Map`,o=a?t.keys():Object.keys(t),s=a?t.size:o.length;if(!s){e.pushByte(xn);return}i=sn.createCheck(i,t);let c=!a&&r.ignoreUndefinedProperties,l=Array(s),u=0;for(let e of o){let n=a?t.get(e):t[e];c&&n===void 0||(l[u++]=[un(e,r,i),n])}if(u===0){e.pushByte(xn);return}u<s&&(l.length=u),l.sort((e,t)=>fn(e,t,r)),On(e,xn,u);for(let[t,n]of l)hn(e,t,an,r),jn(e,n,r,i)}function jn(e,t,n,r){let i=pe(t),a=n.typeEncoders&&n.typeEncoders[i];if(a){let o=a(t,i,n,r);if(o!=null){hn(e,o,an,n);return}}switch(i){case`null`:e.pushByte(wn);return;case`undefined`:e.pushByte(Tn);return;case`boolean`:e.pushByte(t?Cn:Sn);return;case`number`:!Number.isInteger(t)||!Number.isSafeInteger(t)?Bt(e,new L(I.float,t),n):t>=0?On(e,gn,t):On(e,_n,t*-1-1);return;case`bigint`:t>=BigInt(0)?On(e,gn,t):On(e,_n,t*En-Dn);return;case`string`:{let n=ye(t);On(e,yn,n.length),e.push(n);return}case`Uint8Array`:On(e,vn,t.length),e.push(t);return;case`Array`:if(!t.length){e.pushByte(bn);return}r=sn.createCheck(r,t),On(e,bn,t.length);for(let i of t)jn(e,i,n,r);return;case`Object`:case`Map`:n.mapSorter===fn?An(e,t,i,n,r):hn(e,ln.Object(t,i,n,r),an,n);return;default:{let a=ln[i];if(!a)throw Error(`${Oe} unsupported type: ${i}`);hn(e,a(t,i,n,r),an,n)}}}function Mn(e,t,n,r){let i=r instanceof Uint8Array,a=i?new De(r):on,o=un(e,n);if(!Array.isArray(o)&&n.quickEncodeToken){let e=n.quickEncodeToken(o);if(e)return i?(a.push(e),a.toBytes()):e;let r=t[o.type.major];if(r.encodedSize){let e=r.encodedSize(o,n);if(i||(a=new Ee(e)),r(a,o,n),a.chunks.length!==1)throw Error(`Unexpected error: pre-calculated length for ${o} was wrong`);return i?a.toBytes():ve(a.chunks[0])}}return a.reset(),hn(a,o,t,n),a.toBytes(!0)}function Nn(e,t){return t=Object.assign({},tn,t),kn(t)?(on.reset(),jn(on,e,t,void 0),on.toBytes(!0)):Mn(e,an,t)}const Pn={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};var Fn=class{constructor(e,t={}){this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){let e=this.data[this._pos],t=$t[e];if(t===void 0){let n=B[e];if(!n)throw Error(`${R} no decoder for major type ${e>>>5} (byte 0x${e.toString(16).padStart(2,`0`)})`);let r=e&31;t=n(this.data,this._pos,r,this.options)}return this._pos+=t.encodedLength,t}};const In=Symbol.for(`DONE`),Ln=Symbol.for(`BREAK`);function Rn(e,t,n){let r=[];for(let i=0;i<e.value;i++){let a=Hn(t,n);if(a===Ln){if(e.value===1/0)break;throw Error(`${R} got unexpected break to lengthed array`)}if(a===In)throw Error(`${R} found array but not enough entries (got ${i}, expected ${e.value})`);r[i]=a}return r}function zn(e,t,n){let r=n.useMaps===!0,i=n.rejectDuplicateMapKeys===!0,a=r?void 0:{},o=r?new Map:void 0;for(let s=0;s<e.value;s++){let c=Hn(t,n);if(c===Ln){if(e.value===1/0)break;throw Error(`${R} got unexpected break to lengthed map`)}if(c===In)throw Error(`${R} found map but not enough entries (got ${s} [no key], expected ${e.value})`);if(!r&&typeof c!=`string`)throw Error(`${R} non-string keys not supported (got ${typeof c})`);if(i&&(r&&o.has(c)||!r&&Object.hasOwn(a,c)))throw Error(`${R} found repeat map key "${c}"`);let l=Hn(t,n);if(l===In)throw Error(`${R} found map but not enough entries (got ${s} [no value], expected ${e.value})`);r?o.set(c,l):c===`__proto__`?Object.defineProperty(a,c,{value:l,configurable:!0,enumerable:!0,writable:!0}):a[c]=l}return r?o:a}function*Bn(e,t,n){for(let r=0;r<e.value;r++){let i=Hn(t,n);if(i===Ln){if(e.value===1/0)break;throw Error(`${R} got unexpected break to lengthed map`)}if(i===In)throw Error(`${R} found map but not enough entries (got ${r} [no key], expected ${e.value})`);let a=Hn(t,n);if(a===In)throw Error(`${R} found map but not enough entries (got ${r} [no value], expected ${e.value})`);yield[i,a]}}function Vn(e,t){let n=function(){if(n._called)throw Error(`${R} tag decode() may only be called once`);n._called=!0;let r=Hn(e,t);if(r===In)throw Error(`${R} tag content missing`);if(r===Ln)throw Error(`${R} got unexpected break in tag content`);return r};return n.entries=function(){if(n._called)throw Error(`${R} tag decode() may only be called once`);n._called=!0;let r=e.next();if(!I.equals(r.type,I.map))throw Error(`${R} entries() requires map content, got ${r.type.name}`);let i=[];for(let n of Bn(r,e,t))i.push(n);return i},n._called=!1,n}function Hn(e,t){if(e.done())return In;let n=e.next();if(I.equals(n.type,I.break))return Ln;if(n.type.terminal)return n.value;if(I.equals(n.type,I.array))return Rn(n,e,t);if(I.equals(n.type,I.map))return zn(n,e,t);if(I.equals(n.type,I.tag)){if(t.tags&&typeof t.tags[n.value]==`function`){let r=Vn(e,t),i=t.tags[n.value](r);if(!r._called)throw Error(`${R} tag decoder must call decode() or entries()`);return i}throw Error(`${R} tag not supported (${n.value})`)}throw Error(`unsupported`)}function Un(e,t){if(!(e instanceof Uint8Array))throw Error(`${R} data to decode must be a Uint8Array`);t=Object.assign({},Pn,t);let n=ve(e),r=t.tokenizer||new Fn(n,t),i=Hn(r,t);if(i===In)throw Error(`${R} did not find any content to decode`);if(i===Ln)throw Error(`${R} got unexpected break`);return[i,e.subarray(r.pos())]}function Wn(e,t){let[n,r]=Un(e,t);if(r.length>0)throw Error(`${R} too many terminals, data makes no sense`);return n}Object.defineProperty(class e{constructor(e,t){if(typeof e!=`number`||!Number.isInteger(e)||e<0)throw TypeError(`Tagged: tag must be a non-negative integer`);this.tag=e,this.value=t}static decoder(t){return n=>new e(t,n())}static preserve(...t){let n={};for(let r of t)n[r]=e.decoder(r);return n}}.prototype,Symbol.toStringTag,{value:`Tagged`});var V=class extends Error{code;constructor(e,t){super(t?`${e}: ${t}`:e),this.code=e,this.name=`ProtocolError`}};function H(e){return Nn(e,{ignoreUndefinedProperties:!0})}function Gn(e){try{return Wn(e,{rejectDuplicateMapKeys:!0})}catch(e){throw new V(`malformed`,e.message)}}function Kn(e,t){try{let n=new Fn(e,{retainStringBytes:!0});return Wn(e,{rejectDuplicateMapKeys:!0,tokenizer:{done:()=>n.done(),pos:()=>n.pos(),next:()=>{let e=n.next();if(e.type!==I.string||e.value===``&&e.encodedLength===1)return e;if(!e.byteValue)throw new V(`malformed`);return new L(I.string,t(e.byteValue),e.encodedLength)}}})}catch{throw new V(`malformed`)}}const qn={unauth:4096,ctrl:16384,e2eFromPhone:65536,e2eFromAgent:1048576},Jn=61e3,U=e=>F.custom(t=>t instanceof Uint8Array&&(e===void 0||t.length===e),{message:e===void 0?`expected bytes`:`expected ${e} bytes`}),W=F.string().regex(/^[a-z2-7]{26}$/,`fingerprint`),Yn=F.object({v:F.literal(1),t:F.enum([`ctrl`,`e2e`]),from:F.union([W,F.literal(`relay`)]),to:W.optional(),seq:F.number().int().nonnegative(),body:F.unknown()}).refine(e=>e.t!==`e2e`||e.to!==void 0,{message:`e2e envelope needs to`}),Xn=F.object({v:F.literal(2),t:F.literal(`e2e`),from:W,to:W,body:F.custom(e=>e instanceof Uint8Array&&e.length>0&&e.length<=61e3,{message:`v2 opaque frame must be 1–61,000 bytes`})}).strict(),Zn=F.object({n:U(24),c:U()});function Qn(e){return H(e)}function $n(e){let t=Xn.safeParse(e);if(!t.success)throw new V(`malformed`,F.prettifyError(t.error));let n=H(t.data);if(n.length>qn.e2eFromPhone)throw new V(`malformed`,`v2 relay envelope too large`);return n}function er(e){let t=Gn(e),n=typeof t==`object`&&t&&!Array.isArray(t)&&`v`in t&&t.v===2?Xn.safeParse(t):Yn.safeParse(t);if(!n.success)throw new V(`malformed`,F.prettifyError(n.error));return n.data}const tr=F.string().min(1).max(128),nr=[`continuation-v1`,`source-status-v1`,`checkpoint-v1`,`applied-v1`],rr=`native-history-v1`,ir=F.array(F.string().min(1).max(64)).max(16),G={envelopeBytes:32768,chunkBytes:16384,screenBytes:524288,historyBytes:65536,historyLines:200,historyCells:4096,chunks:32,unacked:4,progressMs:5e3,totalMs:15e3,ackDelayMs:500,cols:512,rows:256,runs:32768,codePoints:131072,cacheLines:5e3,cacheBytes:4194304},K=F.string().regex(/^[A-Za-z0-9_-]{22}$/),ar=F.number().int().min(0).max(2**53-1),or=F.number().int().min(1).max(2**53-1),sr=F.discriminatedUnion(`kind`,[F.strictObject({kind:F.literal(`snapshot`),generation:ar}),F.strictObject({kind:F.literal(`diff`),generation:ar}),F.strictObject({kind:F.literal(`history`),generation:ar,requestId:K,before:ar,capture:K.optional()}),F.strictObject({kind:F.literal(`vt-state`),generation:ar,cols:F.number().int().min(1).max(G.cols),rows:F.number().int().min(1).max(G.rows)}),F.strictObject({kind:F.literal(`vt`),generation:ar,offset:ar}),F.strictObject({kind:F.literal(`vt-seed`),generation:ar,cols:F.number().int().min(1).max(G.cols),rows:F.number().int().min(1).max(G.rows),capture:K,disposition:F.enum([`initial`,`discontinuity`,`replace`]),reason:F.enum([`start`,`resize`,`reconnect`,`refresh`,`overflow`,`herdr-idle`,`source-gap`]),cursor:F.enum([`real`,`guessed`,`unknown`]),alternate:F.enum([`real`,`unknown`]),historyBefore:ar.optional(),historyRows:F.number().int().min(0).max(2e3).optional(),historyProof:F.string().regex(/^[a-f0-9]{64}$/).optional()}).refine(e=>{let{historyBefore:t,historyRows:n,historyProof:r}=e;return t===void 0||n===void 0||r===void 0?t===void 0&&n===void 0&&r===void 0:e.disposition!==`discontinuity`&&t<=2**53-1-n})]),cr=F.object({type:F.literal(`stream.chunk`),subscriptionId:K,transferId:K,sessionId:tr,sequence:or,index:F.number().int().min(0).max(G.chunks-1),count:F.number().int().min(1).max(G.chunks),totalBytes:or.max(G.screenBytes),data:U(),meta:sr}).superRefine((e,t)=>{let n=e.meta.kind===`history`?G.historyBytes:G.screenBytes;e.totalBytes>n&&t.addIssue({code:`custom`,path:[`totalBytes`],message:`transfer exceeds kind limit`});let r=Math.ceil(e.totalBytes/G.chunkBytes);e.count!==r&&t.addIssue({code:`custom`,path:[`count`],message:`chunk count mismatch`}),e.index>=e.count&&t.addIssue({code:`custom`,path:[`index`],message:`chunk index exceeds count`});let i=e.index===e.count-1?e.totalBytes-e.index*G.chunkBytes:G.chunkBytes;e.data.length!==i&&t.addIssue({code:`custom`,path:[`data`],message:`chunk payload length mismatch`})}),lr=F.discriminatedUnion(`type`,[F.object({type:F.literal(`stream.subscribe`),subscriptionId:K,sessionId:tr,mode:F.literal(`vt`).optional(),extensions:ir.optional(),retained:F.boolean().optional()}),F.object({type:F.literal(`stream.accepted`),subscriptionId:K,extensions:ir}),F.object({type:F.literal(`stream.applied`),subscriptionId:K,capture:K,generation:ar,offset:ar}),F.object({type:F.literal(`stream.status`),subscriptionId:K,capture:K,generation:ar,offset:ar,state:F.enum([`quiescent`,`catching-up`,`paused`])}),F.object({type:F.literal(`stream.cancel`),subscriptionId:K}),F.object({type:F.literal(`stream.refresh`),subscriptionId:K,history:F.literal(!0).optional()}),F.object({type:F.literal(`stream.ack`),subscriptionId:K,through:or}),F.object({type:F.literal(`stream.history.get`),subscriptionId:K,requestId:K,before:ar,count:F.number().int().min(1).max(G.historyLines),capture:K.optional(),generation:ar.optional()}).refine(e=>e.capture===void 0==(e.generation===void 0)),F.object({type:F.literal(`stream.error`),subscriptionId:K,code:F.enum([`screen-too-large`,`history-unavailable`,`history-reset`,`history-line-too-large`,`stalled`,`invalid-transfer`,`unsupported`,`session-gone`]),requestId:K.optional(),historyReason:F.literal(`fetch-window`).optional()}),cr]);function ur(){throw new V(`malformed`)}function dr(e,t){for(let n=0;n<e.length;){let r=e[n++];if(r===void 0&&ur(),r<128){t?.(r);continue}let i=r>=194&&r<=223?2:r>=224&&r<=239?3:r>=240&&r<=244?4:0;(i===0||n+i-1>e.length)&&ur();let a=e[n++];(a===void 0||a<128||a>191)&&ur(),(r===224&&a<160||r===237&&a>159||r===240&&a<144||r===244&&a>143)&&ur();let o=(r&(i===2?31:i===3?15:7))<<6|a&63;for(let t=2;t<i;t++){let t=e[n++];(t===void 0||t<128||t>191)&&ur(),o=o<<6|t&63}t?.(o)}}function fr(e){let t=[],n=[],r=()=>{n.length>0&&(t.push(String.fromCharCode(...n)),n.length=0)};return dr(e,e=>{if(e<=65535)n.push(e);else{let t=e-65536;n.push(55296|t>>>10,56320|t&1023)}n.length>=4096&&r()}),r(),t.join(``)}function pr(e,t){let n=0,r=[{remaining:1,map:!1}];for(;r.length>0;){let i=r[r.length-1];if(i||ur(),i.remaining===0){r.pop();continue}n>=e.length&&ur();let a=i.map&&i.remaining%2==0;i.remaining--;let o=e[n++];o===void 0&&ur();let s=o>>>5,c=o&31;if(a&&s!==3&&ur(),s===7){c!==20&&c!==21&&ur();continue}s!==0&&s!==1&&s!==3&&s!==4&&s!==5&&!(t&&s===2)&&ur(),c>=28&&ur();let l;if(c<24)l=BigInt(c);else{let t=c===24?1:c===25?2:c===26?4:8;t>e.length-n&&ur(),l=0n;for(let r=0;r<t;r++)l=l<<8n|BigInt(e[n++]??ur())}if(s===0||s===1){let e=BigInt(2**53-1-(s===1));l>e&&ur();continue}l>BigInt(e.length-n)&&ur();let u=Number(l);if(s===3||s===2){s===3&&dr(e.subarray(n,n+u)),n+=u;continue}let d=s===5?u*2:u;(d>e.length-n||r.length>12)&&ur(),r.push({remaining:d,map:s===5})}n!==e.length&&ur()}function mr(e,t,n={}){return(!(e instanceof Uint8Array)||!Number.isSafeInteger(t)||t<1||t>G.screenBytes||e.length===0||e.length>t)&&ur(),pr(e,n.allowBytes===!0),Kn(e,fr)}const hr=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`,gr=new Map([...hr].map((e,t)=>[e,t])),_r=`abcdefghijklmnopqrstuvwxyz234567`;function vr(e){return new TextEncoder().encode(e)}function yr(e){let t=``,n=0;for(;n+2<e.length;n+=3){let r=e[n]<<16|e[n+1]<<8|e[n+2];t+=hr[r>>18&63]+hr[r>>12&63]+hr[r>>6&63]+hr[r&63]}if(n<e.length){let r=e[n],i=n+1<e.length?e[n+1]:0,a=r<<16|i<<8;t+=hr[a>>18&63]+hr[a>>12&63],n+1<e.length&&(t+=hr[a>>6&63])}return t}function br(e){if(!/^[A-Za-z0-9_-]*$/.test(e))throw Error(`invalid base64url`);let t=[],n=0,r=0;for(let i of e)r=(r<<6|gr.get(i))&16777215,n+=6,n>=8&&(n-=8,t.push(r>>n&255));return new Uint8Array(t)}function xr(e){let t=``,n=0,r=0;for(let i of e)for(r=(r<<8|i)&65535,n+=8;n>=5;)n-=5,t+=_r[r>>n&31];return n>0&&(t+=_r[r<<5-n&31]),t}function Sr(e){let t=``;for(let n of e)t+=n.toString(16).padStart(2,`0`);return t}function Cr(e){if(e.length%2!=0||!/^[0-9a-fA-F]*$/.test(e))throw Error(`invalid hex`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=Number.parseInt(e.slice(n*2,n*2+2),16);return t}function wr(...e){let t=e.reduce((e,t)=>e+t.length,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function Tr(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}const Er=`conversation-v1`,Dr={envelopeBytes:32768,batchBytes:31744,entriesPerBatch:64,textBytes:16384,detailBytes:8192,queuedBytes:262144,retainedEntries:2e3,retainedBytes:4194304,progressMs:5e3,queuedItems:8,queuedChars:500},Or=new TextEncoder,kr=e=>F.string().max(e).refine(t=>Or.encode(t).byteLength<=e),Ar=F.number().int().nonnegative().max(2**53-1),jr={subscriptionId:K},Mr={...jr,generation:K},Nr=F.enum([`complete`,`unloaded`,`truncated`,`unlinked`]),Pr=F.strictObject({text:F.string().min(1).max(Dr.queuedChars).optional(),attachment:F.literal(!0).optional()}).refine(e=>e.text!==void 0||e.attachment===!0,`empty queued message`),Fr=F.strictObject({id:K,kind:F.enum([`user`,`assistant`,`tool-call`,`tool-result`,`status`,`group`,`unsupported`]),text:kr(Dr.textBytes),detail:kr(Dr.detailBytes).optional(),collapsed:F.boolean().optional(),truncated:F.boolean().optional()}),Ir=F.strictObject({type:F.literal(`conversation.batch`),...Mr,batchId:K,baseRevision:Ar,revision:Ar,operation:F.enum([`reset`,`patch`,`prepend`]),anchor:K.nullable().optional(),after:K.nullable().optional(),requestId:K.optional(),entries:F.array(Fr).max(Dr.entriesPerBatch),olderCursor:K.nullable().optional(),history:Nr.optional()}).superRefine((e,t)=>{let n=e=>t.addIssue({code:`custom`,message:e});(e.baseRevision===2**53-1||e.revision!==e.baseRevision+1)&&n(`conversation revision must advance exactly once`),new Set(e.entries.map(e=>e.id)).size!==e.entries.length&&n(`duplicate conversation entry ID`),e.operation===`reset`?(e.baseRevision!==0||e.anchor!==void 0||e.requestId!==void 0)&&n(`invalid initial conversation batch`):((e.baseRevision===0||e.anchor===void 0)&&n(`conversation update requires an applied base and anchor`),e.operation===`prepend`&&(e.anchor===null||!e.requestId||e.entries.length===0)&&n(`older conversation page requires a request, anchor and entries`),e.operation===`patch`&&e.requestId!==void 0&&n(`live conversation update cannot satisfy a history request`)),e.operation===`patch`&&e.anchor!==null&&(e.olderCursor!==void 0||e.history!==void 0)&&n(`a live suffix update cannot replace the retained older boundary`),e.olderCursor===void 0!=(e.history===void 0)&&n(`history and its cursor must be described together`),e.history===`complete`&&e.olderCursor!==null&&n(`complete conversation history cannot have an older cursor`),e.operation!==`patch`&&e.after!==void 0&&n(`only live updates can retain a suffix`),e.after&&(e.after===e.anchor||e.entries.some(t=>t.id===e.after))&&n(`a retained suffix must be outside the incoming range`),e.operation!==`patch`&&(e.olderCursor===void 0||e.history===void 0)&&n(`conversation page must describe its older boundary`),e.anchor&&e.entries.some(t=>t.id===e.anchor)&&n(`conversation anchor must precede incoming entries`),H(e).byteLength>Dr.batchBytes&&n(`conversation batch exceeds envelope budget`)}),Lr=F.discriminatedUnion(`type`,[F.strictObject({type:F.literal(`conversation.subscribe`),...jr,sessionId:tr}),F.strictObject({type:F.literal(`conversation.cancel`),...jr}),F.strictObject({type:F.literal(`conversation.refresh`),...jr}),F.strictObject({type:F.literal(`conversation.status`),...jr,state:F.enum([`checking`,`ready`,`disabled`,`unavailable`]),reason:F.enum([`unbound`,`unsupported`,`source`,`busy`]).optional(),caughtUp:F.boolean().optional(),queued:F.array(Pr).max(Dr.queuedItems).optional(),chat:F.string().min(1).max(32).optional()}).superRefine((e,t)=>{e.caughtUp!==void 0&&e.state!==`ready`&&t.addIssue({code:`custom`,message:`only ready conversation can report progress`}),e.queued!==void 0&&e.state!==`ready`&&t.addIssue({code:`custom`,message:`only ready conversation can report a queue`}),e.chat!==void 0&&e.state!==`ready`&&t.addIssue({code:`custom`,message:`only ready conversation names its chat`})}),F.strictObject({type:F.literal(`conversation.clear`),...jr,clearId:K,reason:F.enum([`disabled`,`changed`,`unavailable`,`skipped`,`ended`])}),F.strictObject({type:F.literal(`conversation.cleared`),...jr,clearId:K}),Ir,F.strictObject({type:F.literal(`conversation.applied`),...Mr,batchId:K,revision:Ar.min(1),oldestId:K.nullable(),newestId:K.nullable(),retainedCount:F.number().int().nonnegative().max(Dr.retainedEntries)}).superRefine((e,t)=>{(e.retainedCount===0!=(e.oldestId===null&&e.newestId===null)||e.retainedCount>0&&(!e.oldestId||!e.newestId)||e.retainedCount===1&&e.oldestId!==e.newestId||e.retainedCount>1&&e.oldestId===e.newestId)&&t.addIssue({code:`custom`,message:`invalid retained conversation boundary`})}),F.strictObject({type:F.literal(`conversation.history.get`),...Mr,requestId:K,cursor:K}),F.strictObject({type:F.literal(`conversation.history.end`),...Mr,requestId:K,reason:F.enum([`complete`,`unavailable`,`changed`,`busy`])})]);
2
+ /*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
3
+ function Rr(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const zr=e=>e?`"${e}" `:``;function Br(e,t=``){if(typeof e!=`boolean`)throw TypeError(zr(t)+`expected boolean, got type=`+typeof e);return e}function Vr(e,t=``){if(typeof e!=`number`)throw TypeError(zr(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(zr(t)+`expected integer >= 0, got `+e);return e}function Hr(e,t,n=``){if(Rr(e)&&(t===void 0||e.length===t))return e;t!==void 0&&Vr(t,`length`);let r=Rr(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=zr(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}const Ur=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`)};function Wr(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function Gr(e,t){Hr(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function Kr(e,t){if(Gr(e,t),!ui(e))throw Error(`invalid output, must be aligned`)}function qr(e){return new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}function Jr(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Yr(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Xr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}const Zr=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Qr(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}const $r=Zr?e=>e:e=>Qr(e)>>>0;function ei(e){for(let t=0;t<e.length;t++)e[t]=Qr(e[t]);return e}const ti=Zr?e=>e:ei;function ni(e,t){return!e.byteLength||!t.byteLength?!1:e.buffer===t.buffer&&e.byteOffset<t.byteOffset+t.byteLength&&t.byteOffset<e.byteOffset+e.byteLength}function ri(e,t){if(ni(e,t)&&e.byteOffset<t.byteOffset)throw Error(`complex overlap of input and output is not supported`)}function ii(e,t){return Ur(e,`defaults`),Ur(t,`opts`),Object.assign(e,t)}function ai(e,t){if(e=Hr(e),t=Hr(t),e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r++)n|=e[r]^t[r];return n===0}function oi(e,t,n){let r=t,i=n||(()=>[]),a=(e,t)=>r(t,...i(e)).update(e).digest(),o=r(new Uint8Array(e),...i(new Uint8Array));return a.outputLen=o.outputLen,a.blockLen=o.blockLen,a.create=(e,...t)=>r(e,...t),a}const si=(e,t)=>{function n(n,...r){if(Hr(n,void 0,`key`),e.nonceLength!==void 0){let t=r[0];Hr(t,e.varSizeNonce?void 0:e.nonceLength,`nonce`)}let i=e.tagLength,a=e.nonceLength===void 0?0:1;if(!e.withAAD){for(let e=a;e<r.length;e++)if(Rr(r[e]))throw Error(`AAD not supported`)}e.withAAD&&r[a]!==void 0&&Hr(r[a],void 0,`AAD`);let o=t(n,...r),s=(e,t)=>{if(t!==void 0){if(e!==2)throw Error(`cipher output not supported`);Hr(t,void 0,`output`)}},c=!1;return{encrypt(e,t){if(c)throw Error(`cannot encrypt() twice with same key + nonce`);return c=!0,Hr(e,void 0,`data`),s(o.encrypt.length,t),o.encrypt(e,t)},decrypt(e,t){if(Hr(e,void 0,`data`),i&&e.length<i)throw Error(`"ciphertext" expected length >= tagLength=`+i);return s(o.decrypt.length,t),o.decrypt(e,t)}}}return Object.assign(n,e),n};function ci(e,t,n=!0){if(t===void 0)return new Uint8Array(e);if(Hr(t,e,`output`),n&&!ui(t))throw Error(`invalid output, must be aligned`);return t}function li(e,t,n){Vr(e),Vr(t),Br(n);let r=new Uint8Array(16),i=Xr(r);return i.setBigUint64(0,BigInt(t),n),i.setBigUint64(8,BigInt(e),n),r}function ui(e){return e.byteOffset%4==0}function di(e){return Uint8Array.from(Hr(e))}const fi=e=>Uint8Array.from(e.split(``),e=>e.charCodeAt(0)),pi=ti(Jr(fi(`expand 16-byte k`))),mi=ti(Jr(fi(`expand 32-byte k`)));function q(e,t){return e<<t|e>>>32-t}const hi=2**32-1,gi=Uint32Array.of();function _i(e,t,n,r,i,a,o,s){let c=i.length,l=new Uint8Array(64),u=Jr(l),d=Zr&&ui(i)&&ui(a),f=d?Jr(i):gi,p=d?Jr(a):gi;if(!Zr){for(let d=0;d<c;o++){if(e(t,n,r,u,o,s),ti(u),o>=hi)throw Error(`arx: counter overflow`);let f=Math.min(64,c-d);for(let e=0,t;e<f;e++)t=d+e,a[t]=i[t]^l[e];d+=f}return}for(let m=0;m<c;o++){if(e(t,n,r,u,o,s),o>=hi)throw Error(`arx: counter overflow`);let h=Math.min(64,c-m);if(d&&h===64){let e=m/4;if(m%4!=0)throw Error(`arx: invalid block position`);for(let t=0,n;t<16;t++)n=e+t,p[n]=f[n]^u[t];m+=64;continue}for(let e=0,t;e<h;e++)t=m+e,a[t]=i[t]^l[e];m+=h}}function vi(e,t){let{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:a,rounds:o}=ii({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if(typeof e!=`function`)throw Error(`core must be a function`);return Vr(i),Vr(o),Br(a),Br(n),(t,s,c,l,u=0)=>{Hr(t,void 0,`key`),Hr(s,void 0,`nonce`),Hr(c,void 0,`data`);let d=c.length,f=l!==void 0;if(l=ci(d,l,!1),f&&ri(c,l),Vr(u),u<0||u>=hi)throw Error(`arx: counter overflow`);let p=[],m=t.length,h,g;if(m===32)p.push(h=di(t)),g=mi;else if(m===16&&n)h=new Uint8Array(32),h.set(t),h.set(t,16),g=pi,p.push(h);else throw Hr(t,32,`arx key`),Error(`invalid key size`);(!Zr||!ui(s))&&p.push(s=di(s));let _=Jr(h);if(r){if(s.length!==24)throw Error(`arx: extended nonce must be 24 bytes`);let e=s.subarray(0,16);if(Zr)r(g,_,Jr(e),_);else{let t=ti(Uint32Array.from(g));r(t,_,Jr(e),_),Yr(t),ti(_)}s=s.subarray(16)}else Zr||ti(_);let v=16-i;if(v!==s.length)throw Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){let e=new Uint8Array(12);e.set(s,a?0:12-s.length),s=e,p.push(s)}let y=ti(Jr(s));try{return _i(e,g,_,y,c,l,u,o),l}finally{Yr(...p)}}}function yi(e,t){return e[t++]&255|(e[t++]&255)<<8}var bi=class{blockLen=16;outputLen=16;buffer=new Uint8Array(16);r=new Uint16Array(10);h=new Uint16Array(10);pad=new Uint16Array(8);pos=0;finished=!1;destroyed=!1;constructor(e){e=di(Hr(e,32,`key`));let t=yi(e,0),n=yi(e,2),r=yi(e,4),i=yi(e,6),a=yi(e,8),o=yi(e,10),s=yi(e,12),c=yi(e,14);this.r[0]=t&8191,this.r[1]=(t>>>13|n<<3)&8191,this.r[2]=(n>>>10|r<<6)&7939,this.r[3]=(r>>>7|i<<9)&8191,this.r[4]=(i>>>4|a<<12)&255,this.r[5]=a>>>1&8190,this.r[6]=(a>>>14|o<<2)&8191,this.r[7]=(o>>>11|s<<5)&8065,this.r[8]=(s>>>8|c<<8)&8191,this.r[9]=c>>>5&127;for(let t=0;t<8;t++)this.pad[t]=yi(e,16+2*t)}process(e,t,n=!1){let r=n?0:2048,{h:i,r:a}=this,o=a[0],s=a[1],c=a[2],l=a[3],u=a[4],d=a[5],f=a[6],p=a[7],m=a[8],h=a[9],g=yi(e,t+0),_=yi(e,t+2),v=yi(e,t+4),y=yi(e,t+6),b=yi(e,t+8),ee=yi(e,t+10),x=yi(e,t+12),S=yi(e,t+14),C=i[0]+(g&8191),w=i[1]+((g>>>13|_<<3)&8191),T=i[2]+((_>>>10|v<<6)&8191),E=i[3]+((v>>>7|y<<9)&8191),D=i[4]+((y>>>4|b<<12)&8191),O=i[5]+(b>>>1&8191),k=i[6]+((b>>>14|ee<<2)&8191),te=i[7]+((ee>>>11|x<<5)&8191),A=i[8]+((x>>>8|S<<8)&8191),j=i[9]+(S>>>5|r),M=0,N=M+C*o+5*h*w+5*m*T+5*p*E+5*f*D;M=N>>>13,N&=8191,N+=5*d*O+5*u*k+5*l*te+5*c*A+5*s*j,M+=N>>>13,N&=8191;let ne=M+C*s+w*o+5*h*T+5*m*E+5*p*D;M=ne>>>13,ne&=8191,ne+=5*f*O+5*d*k+5*u*te+5*l*A+5*c*j,M+=ne>>>13,ne&=8191;let re=M+C*c+w*s+T*o+5*h*E+5*m*D;M=re>>>13,re&=8191,re+=5*p*O+5*f*k+5*d*te+5*u*A+5*l*j,M+=re>>>13,re&=8191;let P=M+C*l+w*c+T*s+E*o+5*h*D;M=P>>>13,P&=8191,P+=5*m*O+5*p*k+5*f*te+5*d*A+5*u*j,M+=P>>>13,P&=8191;let ie=M+C*u+w*l+T*c+E*s+D*o;M=ie>>>13,ie&=8191,ie+=5*h*O+5*m*k+5*p*te+5*f*A+5*d*j,M+=ie>>>13,ie&=8191;let F=M+C*d+w*u+T*l+E*c+D*s;M=F>>>13,F&=8191,F+=O*o+5*h*k+5*m*te+5*p*A+5*f*j,M+=F>>>13,F&=8191;let ae=M+C*f+w*d+T*u+E*l+D*c;M=ae>>>13,ae&=8191,ae+=O*s+k*o+5*h*te+5*m*A+5*p*j,M+=ae>>>13,ae&=8191;let oe=M+C*p+w*f+T*d+E*u+D*l;M=oe>>>13,oe&=8191,oe+=O*c+k*s+te*o+5*h*A+5*m*j,M+=oe>>>13,oe&=8191;let se=M+C*m+w*p+T*f+E*d+D*u;M=se>>>13,se&=8191,se+=O*l+k*c+te*s+A*o+5*h*j,M+=se>>>13,se&=8191;let ce=M+C*h+w*m+T*p+E*f+D*d;M=ce>>>13,ce&=8191,ce+=O*u+k*l+te*c+A*s+j*o,M+=ce>>>13,ce&=8191,M=(M<<2)+M|0,M=M+N|0,N=M&8191,M>>>=13,ne+=M,i[0]=N,i[1]=ne,i[2]=re,i[3]=P,i[4]=ie,i[5]=F,i[6]=ae,i[7]=oe,i[8]=se,i[9]=ce}finalize(){let{h:e,pad:t}=this,n=new Uint16Array(10),r=e[1]>>>13;e[1]&=8191;for(let t=2;t<10;t++)e[t]+=r,r=e[t]>>>13,e[t]&=8191;e[0]+=r*5,r=e[0]>>>13,e[0]&=8191,e[1]+=r,r=e[1]>>>13,e[1]&=8191,e[2]+=r,n[0]=e[0]+5,r=n[0]>>>13,n[0]&=8191;for(let t=1;t<10;t++)n[t]=e[t]+r,r=n[t]>>>13,n[t]&=8191;n[9]-=8192;let i=(r^1)-1;for(let e=0;e<10;e++)n[e]&=i;i=~i;for(let t=0;t<10;t++)e[t]=e[t]&i|n[t];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let a=e[0]+t[0];e[0]=a&65535;for(let n=1;n<8;n++)a=(e[n]+t[n]|0)+(a>>>16)|0,e[n]=a&65535;Yr(n)}update(e){Wr(this),Hr(e),e=di(e);let{buffer:t,blockLen:n}=this,r=e.length;for(let i=0;i<r;){let a=Math.min(n-this.pos,r-i);if(a===n){for(;n<=r-i;i+=n)this.process(e,i);continue}t.set(e.subarray(i,i+a),this.pos),this.pos+=a,i+=a,this.pos===n&&(this.process(t,0,!1),this.pos=0)}return this}destroy(){this.destroyed=!0,Yr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Wr(this),Gr(e,this),this.finished=!0;let{buffer:t,h:n}=this,{pos:r}=this;if(r){for(t[r++]=1;r<16;r++)t[r]=0;this.process(t,0,!0)}this.finalize();let i=0;for(let t=0;t<8;t++)e[i++]=n[t]>>>0,e[i++]=n[t]>>>8}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}};const xi=oi(32,e=>new bi(e));function Si(e,t,n,r,i,a=20){let o=e[0],s=e[1],c=e[2],l=e[3],u=t[0],d=t[1],f=t[2],p=t[3],m=t[4],h=t[5],g=t[6],_=t[7],v=i,y=n[0],b=n[1],ee=n[2],x=o,S=s,C=c,w=l,T=u,E=d,D=f,O=p,k=m,te=h,A=g,j=_,M=v,N=y,ne=b,re=ee;for(let e=0;e<a;e+=2)x=x+T|0,M=q(M^x,16),k=k+M|0,T=q(T^k,12),x=x+T|0,M=q(M^x,8),k=k+M|0,T=q(T^k,7),S=S+E|0,N=q(N^S,16),te=te+N|0,E=q(E^te,12),S=S+E|0,N=q(N^S,8),te=te+N|0,E=q(E^te,7),C=C+D|0,ne=q(ne^C,16),A=A+ne|0,D=q(D^A,12),C=C+D|0,ne=q(ne^C,8),A=A+ne|0,D=q(D^A,7),w=w+O|0,re=q(re^w,16),j=j+re|0,O=q(O^j,12),w=w+O|0,re=q(re^w,8),j=j+re|0,O=q(O^j,7),x=x+E|0,re=q(re^x,16),A=A+re|0,E=q(E^A,12),x=x+E|0,re=q(re^x,8),A=A+re|0,E=q(E^A,7),S=S+D|0,M=q(M^S,16),j=j+M|0,D=q(D^j,12),S=S+D|0,M=q(M^S,8),j=j+M|0,D=q(D^j,7),C=C+O|0,N=q(N^C,16),k=k+N|0,O=q(O^k,12),C=C+O|0,N=q(N^C,8),k=k+N|0,O=q(O^k,7),w=w+T|0,ne=q(ne^w,16),te=te+ne|0,T=q(T^te,12),w=w+T|0,ne=q(ne^w,8),te=te+ne|0,T=q(T^te,7);let P=0;r[P++]=o+x|0,r[P++]=s+S|0,r[P++]=c+C|0,r[P++]=l+w|0,r[P++]=u+T|0,r[P++]=d+E|0,r[P++]=f+D|0,r[P++]=p+O|0,r[P++]=m+k|0,r[P++]=h+te|0,r[P++]=g+A|0,r[P++]=_+j|0,r[P++]=v+M|0,r[P++]=y+N|0,r[P++]=b+ne|0,r[P++]=ee+re|0}function Ci(e,t,n,r){let i=Zr?e:ti(e.slice(0,4)),a=Zr?t:ti(t.slice(0,8)),o=Zr?n:ti(n.slice(0,4)),s=new Uint32Array(16);Si(i,a,o.subarray(1),s,o[0]);let c=0;r[c++]=s[0]-i[0]|0,r[c++]=s[1]-i[1]|0,r[c++]=s[2]-i[2]|0,r[c++]=s[3]-i[3]|0,r[c++]=s[12]-o[0]|0,r[c++]=s[13]-o[1]|0,r[c++]=s[14]-o[2]|0,r[c++]=s[15]-o[3]|0,ti(r),Zr||Yr(i,a,o),Yr(s)}const wi=vi(Si,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Ti=vi(Si,{counterRight:!1,counterLength:8,extendNonceFn:Ci,allowShortKeys:!1}),Ei=new Uint8Array(16),Di=(e,t)=>{e.update(t);let n=t.length%16;n&&e.update(Ei.subarray(n))},Oi=new Uint8Array(32);function ki(e,t,n,r,i){i!==void 0&&Hr(i,void 0,`AAD`);let a=e(t,n,Oi),o=li(r.length,i?i.length:0,!0),s=xi.create(a);i&&Di(s,i),Di(s,r),s.update(o);let c=s.digest();return Yr(a,o),c}const Ai=e=>(t,n,r)=>({encrypt(i,a){let o=i.length;a=ci(o+16,a,!1),a.set(i);let s=a.subarray(0,-16);e(t,n,s,s,1);let c=ki(e,t,n,s,r);return a.set(c,o),Yr(c),a},decrypt(i,a){a=ci(i.length-16,a,!1);let o=i.subarray(0,-16),s=i.subarray(-16),c=ki(e,t,n,o,r);if(!ai(s,c))throw Yr(c),Error(`invalid tag`);return a.set(i.subarray(0,-16)),e(t,n,a,a,1),Yr(c),a}}),ji=si({blockSize:64,nonceLength:12,tagLength:16,withAAD:!0},Ai(wi)),Mi=si({blockSize:64,nonceLength:24,tagLength:16,withAAD:!0},Ai(Ti)),Ni=BigInt(2**32-1),Pi=BigInt(32);function Fi(e,t=!1){return t?{h:Number(e&Ni),l:Number(e>>Pi&Ni)}:{h:Number(e>>Pi&Ni)|0,l:Number(e&Ni)|0}}function Ii(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let a=0;a<n;a++){let{h:n,l:o}=Fi(e[a],t);[r[a],i[a]]=[n,o]}return[r,i]}const Li=e=>e/2**32|0,Ri=e=>e>>>0;function zi(e,t,n,r){let i=Li(n),a=Ri(n);e.setUint32(t,r?a:i,r),e.setUint32(t+4,r?i:a,r)}const Bi=(e,t,n)=>e>>>n,Vi=(e,t,n)=>e<<32-n|t>>>n,Hi=(e,t,n)=>e>>>n|t<<32-n,Ui=(e,t,n)=>e<<32-n|t>>>n,Wi=(e,t,n)=>e<<64-n|t>>>n-32,Gi=(e,t,n)=>e>>>n-32|t<<64-n;function Ki(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const qi=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Ji=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Yi=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Xi=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Zi=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Qi=(e,t,n,r,i,a)=>t+n+r+i+a+(e/2**32|0)|0;function $i(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name===`Uint8Array`&&`BYTES_PER_ELEMENT`in e&&e.BYTES_PER_ELEMENT===1}const ea=e=>e?`"${e}" `:``;function ta(e,t=``){if(typeof e!=`number`)throw TypeError(ea(t)+`expected number, got `+typeof e);if(!Number.isSafeInteger(e)||e<0)throw RangeError(ea(t)+`expected integer >= 0, got `+e);return e}function na(e,t,n=``){if($i(e)&&(t===void 0||e.length===t))return e;t!==void 0&&ta(t,`length`);let r=$i(e),i=t===void 0?``:` of length ${t}`,a=r?`length=${e.length}`:`type=${typeof e}`,o=ea(n)+`expected Uint8Array`+i+`, got `+a;throw r?RangeError(o):TypeError(o)}function ra(e){if(typeof e!=`function`||typeof e.create!=`function`)throw TypeError(`expected hash wrapped by utils.createHasher`);if(ta(e.outputLen),ta(e.blockLen),e.outputLen<1||e.blockLen<1)throw Error(`hash blockLen / outputLen must be >= 1`)}const ia=(e,t)=>{if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError((t===`object`?``:`"${t}" `)+`expected object, got type=`+typeof e)},aa=(e,t)=>{ia(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,`__proto__`))throw TypeError(`"${t}.__proto__" is not allowed`)};function oa(e,t=!0){if(e.destroyed)throw Error(`hash was destroyed`);if(t&&e.finished)throw Error(`digest() was already called`)}function sa(e,t){na(e,void 0,`output`);let n=t.outputLen;if(!(e.length>=n))throw RangeError(`"output" expected length >= `+n)}function ca(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function la(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ua(e,t){return e<<32-t|e>>>t}const da=typeof Uint8Array.from([]).toHex==`function`&&typeof Uint8Array.fromHex==`function`,fa=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function pa(e){if(na(e),da)return e.toHex();let t=``;for(let n=0;n<e.length;n++)t+=fa[e[n]];return t}function ma(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:void 0}function ha(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);if(da)try{return Uint8Array.fromHex(e)}catch(e){throw e instanceof SyntaxError?RangeError(e.message):e}let t=e.length,n=t/2;if(t%2)throw RangeError(`hex string expected, got unpadded hex of length `+t);let r=new Uint8Array(n);for(let t=0,i=0;t<n;t++,i+=2){let n=ma(e.charCodeAt(i)),a=ma(e.charCodeAt(i+1));if(n===void 0||a===void 0){let t=e[i]+e[i+1];throw RangeError(`hex string expected, got non-hex character "`+t+`" at index `+i)}r[t]=n*16+a}return r}function ga(...e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];na(r),t+=r.length}let n=new Uint8Array(t);for(let t=0,r=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}function _a(e,t,n=`opts`){return aa(e,`defaults`),t!==void 0&&aa(t,n),Object.assign(Object.create(null),e,t)}function va(e,t={}){if(typeof e!=`function`)throw TypeError(`"hashCons" expected function, got type=`+typeof e);t=_a({},t,`info`);let n=(t,n)=>e(n).update(t).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=t=>e(t),Object.assign(n,t),Object.freeze(n)}function ya(e=32){ta(e,`bytesLength`);let t=typeof globalThis==`object`?globalThis.crypto:null;if(typeof t?.getRandomValues!=`function`)throw Error(`crypto.getRandomValues must be defined`);if(e>65536)throw RangeError(`"bytesLength" expected <= 65536, got ${e}`);return t.getRandomValues(new Uint8Array(e))}const ba=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function xa(e,t,n){return e&t^~e&n}function Sa(e,t,n){return e&t^e&n^t&n}var Ca=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=la(this.buffer)}update(e){oa(this),na(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,a=!1;for(let o=0;o<i;){let s=Math.min(r-this.pos,i-o);if(s===r){let t=la(e);for(;r<=i-o;o+=r)this.process(t,o);a=!0;continue}n.set(o===0&&s===i?e:e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===r&&(this.process(t,0),this.pos=0,a=!0)}return this.length+=e.length,a&&this.roundClean(),this}digestInto(e){oa(this),sa(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:a}=this;t[a++]=128,t.fill(0,a),this.padOffset>r-a&&(this.process(n,0),t.fill(0)),zi(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let o=e===t?n:la(e),s=this.outputLen,c=s/4,l=this.get();if(s%4||c>l.length)throw Error(`invalid outputLen`);for(let e=0;e<c;e++)o.setUint32(4*e,l[e],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:a}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=a,a&&e.buffer.set(t),e}clone(){return this._cloneInto()}};const wa=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ta=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ea=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Da=new Uint32Array(64);var Oa=class extends Ca{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:a,G:o,H:s}=this;return[e,t,n,r,i,a,o,s]}set(e,t,n,r,i,a,o,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=a|0,this.G=o|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Da[n]=e.getUint32(t,!1);for(let e=16;e<64;e++){let t=Da[e-15],n=Da[e-2],r=ua(t,7)^ua(t,18)^t>>>3,i=ua(n,17)^ua(n,19)^n>>>10;Da[e]=i+Da[e-7]+r+Da[e-16]|0}let{A:n,B:r,C:i,D:a,E:o,F:s,G:c,H:l}=this;for(let e=0;e<64;e++){let t=ua(o,6)^ua(o,11)^ua(o,25),u=l+t+xa(o,s,c)+Ea[e]+Da[e]|0,d=(ua(n,2)^ua(n,13)^ua(n,22))+Sa(n,r,i)|0;l=c,c=s,s=o,o=a+u|0,a=i,i=r,r=n,n=u+d|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,a=a+this.D|0,o=o+this.E|0,s=s+this.F|0,c=c+this.G|0,l=l+this.H|0,this.set(n,r,i,a,o,s,c,l)}roundClean(){ca(Da)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),ca(this.buffer)}},ka=class extends Oa{constructor(){super(32,wa)}};const Aa=Ii(`0x428a2f98d728ae22.0x7137449123ef65cd.0xb5c0fbcfec4d3b2f.0xe9b5dba58189dbbc.0x3956c25bf348b538.0x59f111f1b605d019.0x923f82a4af194f9b.0xab1c5ed5da6d8118.0xd807aa98a3030242.0x12835b0145706fbe.0x243185be4ee4b28c.0x550c7dc3d5ffb4e2.0x72be5d74f27b896f.0x80deb1fe3b1696b1.0x9bdc06a725c71235.0xc19bf174cf692694.0xe49b69c19ef14ad2.0xefbe4786384f25e3.0x0fc19dc68b8cd5b5.0x240ca1cc77ac9c65.0x2de92c6f592b0275.0x4a7484aa6ea6e483.0x5cb0a9dcbd41fbd4.0x76f988da831153b5.0x983e5152ee66dfab.0xa831c66d2db43210.0xb00327c898fb213f.0xbf597fc7beef0ee4.0xc6e00bf33da88fc2.0xd5a79147930aa725.0x06ca6351e003826f.0x142929670a0e6e70.0x27b70a8546d22ffc.0x2e1b21385c26c926.0x4d2c6dfc5ac42aed.0x53380d139d95b3df.0x650a73548baf63de.0x766a0abb3c77b2a8.0x81c2c92e47edaee6.0x92722c851482353b.0xa2bfe8a14cf10364.0xa81a664bbc423001.0xc24b8b70d0f89791.0xc76c51a30654be30.0xd192e819d6ef5218.0xd69906245565a910.0xf40e35855771202a.0x106aa07032bbd1b8.0x19a4c116b8d2d0c8.0x1e376c085141ab53.0x2748774cdf8eeb99.0x34b0bcb5e19b48a8.0x391c0cb3c5c95a63.0x4ed8aa4ae3418acb.0x5b9cca4f7763e373.0x682e6ff3d6b2b8a3.0x748f82ee5defb2fc.0x78a5636f43172f60.0x84c87814a1f0ab72.0x8cc702081a6439ec.0x90befffa23631e28.0xa4506cebde82bde9.0xbef9a3f7b2c67915.0xc67178f2e372532b.0xca273eceea26619c.0xd186b8c721c0c207.0xeada7dd6cde0eb1e.0xf57d4f7fee6ed178.0x06f067aa72176fba.0x0a637dc5a2c898a6.0x113f9804bef90dae.0x1b710b35131c471b.0x28db77f523047d84.0x32caab7b40c72493.0x3c9ebe0a15c9bebc.0x431d67c49c100d4c.0x4cc5d4becb3e42b6.0x597f299cfc657e2a.0x5fcb6fab3ad6faec.0x6c44198c4a475817`.split(`.`).map(e=>BigInt(e))),ja=Aa[0],Ma=Aa[1],Na=new Uint32Array(80),Pa=new Uint32Array(80);var Fa=class extends Ca{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:a,Dh:o,Dl:s,Eh:c,El:l,Fh:u,Fl:d,Gh:f,Gl:p,Hh:m,Hl:h}=this;return[e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h]}set(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=a|0,this.Dh=o|0,this.Dl=s|0,this.Eh=c|0,this.El=l|0,this.Fh=u|0,this.Fl=d|0,this.Gh=f|0,this.Gl=p|0,this.Hh=m|0,this.Hl=h|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let n=0;n<16;n++,t+=4)Na[n]=e.getUint32(t),Pa[n]=e.getUint32(t+=4);for(let e=16;e<80;e++){let t=Na[e-15]|0,n=Pa[e-15]|0,r=Hi(t,n,1)^Hi(t,n,8)^Bi(t,n,7),i=Ui(t,n,1)^Ui(t,n,8)^Vi(t,n,7),a=Na[e-2]|0,o=Pa[e-2]|0,s=Hi(a,o,19)^Wi(a,o,61)^Bi(a,o,6),c=Ui(a,o,19)^Gi(a,o,61)^Vi(a,o,6),l=Yi(i,c,Pa[e-7],Pa[e-16]),u=Xi(l,r,s,Na[e-7],Na[e-16]);Na[e]=u|0,Pa[e]=l|0}let{Ah:n,Al:r,Bh:i,Bl:a,Ch:o,Cl:s,Dh:c,Dl:l,Eh:u,El:d,Fh:f,Fl:p,Gh:m,Gl:h,Hh:g,Hl:_}=this;for(let e=0;e<80;e++){let t=Hi(u,d,14)^Hi(u,d,18)^Wi(u,d,41),v=Ui(u,d,14)^Ui(u,d,18)^Gi(u,d,41),y=u&f^~u&m,b=d&p^~d&h,ee=Zi(_,v,b,Ma[e],Pa[e]),x=Qi(ee,g,t,y,ja[e],Na[e]),S=ee|0,C=Hi(n,r,28)^Wi(n,r,34)^Wi(n,r,39),w=Ui(n,r,28)^Gi(n,r,34)^Gi(n,r,39),T=n&i^n&o^i&o,E=r&a^r&s^a&s;g=m|0,_=h|0,m=f|0,h=p|0,f=u|0,p=d|0,{h:u,l:d}=Ki(c|0,l|0,x|0,S|0),c=o|0,l=s|0,o=i|0,s=a|0,i=n|0,a=r|0;let D=qi(S,w,E);n=Ji(D,x,C,T),r=D|0}({h:n,l:r}=Ki(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:a}=Ki(this.Bh|0,this.Bl|0,i|0,a|0),{h:o,l:s}=Ki(this.Ch|0,this.Cl|0,o|0,s|0),{h:c,l}=Ki(this.Dh|0,this.Dl|0,c|0,l|0),{h:u,l:d}=Ki(this.Eh|0,this.El|0,u|0,d|0),{h:f,l:p}=Ki(this.Fh|0,this.Fl|0,f|0,p|0),{h:m,l:h}=Ki(this.Gh|0,this.Gl|0,m|0,h|0),{h:g,l:_}=Ki(this.Hh|0,this.Hl|0,g|0,_|0),this.set(n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_)}roundClean(){ca(Na,Pa)}destroy(){this.destroyed=!0,ca(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},Ia=class extends Fa{constructor(){super(64,Ta)}};const La=va(()=>new ka,ba(1)),Ra=va(()=>new Ia,ba(3));
4
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
5
+ function za(e,t,n=()=>{}){if(!Array.isArray(e))throw TypeError(`"${t}" expected array, got type=${typeof e}`);for(let r=0;r<e.length;r++)n(e[r],`${t}[${r}]`);return e}const Ba=(e,t,n)=>na(e,t,n),Va=ta;function Ha(e,t=`object`){if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(t===`object`?`expected valid options object`:`"${t}" expected object, got type=${typeof e}`);return e}function Ua(e,t){if(typeof e!=`function`)throw TypeError(`"${t}" is invalid: expected function, got ${typeof e}`);return e}const Wa=pa,Ga=(...e)=>ga(...e),Ka=e=>ha(e),qa=$i,Ja=e=>ya(e),Ya=BigInt(0),Xa=BigInt(1),Za=e=>e?`"${e}" `:``;function Qa(e,t=``){if(typeof e!=`boolean`)throw TypeError(Za(t)+`expected boolean, got type=`+typeof e);return e}function $a(e){if(typeof e==`bigint`){if(!so(e))throw RangeError(`positive bigint expected, got `+e)}else Va(e);return e}function eo(e,t=``){if(typeof e!=`number`){let n=t&&`"${t}" `;throw TypeError(n+`expected number, got type=`+typeof e)}if(!Number.isSafeInteger(e)){let n=t&&`"${t}" `;throw RangeError(n+`expected safe integer, got `+e)}}function to(e){if(typeof e!=`string`)throw TypeError(`hex string expected, got `+typeof e);return e===``?Ya:BigInt(`0x`+e)}function no(e){return to(pa(e))}function ro(e){return to(pa(oo(na(e)).reverse()))}function io(e,t){if(ta(t),t===0)throw Error(`zero output length is invalid`);e=$a(e);let n=t*2,r=e.toString(16);if(r.length>n)throw RangeError(`number is too large`);return ha(r.padStart(n,`0`))}function ao(e,t){return io(e,t).reverse()}function oo(e){return Uint8Array.from(Ba(e))}function so(e){return typeof e==`bigint`&&Ya<=e}function co(e,t,n){return so(e)&&so(t)&&so(n)&&t<=e&&e<n}function lo(e,t,n,r){if(!co(t,n,r))throw RangeError(`expected valid `+e+`: `+n+` <= n < `+r+`, got `+t)}function uo(e){if(e<Ya)throw Error(`expected non-negative bigint, got `+e);return e===Ya?0:e.toString(2).length}const fo=e=>(eo(e,`n`),(Xa<<BigInt(e))-Xa);function po(e,t={},n={},r=`object`){Ha(e,r),Ha(t,`fields`),Ha(n,`optFields`);function i(t,n,i){let a=r===`object`?`param "${String(t)}"`:`"${r}.${String(t)}"`,o=e[t];if(!Object.hasOwn(e,t)&&(i?o!==void 0:n!==`function`))throw TypeError(`${a} is invalid: expected own property`);if(i&&o===void 0)return;let s=typeof o;if(s!==n||o===null)throw TypeError(`${a} is invalid: expected ${n}, got ${s}`)}let a=(e,t)=>Object.entries(e).forEach(([e,n])=>i(e,n,t));a(t,!1),a(n,!0)}
6
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
7
+ const mo=BigInt(0),ho=BigInt(1),go=BigInt(2),_o=BigInt(3),vo=BigInt(4),yo=BigInt(5),bo=BigInt(7),xo=BigInt(8),So=BigInt(9),Co=BigInt(15),wo=BigInt(16),To=BigInt(`0x10000000000000000`);function Eo(e,t){if(t<=mo)throw Error(`mod: expected positive modulus, got `+t);let n=e%t;return n>=mo?n:t+n}function Do(e,t,n){if(n<=ho)throw Error(`pow: expected modulus > 1, got `+n);if(typeof t!=`bigint`)throw TypeError(`invalid exponent: expected bigint, got `+typeof t);if(t<mo)throw Error(`invalid exponent, negatives unsupported`);if(t===mo)return ho;if(t===ho)return e;let r=e%n;if(r<mo&&(r+=n),t<To){let e=ho;for(;t>mo;)t&ho&&(e=e*r%n),r=r*r%n,t>>=ho;return e}let i=[];for(;t>mo;)i.push(Number(t&Co)),t>>=vo;let a=Array(16);a[0]=ho,a[1]=r;for(let e=2;e<16;e++)a[e]=a[e-1]*r%n;let o=a[i[i.length-1]];for(let e=i.length-2;e>=0;e--){o=o*o%n,o=o*o%n,o=o*o%n,o=o*o%n;let t=i[e];t!==0&&(o=o*a[t]%n)}return o}function Oo(e,t,n){if(n<=ho)throw Error(`pow2: expected modulus > 1, got `+n);if(t<mo)throw Error(`pow2: expected non-negative exponent, got `+t);let r=e;for(;t-->mo;)r*=r,r%=n;return r}function ko(e,t){if(e===mo)throw Error(`invert: expected non-zero number`);if(t<=ho)throw Error(`invert: expected modulus > 1, got `+t);let n=Eo(e,t),r=t,i=mo,a=ho;for(;n!==mo;){let e=r/n,t=r-n*e,o=i-a*e;r=n,n=t,i=a,a=o}if(r!==ho)throw Error(`invert: does not exist`);return Eo(i,t)}function Ao(e,t,n){let r=e;if(!r.eql(r.sqr(t),n))throw Error(`Cannot find square root`)}function jo(e,t){if((e&ho)===mo)throw Error(t+`: expected odd modulus, got `+e)}function Mo(e,t){let n=e,r=(n.ORDER+ho)/vo,i=n.pow(t,r);return Ao(n,i,t),i}function No(e,t){let n=e,r=(n.ORDER-yo)/xo,i=n.mul(t,go),a=n.pow(i,r),o=n.mul(t,a),s=n.mul(n.mul(o,go),a),c=n.mul(o,n.sub(s,n.ONE));return Ao(n,c,t),c}function Po(e){let t=Go(e),n=Fo(e),r=n(t,t.neg(t.ONE)),i=n(t,r),a=n(t,t.neg(r)),o=(e+bo)/wo;return((e,t)=>{let n=e,s=n.pow(t,o),c=n.mul(s,r),l=n.mul(s,i),u=n.mul(s,a),d=n.eql(n.sqr(c),t),f=n.eql(n.sqr(l),t);s=n.cmov(s,c,d),c=n.cmov(u,l,f);let p=n.eql(n.sqr(c),t),m=n.cmov(s,c,p);return Ao(n,m,t),m})}function Fo(e){if(e<_o)throw Error(`sqrt is not defined for small field`);jo(e,`tonelliShanks`);let t=e-ho,n=0;for(;t%go===mo;)t/=go,n++;let r=go,i=Go(e);for(;Vo(i,r)===1;)if(r++>1e3)throw Error(`Cannot find square root: probably non-prime P`);if(n===1)return Mo;let a=i.pow(r,t),o=(t+ho)/go;return function(e,r){let i=e;if(i.is0(r))return r;if(Vo(i,r)!==1)throw Error(`Cannot find square root`);let s=n,c=i.mul(i.ONE,a),l=i.pow(r,t),u=i.pow(r,o);for(;!i.eql(l,i.ONE);){if(i.is0(l))throw Error(`Cannot find square root: probably non-prime P`);let e=1,t=i.sqr(l);for(;!i.eql(t,i.ONE);)if(e++,t=i.sqr(t),e===s)throw Error(`Cannot find square root`);let n=ho<<BigInt(s-e-1),r=i.pow(c,n);s=e,c=i.sqr(r),l=i.mul(l,c),u=i.mul(u,r)}return u}}function Io(e){return jo(e,`Fp.sqrt`),e%vo===_o?Mo:e%xo===yo?No:e%wo===So?Po(e):Fo(e)}const Lo=(e,t)=>(Eo(e,t)&ho)===ho,Ro=[`create`,`isValid`,`is0`,`neg`,`inv`,`sqrt`,`sqr`,`eql`,`add`,`sub`,`mul`,`pow`,`div`,`addN`,`subN`,`mulN`,`sqrN`];function zo(e){if(Ha(e,`field`),typeof e.ORDER!=`bigint`)throw TypeError(`param "ORDER" is invalid: expected bigint, got `+typeof e.ORDER);eo(e.BYTES,`BYTES`),eo(e.BITS,`BITS`);for(let t of Ro)Ua(e[t],`field.`+t);if(e.BYTES<1||e.BITS<1)throw Error(`invalid field: expected BYTES/BITS > 0`);if(e.ORDER<=ho)throw Error(`invalid field: expected ORDER > 1, got `+e.ORDER);return e}function Bo(e,t,n=!1){zo(e),za(t,`nums`),Qa(n,`passZero`);let r=e,i=Array(t.length).fill(n?r.ZERO:void 0),a=t.reduce((e,t,n)=>r.is0(t)?e:(i[n]=e,r.mul(e,t)),r.ONE),o=r.inv(a);return t.reduceRight((e,t,n)=>r.is0(t)?e:(i[n]=r.mul(e,i[n]),r.mul(e,t)),o),i}function Vo(e,t){zo(e);let n=e;jo(n.ORDER,`FpLegendre`);let r=(n.ORDER-ho)/go,i=n.pow(t,r),a=n.eql(i,n.ONE),o=n.eql(i,n.ZERO),s=n.eql(i,n.neg(n.ONE));if(!a&&!o&&!s)throw Error(`invalid Legendre symbol result`);return a?1:o?0:-1}function Ho(e,t){if(t!==void 0&&Va(t),e<=mo)throw Error(`invalid n length: expected positive n, got `+e);if(t!==void 0&&t<1)throw Error(`invalid n length: expected positive bit length, got `+t);let n=uo(e);if(t!==void 0&&t<n)throw Error(`invalid n length: expected nBitLength (${t}) >= bitLen(n) (${n})`);let r=t===void 0?n:t;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}const Uo=new WeakMap;var Wo=class{ORDER;BITS;BYTES;isLE;ZERO=mo;ONE=ho;_lengths;_mod;constructor(e,t={}){if(e<=ho)throw Error(`invalid field: expected ORDER > 1, got `+e);let n;this.isLE=!1,typeof t==`object`&&t&&(typeof t.BITS==`number`&&(n=t.BITS),typeof t.sqrt==`function`&&Object.defineProperty(this,"sqrt",{value:t.sqrt,enumerable:!0}),typeof t.isLE==`boolean`&&(this.isLE=t.isLE),t.allowedLengths&&(this._lengths=Object.freeze(t.allowedLengths.slice())),typeof t.modFromBytes==`boolean`&&(this._mod=t.modFromBytes));let{nBitLength:r,nByteLength:i}=Ho(e,n);if(i>2048)throw Error(`invalid field: expected ORDER of <= 2048 bytes`);this.ORDER=e,this.BITS=r,this.BYTES=i,Object.freeze(this)}create(e){return Eo(e,this.ORDER)}isValid(e){if(typeof e!=`bigint`)throw TypeError(`invalid field element: expected bigint, got `+typeof e);return mo<=e&&e<this.ORDER}is0(e){return e===mo}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&ho)===ho}neg(e){return Eo(-e,this.ORDER)}eql(e,t){return e===t}sqr(e){return Eo(e*e,this.ORDER)}add(e,t){return Eo(e+t,this.ORDER)}sub(e,t){return Eo(e-t,this.ORDER)}mul(e,t){return Eo(e*t,this.ORDER)}pow(e,t){return Do(e,t,this.ORDER)}div(e,t){return Eo(e*ko(t,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,t){return e+t}subN(e,t){return e-t}mulN(e,t){return e*t}inv(e){return ko(e,this.ORDER)}sqrt(e){let t=Uo.get(this);return t||Uo.set(this,t=Io(this.ORDER)),t(this,e)}toBytes(e){return this.isLE?ao(e,this.BYTES):io(e,this.BYTES)}fromBytes(e,t=!1){Ba(e);let{_lengths:n,BYTES:r,isLE:i,ORDER:a,_mod:o}=this;if(n){if(e.length<1||!n.includes(e.length)||e.length>r)throw Error(`Field.fromBytes: expected `+n+` bytes, got `+e.length);let t=new Uint8Array(r);t.set(e,i?0:t.length-e.length),e=t}if(e.length!==r)throw Error(`Field.fromBytes: expected `+r+` bytes, got `+e.length);let s=i?ro(e):no(e);if(o&&(s=Eo(s,a)),!t&&!this.isValid(s))throw Error(`invalid field element: outside of range 0..ORDER`);return s}invertBatch(e){return Bo(this,e,!0)}cmov(e,t,n){return Qa(n,`condition`),n?t:e}};function Go(e,t={}){return Object.freeze(Wo.prototype),new Wo(e,t)}
8
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
9
+ const Ko=BigInt(0),qo=BigInt(1),Jo=BigInt(4),Yo=2**31;function Xo(e){let t=e;if(typeof t!=`function`)throw TypeError(`"Point" expected constructor, got type=`+typeof e);Ua(t.fromAffine,`Point.fromAffine`),Ua(t.fromBytes,`Point.fromBytes`),Ua(t.fromHex,`Point.fromHex`),Ha(t.BASE,`Point.BASE`),Ha(t.ZERO,`Point.ZERO`),zo(t.Fp),zo(t.Fn)}function Zo(e,t){Xo(e),ts(t,e);let n=Bo(e.Fp,t.map(e=>e.Z));return t.map((t,r)=>e.fromAffine(t.toAffine(n[r])))}function Qo(e,t,n=1){if(!Number.isSafeInteger(e)||e<n||e>t)throw Error(`invalid window size, expected [`+n+`..`+t+`], got W=`+e)}function $o(e,t){let n=e*(4*t+128);if(n>Yo)throw Error(`invalid window size: table would need ~`+Math.ceil(n/2**20)+` MiB, max `+Yo/2**20+` MiB`)}function es(e,t){if(e!==void 0){Ua(e,`randomBytes`);try{let n=e(t);if(!qa(n)||n.length!==t)return}catch{return}return e}}function ts(e,t){za(e,`points`),e.forEach((e,n)=>{if(!(e instanceof t))throw Error(`invalid point at index `+n)})}function ns(e,t,n){if(!Array.isArray(e))throw Error(`array of scalars expected`);e.forEach((e,r)=>{if(!(n===void 0?t.isValid(e):so(e)&&e<n))throw Error(`invalid scalar at index `+r)})}const rs=new WeakMap;function is(e){return rs.get(e)||1}function as(e,t){let n=e.double(),r=[e];for(let e=1;e<t;e++)r.push(r[e-1].add(n));return r}function os(e,t){let n=2**t,r=n/2,i=BigInt(n-1),a=[];for(;e>Ko;){let t=0;e&qo&&(t=Number(e&i),t>=r&&(t-=n),e-=BigInt(t)),a.push(t),e>>=qo}return a}function ss(e,t,n){let r=2**t,i=r/2,a=BigInt(r-1),o=BigInt(t),s=[];for(let t=0;t<n;t++){let t=Number(e&a);e>>=o,t>i&&(t-=r,e+=qo),s.push(t)}if(e!==Ko)throw Error(`invalid wnaf`);return s}function cs(e,t,n){let r=0;for(let e of n)r=Math.max(r,e.length);let i=e;for(let e=r-1;e>=0;e--){e!==r-1&&(i=i.double());for(let r=0;r<n.length;r++){let a=n[r][e];if(a){let e=t[r][Math.abs(a)-1>>1];i=i.add(a<0?e.negate():e)}}}return i}var ls=class{Point;BASE;ZERO;randomBytes;wnafPrecomputes=new WeakMap;baseCanBeBlinded;bits;constructor(e,t){Xo(e),this.randomBytes=es(t,16),this.Point=e,this.BASE=e.BASE,this.ZERO=e.ZERO,this.bits=e.Fn.BITS}buildWnafTable(e,t,n){let r=Math.ceil(n/t)+1,i=2**(t-1),a=[],o=e;for(let e=0;e<r;e++){let e=o;for(let t=0;t<i;t++)a.push(e),e=e.add(o);o=a[a.length-1].double()}return{W:t,bits:n,windows:r,comp:a}}wnafCachedCT(e,t){let{W:n,windows:r,comp:i}=e,a=2**(n-1),o=ss(t,n,r),s=this.ZERO,c=this.BASE;for(let e=0;e<r;e++){let t=o[e],n=e*a,r=Math.abs(t)-1,l=i[n];for(let e=1;e<a;e++)l=e===r?i[n+e]:l;let u=l.negate();t===0?c=c.add(i[n]):s=s.add(t<0?u:l)}return{p:s,f:c}}getWnafPrecomputes(e,t,n,r){let i=this.wnafPrecomputes.get(t),a=i?.find(t=>t.W===e&&t.bits===n);return a||(a=this.buildWnafTable(t,e,n),typeof r==`function`&&(a={...a,comp:r(a.comp)}),i||(i=[],this.wnafPrecomputes.set(t,i)),i.push(a)),a}assertPoint(e){if(!(e instanceof this.Point))throw TypeError(`"point" expected Point instance, got type=`+typeof e)}validateMulInput(e,t){if(this.assertPoint(e),!co(t,qo,this.Point.Fn.ORDER))throw Error(`invalid scalar`)}runCT(e,t,n,r){let i=is(e);return i===1?this.fixedWindowCT(e,t,n):this.wnafCachedCT(this.getWnafPrecomputes(i,e,n,r),t)}mulCT(e,t,n){return this.validateMulInput(e,t),this.runCT(e,t,this.bits,n)}mulCTBlinded(e,t,n){if(this.validateMulInput(e,t),this.randomBytes===void 0)throw Error(`randomBytes is required for scalar blinding`);let r=this.Point.Fn.BITS+128,i=this.randomBytes(16);if(!qa(i)||i.length!==16)throw Error(`randomBytes returned invalid byte array`);i[0]=i[0]&63|128;let a=t+no(i)*this.Point.Fn.ORDER;return this.runCT(e,a,r,n)}fixedWindowCT(e,t,n){let r=fo(5),i=Array(32);i[0]=this.ZERO;for(let t=1;t<32;t++)i[t]=i[t-1].add(e);let a=Math.ceil(n/5),o=this.ZERO;for(let e=a-1;e>=0;e--){if(e!==a-1)for(let e=0;e<5;e++)o=o.double();let n=Number(t>>BigInt(e*5)&r),s=i[0];for(let e=1;e<32;e++)s=e===n?i[e]:s;o=o.add(s)}return{p:o,f:o}}shouldBlind(e,t){return this.randomBytes===void 0?!1:t===qo||e===this.BASE&&(this.baseCanBeBlinded===void 0&&(this.baseCanBeBlinded=this.mulUnsafe(this.BASE,this.Point.Fn.ORDER).is0()),this.baseCanBeBlinded)}mulSecret(e,t,n,r){return this.shouldBlind(e,n)?this.mulCTBlinded(e,t,r):this.mulCT(e,t,r)}mulUnsafe(e,t,n){if(this.assertPoint(e),!so(t))throw Error(`invalid scalar`);let r=is(e);if(r===1||t>=this.Point.Fn.ORDER)return us(this.Point,[e],[t],!0);let i=this.getWnafPrecomputes(r,e,this.bits,n);return this.wnafCachedCT(i,t).p}setWindowSize(e,t){this.assertPoint(e),Qo(t,this.bits),$o((Math.ceil((this.bits+128)/t)+1)*2**(t-1),this.Point.Fp.BYTES),rs.set(e,t),this.wnafPrecomputes.delete(e)}hasWindowSize(e){return is(e)!==1}};function us(e,t,n,r=!1){if(Xo(e),ts(t,e),Qa(r,`allowOversized`),ns(n,e.Fn,r?e.Fn.ORDER**Jo:void 0),t.length!==n.length)throw Error(`arrays of points and scalars must have equal length`);let i=t.map(e=>as(e,4)),a=n.map(e=>os(e,4));return cs(e.ZERO,i,a)}function ds(e,t,n){if(t){if(t.ORDER!==e)throw Error(`Field.ORDER must match order: Fp == p, Fn == n`);return zo(t),t}return Go(e,{isLE:n})}function fs(e,t,n={},r){if(e!==`weierstrass`&&e!==`edwards`)throw Error(`expected curve type "weierstrass" or "edwards"`);if(r===void 0&&(r=e===`edwards`),!t||typeof t!=`object`)throw Error(`expected valid ${e} CURVE object`);po(n);for(let e of[`p`,`n`,`h`]){let n=t[e];if(!(so(n)&&n!==Ko))throw Error(`CURVE.${e} must be positive bigint`)}let i=ds(t.p,n.Fp,r),a=ds(t.n,n.Fn,r),o=[`Gx`,`Gy`,`a`,e===`weierstrass`?`b`:`d`];for(let e of o)if(!i.isValid(t[e]))throw Error(`CURVE.${e} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:a}}function ps(e,t){return function(n){let r=e(n);return{secretKey:r,publicKey:t(r)}}}
10
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
+ const ms=BigInt(0),hs=BigInt(1),gs=BigInt(2),_s=BigInt(4),vs=BigInt(8);function ys(e,t,n,r){let i=e.sqr(n),a=e.sqr(r),o=e.add(e.mul(t.a,i),a),s=e.add(e.ONE,e.mul(t.d,e.mul(i,a)));return e.eql(o,s)}function bs(e,t={}){po(t,{},{},`extraOpts`);let n=t,r=fs(`edwards`,e,n,n.FpFnLE),{Fp:i,Fn:a}=r,o=r.CURVE,{h:s}=o;if(Vo(i,o.a)!==1)throw Error(`edwards: CURVE.a must be a square in Fp for complete addition formulas`);if(Vo(i,o.d)!==-1)throw Error(`edwards: CURVE.d must be a non-square in Fp for complete addition formulas`);po(n,{},{uvRatio:`function`,randomBytes:`function`});let c=n.randomBytes===void 0?Ja:n.randomBytes,l=gs<<BigInt(i.BYTES*8)-hs;function u(e){if(!i.isOdd)throw Error(`Field does not have .isOdd()`);return i.isOdd(e)}let d=n.uvRatio===void 0?(e,t)=>{try{return{isValid:!0,value:i.sqrt(i.div(e,t))}}catch{return{isValid:!1,value:ms}}}:n.uvRatio;if(!ys(i,o,o.Gx,o.Gy))throw Error(`bad curve params: generator point`);let f=i.eql(o.a,i.neg(i.ONE))?e=>i.neg(e):i.eql(o.a,i.ONE)?e=>e:e=>i.mul(o.a,e);function p(e,t,n=!1){let r=n?hs:ms;return lo(`coordinate `+e,t,r,l),t}function m(e){if(!(e instanceof h))throw Error(`EdwardsPoint expected`)}class h{static BASE=new h(o.Gx,o.Gy,i.ONE,i.mul(o.Gx,o.Gy));static ZERO=new h(i.ZERO,i.ONE,i.ONE,i.ZERO);static Fp=i;static Fn=a;X;Y;Z;T;constructor(e,t,n,r){this.X=p(`x`,e),this.Y=p(`y`,t),this.Z=p(`z`,n,!0),this.T=p(`t`,r),Object.freeze(this)}static CURVE(){return o}static fromAffine(e){if(e instanceof h)throw Error(`extended point not allowed`);let{x:t,y:n}=e||{};return p(`x`,t),p(`y`,n),new h(t,n,i.ONE,i.mul(t,n))}static fromBytes(e,t=!1){let n=i.BYTES,{a:r,d:a}=o;e=oo(Ba(e,n,`point`)),Qa(t,`zip215`);let s=oo(e),c=e[n-1];s[n-1]=c&-129;let f=ro(s),p=t?l:i.ORDER;lo(`point.y`,f,ms,p);let m=i.sqr(f),g=i.sub(m,i.ONE),_=i.sub(i.mulN(a,m),r),{isValid:v,value:y}=d(g,_);if(!v)throw Error(`bad point: invalid y coordinate`);let b=u(y),ee=!!(c&128);if(!t&&i.is0(y)&&ee)throw Error(`bad point: x=0 and x_0=1`);return ee!==b&&(y=i.neg(y)),h.fromAffine({x:y,y:f})}static fromHex(e,t=!1){return h.fromBytes(Ka(e),t)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(e=6,t=!0){return _.setWindowSize(this,e),t||this.multiply(gs),this}assertValidity(){let e=this,{a:t,d:n}=o;if(e.is0())throw Error(`bad point: ZERO`);let{X:r,Y:a,Z:s,T:c}=e,l=i.sqr(r),u=i.sqr(a),d=i.sqr(s),f=i.sqr(d),p=i.mul(l,t),m=i.mul(i.add(p,u),d),h=i.add(f,i.mul(n,i.mul(l,u)));if(!i.eql(m,h))throw Error(`bad point: equation left != right (1)`);let g=i.mul(r,a),_=i.mul(s,c);if(!i.eql(g,_))throw Error(`bad point: equation left != right (2)`)}equals(e){m(e);let{X:t,Y:n,Z:r}=this,{X:a,Y:o,Z:s}=e,c=i.mul(t,s),l=i.mul(a,r),u=i.mul(n,s),d=i.mul(o,r);return i.eql(c,l)&&i.eql(u,d)}is0(){return this.equals(h.ZERO)}negate(){return new h(i.neg(this.X),this.Y,this.Z,i.neg(this.T))}double(){let{X:e,Y:t,Z:n}=this,r=i.sqr(e),a=i.sqr(t),o=i.mul(i.sqr(n),gs),s=f(r),c=i.addN(e,t),l=i.sub(i.subN(i.sqr(c),r),a),u=i.addN(s,a),d=i.subN(u,o),p=i.subN(s,a),m=i.mul(l,d),g=i.mul(u,p),_=i.mul(l,p),v=i.mul(d,u);return new h(m,g,v,_)}add(e){m(e);let{d:t}=o,{X:n,Y:r,Z:a,T:s}=this,{X:c,Y:l,Z:u,T:d}=e,p=i.mul(n,c),g=i.mul(r,l),_=i.mul(i.mulN(s,t),d),v=i.mul(a,u),y=i.sub(i.subN(i.mulN(i.addN(n,r),i.addN(c,l)),p),g),b=i.subN(v,_),ee=i.addN(v,_),x=i.sub(g,f(p)),S=i.mul(y,b),C=i.mul(ee,x),w=i.mul(y,x),T=i.mul(b,ee);return new h(S,C,T,w)}subtract(e){return m(e),this.add(e.negate())}multiply(e){if(!a.isValidNot0(e))throw RangeError(`invalid scalar: expected 1 <= sc < curve.n`);let{p:t,f:n}=_.mulSecret(this,e,s,g);return g([t,n])[0]}multiplyUnsafe(e){if(!a.isValid(e))throw RangeError(`invalid scalar: expected 0 <= sc < curve.n`);return e===ms?h.ZERO:this.is0()||e===hs?this:_.mulUnsafe(this,e,g)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return _.mulUnsafe(this,o.n).is0()}toAffine(e){let t=this,n=e;if(n!=null&&typeof n!=`bigint`)throw TypeError(`"invertedZ" expected bigint, got type=`+typeof n);let{X:r,Y:a,Z:o}=t,s=t.is0();n??=s?i.create(vs):i.inv(o);let c=i.mul(r,n),l=i.mul(a,n),u=i.mul(o,n);if(s)return{x:i.ZERO,y:i.ONE};if(!i.eql(u,i.ONE))throw Error(`invZ was invalid`);return{x:c,y:l}}clearCofactor(){return s===hs?this:s===gs?this.double():s===_s?this.double().double():s===vs?this.double().double().double():this.multiplyUnsafe(s)}toBytes(){let{x:e,y:t}=this.toAffine(),n=i.toBytes(t);return n[n.length-1]|=u(e)?128:0,n}toHex(){return Wa(this.toBytes())}toString(){return`<Point ${this.is0()?`ZERO`:this.toHex()}>`}}let g=e=>Zo(h,e),_=new ls(h,c);return _.bits>=6&&h.BASE.precompute(6),Object.freeze(h.prototype),Object.freeze(h),h}function xs(e,t,n={}){if(Xo(e),typeof t!=`function`)throw Error(`"hash" function param is required`);let r=t,i=n;po(i,{},{adjustScalarBytes:`function`,randomBytes:`function`,domain:`function`,prehash:`function`,zip215:`boolean`,mapToCurve:`function`,toMontgomery:`function`,toMontgomerySecret:`function`});let{prehash:a}=i,{BASE:o,Fp:s,Fn:c}=e,l=r.outputLen,u=2*s.BYTES;if(l!==void 0&&(eo(l,`hash.outputLen`),l!==u))throw Error(`hash.outputLen must be ${u}, got ${l}`);let d=i.randomBytes===void 0?Ja:i.randomBytes,f=i.toMontgomery,p=i.toMontgomerySecret,m=i.adjustScalarBytes===void 0?e=>e:i.adjustScalarBytes,h=i.domain===void 0?(e,t,n)=>{if(Qa(n,`phflag`),t.length||n)throw Error(`Contexts/pre-hash are not supported`);return e}:i.domain;function g(e){return c.create(ro(e))}function _(e){let t=w.secretKey;Ba(e,w.secretKey,`secretKey`);let n=Ba(r(e),2*t,`hashedSecretKey`),i=m(n.slice(0,t));return{head:i,prefix:n.slice(t,2*t),scalar:g(i)}}function v(e){let{head:t,prefix:n,scalar:r}=_(e),i=o.multiply(r);return{head:t,prefix:n,scalar:r,point:i,pointBytes:i.toBytes()}}function y(e){return v(e).pointBytes}function b(e=Uint8Array.of(),...t){let n=Ga(...t);return g(r(h(n,Ba(e,void 0,`context`),!!a)))}function ee(e,t,n={}){po(n,{},{},`options`),e=oo(Ba(e,void 0,`message`)),a&&(e=a(e));let{prefix:r,scalar:i,pointBytes:s}=v(t),l=b(n.context,r,e),u=o.multiply(l).toBytes(),d=b(n.context,u,s,e),f=c.create(l+d*i);if(!c.isValid(f))throw Error(`sign failed: invalid s`);let p=Ga(u,c.toBytes(f));return Ba(p,w.signature,`result`)}let x={zip215:i.zip215};function S(t,n,r,i=x){po(i);let{context:s}=i,c=i.zip215===void 0?!!x.zip215:i.zip215,l=w.signature;t=Ba(t,l,`signature`),n=Ba(n,void 0,`message`),r=Ba(r,w.publicKey,`publicKey`),c!==void 0&&Qa(c,`zip215`),a&&(n=a(n));let u=l/2,d=t.subarray(0,u),f=ro(t.subarray(u,l)),p,m,h;try{p=e.fromBytes(r,c),m=e.fromBytes(d,c),h=o.multiplyUnsafe(f)}catch{return!1}if(!c&&p.isSmallOrder())return!1;let g=b(s,d,r,n);return m.add(p.multiplyUnsafe(g)).subtract(h).clearCofactor().is0()}let C=s.BYTES,w={secretKey:C,publicKey:C,signature:2*C,seed:C};function T(e){return e=e===void 0?d(w.seed):e,Ba(e,w.seed,`seed`)}function E(e){return qa(e)&&e.length===w.secretKey}function D(t,n){try{return!!e.fromBytes(t,n===void 0?x.zip215:n)}catch{return!1}}let O={getExtendedPublicKey:v,randomSecretKey:T,isValidSecretKey:E,isValidPublicKey:D,toMontgomery(t){if(f===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return f(e.fromBytes(t))},toMontgomerySecret(e){if(p===void 0)throw Error(`Montgomery conversion is not supported for this curve`);return p(e)}};return Object.freeze(w),Object.freeze(O),Object.freeze({keygen:ps(T,y),getPublicKey:y,sign:ee,verify:S,utils:O,Point:e,lengths:w})}
12
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
13
+ const Ss=BigInt(0),Cs=BigInt(1),ws=BigInt(2);function Ts(e,t){return e+t-(t>>Cs<<Cs)}function Es(e){let t=BigInt(6)*e;return(n,r,i)=>{let a=r+i,o=((t+i-r)*n+r)%e;return{x_2:o,x_3:a-o}}}function Ds(e){return po(e,{P:`bigint`,type:`string`,adjustScalarBytes:`function`,powPminus2:`function`},{randomBytes:`function`,scalarMultBase:`function`}),Object.freeze({...e})}function Os(e){let t=Ds(e),{P:n,type:r,adjustScalarBytes:i,powPminus2:a,randomBytes:o}=t,s=t.scalarMultBase,c=r===`x25519`;if(!c&&r!==`x448`)throw Error(`invalid type`);let l=o===void 0?Ja:o,u=c?255:448,d=Es(n),f=c?32:56,p=BigInt(c?9:5),m=BigInt(c?121665:39081),h=c?ws**BigInt(254):ws**BigInt(447),g=h+(c?BigInt(8)*(ws**BigInt(251)-Cs):BigInt(4)*(ws**BigInt(445)-Cs))+Cs,_=e=>Eo(e,n),v=y(p);function y(e){return ao(_(e),f)}function b(e){let t=oo(Ba(e,f,`uCoordinate`));return c&&(t[31]&=127),_(ro(t))}function ee(e){return ro(i(oo(Ba(e,f,`scalar`))))}let x=new Set(c?[Ss,Cs,n-Cs,BigInt(`325606250916557431795983626356110631294008115727848805560023387167927233504`),BigInt(`39382357235489614581723060781553021112529911719440698176882885853963445705823`)]:[Ss,Cs,n-Cs]);function S(e,t){let n=b(t);if(x.has(n))throw Error(`invalid private or public key received`);let r=E(n,ee(e));if(r===Ss)throw Error(`invalid private or public key received`);return y(r)}function C(e){if(s===void 0)return S(e,v);let t=ee(e);lo(`scalar`,t,h,g);let n=_(s(t));if(n===Ss)throw Error(`invalid private or public key received`);return y(n)}let w=C,T=S;function E(e,t){lo(`u`,e,Ss,n),lo(`scalar`,t,h,g);let r=t,i=e,o=Cs,s=Ss,c=e,l=Cs,f=r^r>>Cs;for(let e=BigInt(u-1);e>=Ss;e--){let t=Ts(n,f>>e);({x_2:o,x_3:c}=d(t,o,c)),{x_2:s,x_3:l}=d(t,s,l);let r=o+s,a=_(r*r),u=o-s,p=_(u*u),h=a-p,g=c+l,v=c-l,y=_(v*r),b=_(g*u),ee=y+b,x=y-b;c=_(ee*ee),l=_(i*_(x*x)),o=_(a*p),s=_(h*(a+_(m*h)))}let p=Ts(n,r);({x_2:o,x_3:c}=d(p,o,c)),{x_2:s,x_3:l}=d(p,s,l);let v=a(s);return _(o*v)}let D={secretKey:f,publicKey:f,seed:f},O=e=>(e=e===void 0?l(f):e,Ba(e,D.seed,`seed`),e),k={randomSecretKey:O};return Object.freeze(D),Object.freeze(k),Object.freeze({keygen:ps(O,w),getSharedSecret:T,getPublicKey:w,scalarMult:S,scalarMultBase:C,utils:k,GuBytes:v.slice(),lengths:D})}
14
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
15
+ const ks=BigInt(0),As=BigInt(1),js=BigInt(2),Ms=BigInt(3),Ns=BigInt(5),Ps=BigInt(8),Fs=BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed`),Is={p:Fs,n:BigInt(`0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed`),h:Ps,a:BigInt(`0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec`),d:BigInt(`0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3`),Gx:BigInt(`0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a`),Gy:BigInt(`0x6666666666666666666666666666666666666666666666666666666666666658`)};function Ls(e){let t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),a=Fs,o=e*e%a*e%a,s=Oo(Oo(o,js,a)*o%a,As,a)*e%a,c=Oo(s,Ns,a)*s%a,l=Oo(c,t,a)*c%a,u=Oo(l,n,a)*l%a,d=Oo(u,r,a)*u%a;return{pow_p_5_8:Oo(Oo(Oo(Oo(d,i,a)*d%a,i,a)*d%a,t,a)*c%a,js,a)*e%a,b2:o}}function Rs(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const zs=BigInt(`19681161376707505956807079304988542015446066515923890162744021073123829784752`);function Bs(e,t){let n=Fs,r=Eo(t*t*t,n),i=Ls(e*Eo(r*r*t,n)).pow_p_5_8,a=Eo(e*r*i,n),o=Eo(t*a*a,n),s=a,c=Eo(a*zs,n),l=o===e,u=o===Eo(-e,n),d=o===Eo(-e*zs,n);return l&&(a=s),(u||d)&&(a=c),Lo(a,n)&&(a=Eo(-a,n)),{isValid:l||u,value:a}}const Vs=bs(Is,{uvRatio:Bs}),Hs=Vs.Fp;function Us(e){let{y:t}=e;return Hs.toBytes(Hs.div(As+t,As-t))}function Ws(e){let t=Vs.Fp.BYTES;return na(e,t),Rs(Ra(e.subarray(0,t))).subarray(0,t)}function Gs(e){return xs(Vs,Ra,Object.assign({adjustScalarBytes:Rs,toMontgomery:Us,toMontgomerySecret:Ws,zip215:!0},e))}const Ks=Gs({}),qs=(()=>{let e=Fs,t=t=>{let{pow_p_5_8:n,b2:r}=Ls(t);return Eo(Oo(n,Ms,e)*r,e)};return Os({P:e,type:`x25519`,powPminus2:t,adjustScalarBytes:Rs,scalarMultBase:n=>{let r=Eo(n,Vs.Fn.ORDER);if(r===ks)return ks;let i=Vs.BASE.multiply(r);return Eo((i.Z+i.Y)*t(Eo(i.Z-i.Y,e)),e)}})})();var Js=class{oHash;iHash;blockLen;outputLen;canXOF=!1;finished=!1;destroyed=!1;constructor(e,t){if(ra(e),na(t,void 0,`key`),this.iHash=e.create(),typeof this.iHash.update!=`function`)throw Error(`expected Hash instance`);this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;let n=this.blockLen,r=new Uint8Array(n);r.set(t.length>n?e.create().update(t).digest():t);for(let e=0;e<r.length;e++)r[e]^=54;this.iHash.update(r),this.oHash=e.create();for(let e=0;e<r.length;e++)r[e]^=106;this.oHash.update(r),ca(r)}update(e){return oa(this),this.iHash.update(e),this}digestInto(e){oa(this),sa(e,this),this.finished=!0;let t=e.subarray(0,this.outputLen);this.iHash.digestInto(t),this.oHash.update(t),this.oHash.digestInto(t),this.destroy()}digest(){let e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||=Object.create(Object.getPrototypeOf(this),{});let{oHash:t,iHash:n,finished:r,destroyed:i,blockLen:a,outputLen:o,canXOF:s}=this;return e=e,e.finished=r,e.destroyed=i,e.blockLen=a,e.outputLen=o,e.canXOF=s,e.oHash=t._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Ys=(()=>{let e=((e,t,n)=>new Js(e,t).update(n).digest());return e.create=(e,t)=>new Js(e,t),e})(),Xs=Uint8Array.of(0),Zs=Uint8Array.of();function Qs(e,t,n,r=32,i){ra(e),ta(r,`length`),na(t,void 0,`prk`);let a=e.outputLen;if(t.length<a)throw Error(`"prk" must be at least HashLen octets`);if(r>255*a)throw Error(`Length must be <= 255*HashLen`);let o=Math.ceil(r/a);if(n===void 0?n=Zs:na(n,void 0,`info`),!o)return i&&ca(t),new Uint8Array;let s=i&&o===1?t:new Uint8Array(o*a),{iHash:c,oHash:l}=Ys.create(e,t),u=i?t:new Uint8Array(a),d=o>1?i?.iHash||e.create():void 0;for(let e=0;e<o-1;e++){Xs[0]=e+1;let t=c._cloneInto(d);e&&t.update(u),t.update(n).update(Xs).digestInto(u),l._cloneInto(d).update(u).digestInto(u),s.set(u,a*e)}if(Xs[0]=o,o>1&&c.update(u),c.update(n).update(Xs).digestInto(u),l.update(u).digestInto(u),s.set(u,a*(o-1)),c.destroy(),l.destroy(),d?.destroy(),u!==s&&ca(u),ca(Xs),r===s.length)return s;let f=s.slice(0,r);return ca(s),f}const $s=(e,t,n,r,i)=>{ra(e),n===void 0&&(n=new Uint8Array(e.outputLen));let a=Ys.create(e,n).update(t);return Qs(e,a.digest(),r,i,a)};function ec(){return tc(ya(32),ya(32),new Date().toISOString())}function tc(e,t,n){let r=Ks.keygen(e),i=qs.keygen(t);return{ed25519:{pub:r.publicKey,priv:r.secretKey},x25519:{pub:i.publicKey,priv:i.secretKey},createdAt:n}}const nc=F.object({v:F.literal(1),ed25519:F.object({pub:F.string(),priv:F.string()}),x25519:F.object({pub:F.string(),priv:F.string()}),createdAt:F.string()});function rc(e){return{v:1,ed25519:{pub:yr(e.ed25519.pub),priv:yr(e.ed25519.priv)},x25519:{pub:yr(e.x25519.pub),priv:yr(e.x25519.priv)},createdAt:e.createdAt}}function ic(e){let t=nc.safeParse(e);if(!t.success)throw new V(`malformed`,`identity: ${F.prettifyError(t.error)}`);let n=t.data,r,i,a,o;try{r=br(n.ed25519.pub),i=br(n.ed25519.priv),a=br(n.x25519.pub),o=br(n.x25519.priv)}catch{throw new V(`malformed`,`identity: bad base64url`)}if(r.length!==32||i.length!==32||a.length!==32||o.length!==32)throw new V(`malformed`,`identity: key length`);return{ed25519:{pub:r,priv:i},x25519:{pub:a,priv:o},createdAt:n.createdAt}}function ac(e){return xr(La(e)).slice(0,26)}function oc(e){return typeof e==`string`?vr(e):e}function sc(e,t){return Ks.sign(oc(t),e)}function cc(e,t,n){try{return Ks.verify(n,oc(t),e)}catch{return!1}}function lc(e,t,n,r){return`shellbell-auth-v1|${e}|${t}|${n}|${yr(r)}`}function uc(e,t,n,r){return{n:t,c:Mi(e,t,vr(r)).encrypt(n)}}function dc(e,t,n){return uc(e,ya(24),t,n)}function fc(e,t,n){try{return Mi(e,t.n,vr(n)).decrypt(t.c)}catch{throw new V(`crypto`,`aead open failed`)}}function pc(e,t){return $s(La,e,vr(`shellbell-pairing-v1`),vr(t),32)}function mc(e,t,n,r,i){let a=qs.getSharedSecret(e,t);if(a.every(e=>e===0))throw new V(`crypto`,`low-order point`);return $s(La,wr(a,n),vr(`shellbell-pair-v1`),vr(`${r}|${i}`),32)}function hc(e,t,n,r,i){let a=wr(t,n);return{kConn:$s(La,e,a,vr(`shellbell-conn-v1|${r}|${i}`),32),connTag:yr(La(a)).slice(0,22)}}function gc(e,t,n){if(e.length!==32||!/^[a-z2-7]{26}$/.test(t)||!/^[a-z2-7]{26}$/.test(n))throw new V(`malformed`,`invalid Noise PSK derivation input`);return $s(La,e,vr(`shellbell-noise-v2-psk`),vr(`${t}|${n}`),32)}function _c(e,t,n,r){return`1|${e}|${t}|${n}|${r}`}function vc(e,t){return`1|${e}|${t}|hello|0`}function yc(e,t,n){return`pairing-${e}|${t}|${n}`}function bc(e,t,n,r){return`shellbell-pair-bind-v1|${e}|${t}|${n}|${yr(r)}`}function xc(e){return e.match(/.{1,4}/g)?.join(` `)??e}const Sc=`notify-context-v1`,Cc=`notify-instance-v1`,wc=`shellbell-notification-v1`,Tc={plaintextBytes:1536,ciphertextBytes:1552,providerBytes:3500,freshnessMs:12e4,clockSkewMs:6e4,previousGenerationMs:3e5,sessions:500,encryptions:2**20};function Ec(e,t=e){return F.string().min(Math.ceil(e*4/3)).max(Math.ceil(t*4/3)).refine(n=>{try{let r=br(n);return r.length>=e&&r.length<=t&&yr(r)===n}catch{return!1}},`invalid canonical base64url`)}const Dc=Ec(16),Oc=F.array(F.string().min(1).max(32)).max(8),kc=F.number().int().nonnegative().max(2**53-1),Ac=F.string().regex(/^[1-9][0-9]{0,19}$/).refine(e=>/^[1-9][0-9]{0,19}$/.test(e)&&BigInt(e)<=18446744073709551615n,`sequence overflow`),jc=/[\p{Cc}\p{Cs}\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/u;function Mc(e){return F.string().min(1).max(e).refine(t=>t.trim().length>0&&!jc.test(t)&&vr(t).length<=e,`invalid notification label`)}const Nc=F.strictObject({computerName:Mc(128),sessionLabel:Mc(128),observedAt:kc,customName:Mc(256).optional(),repository:Mc(256).optional(),branch:Mc(256).optional(),title:Mc(256).optional(),shell:Mc(64).optional(),agentName:Mc(64).optional()}),Pc=F.strictObject({computerFp:W,phoneFp:W,generation:Dc,sessionId:F.string().min(1).max(128),eventId:Ec(16)}),Fc=F.enum([`command-finished`,`prompt-returned`,`agent-finished`,`agent-blocked`,`quiet`]),Ic=Pc.extend({context:Nc,reason:Fc,exitCode:F.number().int().optional(),durationMs:kc.optional(),instance:F.string().regex(/^[A-Za-z0-9._:-]{1,64}$/).optional(),issuedAt:kc,expiresAt:kc,sequence:Ac}).refine(e=>e.expiresAt>e.issuedAt&&e.expiresAt-e.issuedAt<=Tc.freshnessMs&&e.context.observedAt<=e.issuedAt,`invalid notification times`).refine(e=>vr(JSON.stringify(e)).length<=Tc.plaintextBytes,`notification plaintext exceeds byte limit`),Lc=Pc.extend({nonce:Ec(12),ciphertext:Ec(17,Tc.ciphertextBytes)});function Rc(e){return Pc.parse({computerFp:e.computerFp,phoneFp:e.phoneFp,generation:e.generation,sessionId:e.sessionId,eventId:e.eventId})}const zc=vr(`shellbell-pair-revocation-id-v2\0`),Bc=F.strictObject({v:F.literal(2),computerFp:W,phoneFp:W,pairId:U(32),signature:U(64)});function Vc(e){if(!(e instanceof Uint8Array)||e.length!==32)throw Error(`K_pair must be 32 bytes`);return La(wr(zc,e))}function Hc(e,t,n){return H([`shellbell-pair-revocation-v2`,e,t,n])}function Uc(e,t){if(e.length!==32||t.length!==32)return!1;let n=0;for(let r=0;r<32;r++)n|=(e[r]??0)^(t[r]??0);return n===0}function Wc(e,t){if(!Gc(e,t))return!1;try{return Uc(e.pairId,Vc(t.kPair))}catch{return!1}}function Gc(e,t){let n=Bc.safeParse(e);if(!n.success)return!1;let r=n.data;if(r.computerFp!==t.computerFp||r.phoneFp!==t.phoneFp||t.phoneEd25519Pub.length!==32||ac(t.phoneEd25519Pub)!==t.phoneFp)return!1;try{return cc(t.phoneEd25519Pub,Hc(r.computerFp,r.phoneFp,r.pairId),r.signature)}catch{return!1}}const Kc=F.enum([`agent`,`phone`,`pairing`]),qc=F.enum([`prompt`,`idle`,`exit`,`blocked`]),Jc=F.enum([`bad-sig`,`not-paired`,`fp-mismatch`,`no-agent`,`no-window`,`timeout`]),Yc=F.enum([`bad-code`,`declined`,`window-closed`,`no-agent`,`too-many`]),Xc=F.string().min(1).max(64),Zc=F.string().max(256).regex(/^(stun|turns?):[\x21-\x7e]+$/,`ICE server URL must be STUN or TURN`),Qc=F.object({urls:F.array(Zc).min(1).max(8),username:F.string().min(1).max(256).optional(),credential:F.string().min(1).max(256).optional()}).strict(),$c=F.array(Qc).max(4),el=F.number().int().min(0).max(6048e5),tl=F.string().min(1).max(64),nl=Zn;function rl(e){let t=e.environment??void 0;return e.provider===`fcm`?e.platform===`android`&&t===void 0:e.provider===`apns`&&e.platform===`ios`&&(t===`development`||t===`production`)}const il=F.strictObject({type:F.literal(`push-token`),token:F.string().min(1).max(4096),platform:F.enum([`ios`,`android`]),provider:F.enum([`fcm`,`apns`]).optional(),environment:F.enum([`development`,`production`]).optional(),enabled:F.boolean(),features:Oc.optional()}).superRefine((e,t)=>{if(e.provider===void 0){e.token.length>256&&t.addIssue({code:`custom`,path:[`token`],message:`legacy token exceeds 256 characters`}),e.environment!==void 0&&t.addIssue({code:`custom`,path:[`environment`],message:`environment requires APNs`});return}[...e.token].some(e=>e.charCodeAt(0)>127)&&t.addIssue({code:`custom`,path:[`token`],message:`native token must be ASCII`}),!rl(e)&&(e.provider===`fcm`?(e.platform!==`android`&&t.addIssue({code:`custom`,path:[`platform`],message:`FCM requires Android`}),e.environment!==void 0&&t.addIssue({code:`custom`,path:[`environment`],message:`FCM has no environment`})):(e.platform!==`ios`&&t.addIssue({code:`custom`,path:[`platform`],message:`APNs requires iOS`}),e.environment===void 0&&t.addIssue({code:`custom`,path:[`environment`],message:`APNs requires an environment`})))}).refine(e=>e.provider===void 0?e.token.length<=256&&e.environment===void 0:![...e.token].some(e=>e.charCodeAt(0)>127)&&rl(e),{message:`invalid push-token provider, platform, environment, or token`}),al=F.object({phoneFp:W,ed25519Pub:U(32),name:Xc,pairId:U(32).optional()}),ol=F.discriminatedUnion(`type`,[F.strictObject({type:F.literal(`notify-context`),sessionId:Pc.shape.sessionId,eventId:Pc.shape.eventId,kind:F.enum([`prompt`,`idle`,`blocked`]),exitCode:F.number().int().optional(),durationMs:F.number().int().nonnegative().optional(),boxes:F.array(Lc).max(10)}).refine(e=>new Set(e.boxes.map(e=>e.phoneFp)).size===e.boxes.length&&e.boxes.every(t=>t.sessionId===e.sessionId&&t.eventId===e.eventId&&t.computerFp===e.boxes[0]?.computerFp),`inconsistent notification recipients`),F.object({type:F.literal(`challenge`),nonce:U(32),connId:tl}),F.object({type:F.literal(`auth`),role:Kc,fp:W,ed25519Pub:U(32),sig:U(64),name:Xc,appVersion:F.string().max(32),gate:U(16).optional(),turn:F.literal(!1).optional()}),F.object({type:F.literal(`auth-ok`),role:Kc,agentOnline:F.boolean(),computerName:F.string().max(64).nullable(),serverTime:F.number(),minFrameMs:F.number().int().min(50).max(2e3),features:Oc.optional(),iceServers:$c.optional(),iceExpiresInMs:el.optional(),turnOff:F.literal(!0).optional()}),F.object({type:F.literal(`auth-fail`),reason:Jc}),F.object({type:F.literal(`presence`),agentOnline:F.boolean(),computerName:F.string().max(64).nullable()}),F.object({type:F.literal(`unpaired`),phoneFps:F.array(W).max(10),proofs:F.array(Bc).max(10).optional()}),F.object({type:F.literal(`phones`),connected:F.array(F.object({phoneFp:W,connId:tl,name:Xc})).max(10)}),F.object({type:F.literal(`pairings-sync`),phones:F.array(al).max(10)}),F.object({type:F.literal(`revocation-ack`),phoneFp:W,pairId:U(32)}),F.object({type:F.literal(`pairing-open`),gateHash:U(32),expiresAt:F.number()}),F.object({type:F.literal(`pairing-close`)}),F.object({type:F.literal(`pairing-request`),phoneFp:W,box:nl}),F.object({type:F.literal(`pairing-response`),phoneFp:W,box:nl}),F.object({type:F.literal(`pairing-reject`),phoneFp:W,reason:Yc}),F.object({type:F.literal(`pairing-add`),phoneFp:W,ed25519Pub:U(32),name:Xc,pairId:U(32).optional()}),F.object({type:F.literal(`unpair`),phoneFp:W,proof:Bc.optional()}),F.object({type:F.literal(`revocation-submit`),phoneEd25519Pub:U(32),proof:Bc}),F.object({type:F.literal(`revocation-receipt`),phoneFp:W,pairId:U(32),status:F.enum([`stored`,`absent`,`stale`,`unavailable`])}),il,F.object({type:F.literal(`lease`),ttlMs:F.number().int().min(0).max(12e4)}),F.object({type:F.literal(`ice-refresh`)}),F.object({type:F.literal(`ice-servers`),iceServers:$c,iceExpiresInMs:el}),F.object({type:F.literal(`notify`),sessionId:F.string().min(1).max(128),kind:F.enum([`prompt`,`idle`,`blocked`]),exitCode:F.number().int().optional(),durationMs:F.number().int().nonnegative().optional()}),F.object({type:F.literal(`phone-connected`),phoneFp:W,connId:tl,name:Xc}),F.object({type:F.literal(`phone-disconnected`),phoneFp:W,connId:tl}),F.object({type:F.literal(`error`),code:F.string().max(64),message:F.string().max(512)})]);function sl(e){let t=ol.safeParse(e);if(!t.success)throw new V(`malformed`,`ctrl: ${F.prettifyError(t.error)}`);return t.data}const cl={enter:`\r`,tab:` `,"shift-tab":`\x1B[Z`,esc:`\x1B`,backspace:``,delete:`\x1B[3~`,up:`\x1B[A`,down:`\x1B[B`,right:`\x1B[C`,left:`\x1B[D`,home:`\x1B[H`,end:`\x1B[F`,"page-up":`\x1B[5~`,"page-down":`\x1B[6~`,"ctrl-space":`\0`,...Object.fromEntries(`abcdefghijklmnopqrstuvwxyz`.split(``).map((e,t)=>[`ctrl-${e}`,String.fromCharCode(t+1)])),f1:`\x1BOP`,f2:`\x1BOQ`,f3:`\x1BOR`,f4:`\x1BOS`,f5:`\x1B[15~`,f6:`\x1B[17~`,f7:`\x1B[18~`,f8:`\x1B[19~`,f9:`\x1B[20~`,f10:`\x1B[21~`,f11:`\x1B[23~`,f12:`\x1B[24~`},ll=F.enum(Object.keys(cl));function ul(e){return cl[e]}const dl=new Uint8Array,fl=vr(`Noise_KKpsk2_25519_ChaChaPoly_SHA256`),pl=(1n<<64n)-2n,ml=65535,hl=Symbol(`Noise transport factory`);let gl={seal:(e,t,n,r)=>ji(e,t,n).encrypt(r),open:(e,t,n,r)=>ji(e,t,n).decrypt(r)};function _l(){return globalThis.process?.env?.NODE_ENV===`test`}function vl(e){if(e<0n||e>pl)throw Error(`invalid Noise sequence or reserved nonce`)}function yl(e){vl(e);let t=new Uint8Array(8);return new DataView(t.buffer).setBigUint64(0,e,!0),t}function bl(e){if(e.length!==8)throw Error(`invalid Noise sequence length`);let t=new DataView(e.buffer,e.byteOffset,8).getBigUint64(0,!0);return vl(t),t}function xl(e){let t=new Uint8Array(12);return t.set(yl(e),4),t}function Sl(e,t,n){let r=Ys(La,e,t),i=Ys(La,r,Uint8Array.of(1)),a=Ys(La,r,wr(i,Uint8Array.of(2))),o=n===2?[i,a]:[i,a,Ys(La,r,wr(a,Uint8Array.of(3)))];return r.fill(0),o}function Cl(e,t){let n=qs.getSharedSecret(e,t);if(n.every(e=>e===0))throw Error(`invalid Noise public key`);return n}var wl=class{chainingKey=La(fl);hash=this.chainingKey.slice();key=null;nonce=0n;get handshakeHash(){return this.hash.slice()}mixHash(e){this.hash=La(wr(this.hash,e))}setKey(e){this.key?.fill(0),this.key=e,this.nonce=0n}mixKey(e){let[t,n]=Sl(this.chainingKey,e,2);this.chainingKey.fill(0),this.chainingKey=t,this.setKey(n)}mixKeyAndHash(e){let[t,n,r]=Sl(this.chainingKey,e,3);this.chainingKey.fill(0),this.chainingKey=t,this.mixHash(n),n.fill(0),this.setKey(r)}encryptAndHash(e){if(!this.key)throw Error(`Noise handshake key missing`);let t=ji(this.key,xl(this.nonce),this.hash).encrypt(e);return this.nonce+=1n,this.mixHash(t),t}decryptAndHash(e){if(!this.key)throw Error(`Noise handshake key missing`);let t=ji(this.key,xl(this.nonce),this.hash).decrypt(e);return this.nonce+=1n,this.mixHash(e),t}split(){let[e,t]=Sl(this.chainingKey,dl,2);return this.close(),[e,t]}close(){this.chainingKey.fill(0),this.hash.fill(0),this.key?.fill(0),this.key=null}},Tl=class{sendKey;receiveKey;lastSent=-1n;lastReceived=-1n;closed=!1;constructor(e,t,n,r){if(r!==hl)throw Error(`Noise transport factory required`);this.sendKey=new Uint8Array(e===`initiator`?t:n),this.receiveKey=new Uint8Array(e===`initiator`?n:t),t.fill(0),n.fill(0)}seal(e,t,n=dl){if(this.closed)throw Error(`Noise transport closed`);if(t.length>65519)throw Error(`Noise message too large`);if(vl(e),e<=this.lastSent)throw Error(`Noise send sequence reuse`);let r=gl.seal(this.sendKey,xl(e),n,t);return this.lastSent=e,r}open(e,t,n=dl){if(this.closed)throw Error(`Noise transport closed`);if(t.length<16||t.length>ml)throw Error(`Noise message length invalid`);if(vl(e),e<=this.lastReceived)throw Error(`Noise receive sequence replay`);let r=gl.open(this.receiveKey,xl(e),n,t);return this.lastReceived=e,r}close(){this.closed||(this.closed=!0,this.sendKey.fill(0),this.receiveKey.fill(0))}},El=class{role;staticPrivate;remoteStatic;psk;ephemeralPrivate;remoteEphemeral=null;symmetric=new wl;finalHash=null;phase=`first`;constructor(e){if(e.role!==`initiator`&&e.role!==`responder`)throw Error(`invalid Noise role`);if(e.ephemeralPrivate&&!_l())throw Error(`fixed Noise ephemeral key is test-only`);for(let t of[e.staticPrivate,e.remoteStatic,e.psk])if(t.length!==32)throw Error(`Noise key must be 32 bytes`);if(e.prologue.length>1024)throw Error(`Noise prologue too large`);if(e.ephemeralPrivate&&e.ephemeralPrivate.length!==32)throw Error(`Noise ephemeral key must be 32 bytes`);this.role=e.role,this.staticPrivate=new Uint8Array(e.staticPrivate),this.remoteStatic=new Uint8Array(e.remoteStatic),this.psk=new Uint8Array(e.psk),this.ephemeralPrivate=e.ephemeralPrivate?new Uint8Array(e.ephemeralPrivate):qs.utils.randomSecretKey(),this.symmetric.mixHash(e.prologue);let t=qs.getPublicKey(this.staticPrivate);this.symmetric.mixHash(this.role===`initiator`?t:this.remoteStatic),this.symmetric.mixHash(this.role===`responder`?t:this.remoteStatic)}get handshakeHash(){if(this.finalHash)return this.finalHash.slice();if(this.phase!==`complete`)throw Error(`Noise handshake not complete`);return this.symmetric.handshakeHash}write(e=dl){if(e.length>0&&!_l())throw Error(`Noise handshake payloads are test-only`);if(this.role===`initiator`&&this.phase!==`first`||this.role===`responder`&&this.phase!==`second`)throw Error(`Noise handshake message order`);if(e.length>65487)throw Error(`Noise handshake payload too large`);try{let t=qs.getPublicKey(this.ephemeralPrivate);if(this.symmetric.mixHash(t),this.symmetric.mixKey(t),this.role===`initiator`)this.symmetric.mixKey(Cl(this.ephemeralPrivate,this.remoteStatic)),this.symmetric.mixKey(Cl(this.staticPrivate,this.remoteStatic));else{if(!this.remoteEphemeral)throw Error(`Noise peer ephemeral key missing`);this.symmetric.mixKey(Cl(this.ephemeralPrivate,this.remoteEphemeral)),this.symmetric.mixKey(Cl(this.ephemeralPrivate,this.remoteStatic)),this.symmetric.mixKeyAndHash(this.psk)}let n=wr(t,this.symmetric.encryptAndHash(e));return this.phase=this.role===`initiator`?`second`:`complete`,n}catch(e){throw this.close(),e}}read(e){if(this.role===`responder`&&this.phase!==`first`||this.role===`initiator`&&this.phase!==`second`)throw Error(`Noise handshake message order`);if(e.length<48||e.length>ml)throw this.close(),Error(`Noise handshake message length`);if(e.length!==48&&!_l())throw this.close(),Error(`Noise handshake payloads are test-only`);try{let t=new Uint8Array(e.subarray(0,32));this.remoteEphemeral=t,this.symmetric.mixHash(t),this.symmetric.mixKey(t),this.role===`responder`?(this.symmetric.mixKey(Cl(this.staticPrivate,t)),this.symmetric.mixKey(Cl(this.staticPrivate,this.remoteStatic))):(this.symmetric.mixKey(Cl(this.ephemeralPrivate,t)),this.symmetric.mixKey(Cl(this.staticPrivate,t)),this.symmetric.mixKeyAndHash(this.psk));let n=this.symmetric.decryptAndHash(e.subarray(32));return this.phase=this.role===`responder`?`second`:`complete`,n}catch(e){throw this.close(),e}}split(){if(this.phase!==`complete`)throw Error(`Noise handshake not complete`);this.finalHash=this.symmetric.handshakeHash;let[e,t]=this.symmetric.split();return this.close(),new Tl(this.role,e,t,hl)}close(){this.phase!==`failed`&&(this.phase=`failed`,this.staticPrivate.fill(0),this.remoteStatic.fill(0),this.psk.fill(0),this.ephemeralPrivate.fill(0),this.remoteEphemeral?.fill(0),this.symmetric.close())}};const Dl=`shellbell-v2-key-confirm`,Ol=Symbol(`v2 handshake factory`),kl=Symbol(`v2 session factory`),Al=U(16).refine(e=>e.some(e=>e!==0),{message:`v2 ID must not be zero`}),jl=U(8).refine(e=>{try{return bl(e)>0n}catch{return!1}},{message:`invalid v2 route generation`}),Ml={computerFp:W,phoneFp:W,sessionId:Al,attemptId:Al,generation:jl},Nl=F.discriminatedUnion(`route`,[F.object({...Ml,route:F.literal(`relay`)}).strict(),F.object({...Ml,route:F.literal(`direct`),phoneDtls:U(32),computerDtls:U(32)}).strict()]),Pl=F.custom(e=>e instanceof Uint8Array&&e.length>=16&&e.length<=60016,{message:`invalid v2 ciphertext length`}),Fl=F.object({v:F.literal(2),type:F.enum([`confirm`,`data`]),sessionId:Al,generation:jl,seq:U(8),ciphertext:Pl}).strict();function Il(e){let t=Nl.parse(e),n={...t,sessionId:new Uint8Array(t.sessionId),attemptId:new Uint8Array(t.attemptId),generation:new Uint8Array(t.generation),...t.route===`direct`&&{phoneDtls:new Uint8Array(t.phoneDtls),computerDtls:new Uint8Array(t.computerDtls)}};return Nl.parse(n)}function Ll(e){let t=Nl.parse(e);return H([`shellbell-session-v2`,2,`phone`,`computer`,t.computerFp,t.phoneFp,t.sessionId,t.attemptId,t.generation,t.route,t.route===`direct`?t.phoneDtls:null,t.route===`direct`?t.computerDtls:null])}function Rl(e,t,n){return H([`shellbell-v2-frame`,e.sessionId,e.attemptId,e.generation,e.route,t,n.type,n.seq])}function zl(e){return e===`phone`?`computer`:`phone`}function Bl(e){let t=H(Fl.parse(e));if(t.length>61e3)throw new V(`malformed`,`v2 frame too large`);return t}function Vl(e){if(e.length>61e3)throw new V(`malformed`,`v2 frame too large`);return Fl.parse(Gn(e))}var Hl=class{context;role;noise;finished=!1;constructor(e,t,n,r){if(this.context=e,this.role=t,this.noise=n,r!==Ol)throw Error(`v2 handshake factory required`)}write(){if(this.finished)throw Error(`v2 handshake finished`);return this.noise.write()}read(e){if(this.finished)throw Error(`v2 handshake finished`);if(e.length!==48)throw Error(`v2 empty-payload handshake must be 48 bytes`);if(this.noise.read(e).length!==0)throw Error(`v2 handshake payload forbidden`)}finish(){if(this.finished)throw Error(`v2 handshake already finished`);let e=this.noise.handshakeHash,t=this.noise.split();return this.finished=!0,new Wl(this.context,this.role,t,e,kl)}close(){this.finished=!0,this.noise.close()}};function Ul(e,t,n){if(t!==`phone`&&t!==`computer`)throw Error(`invalid v2 role`);let r=Il(e),i=gc(n.pairKey,r.computerFp,r.phoneFp);try{return new Hl(r,t,new El({role:t===`phone`?`initiator`:`responder`,staticPrivate:n.staticPrivate,remoteStatic:n.remoteStatic,psk:i,prologue:Ll(r)}),Ol)}finally{i.fill(0)}}var Wl=class{context;role;transport;handshakeHash;sentConfirmation=!1;receivedConfirmation=!1;dtlsVerified=!1;nextSequence=0n;lastReceived=-1n;closed=!1;constructor(e,t,n,r,i){if(this.context=e,this.role=t,this.transport=n,this.handshakeHash=r,i!==kl)throw Error(`v2 session factory required`)}get ready(){return!this.closed&&this.sentConfirmation&&this.receivedConfirmation&&(this.context.route===`relay`||this.dtlsVerified)}get description(){return Il(this.context)}get senderRole(){return this.role}verifyRemoteDtls(e){if(this.closed)throw Error(`v2 session closed`);if(this.context.route!==`direct`)throw Error(`relay route has no DTLS certificate`);let t=this.role===`phone`?this.context.computerDtls:this.context.phoneDtls;if(e.length!==32||!Tr(e,t))throw this.close(),Error(`remote DTLS certificate mismatch`);this.dtlsVerified=!0}frame(e,t){if(this.closed)throw Error(`v2 session closed`);if(t.length>6e4)throw Error(`v2 data too large`);let n=yl(this.nextSequence),r={v:2,type:e,sessionId:this.context.sessionId.slice(),generation:this.context.generation.slice(),seq:n,ciphertext:new Uint8Array};return r.ciphertext=this.transport.seal(this.nextSequence,t,Rl(this.context,this.role,r)),this.nextSequence+=1n,r}openFrame(e,t){if(this.closed)throw Error(`v2 session closed`);let n=Fl.parse(e);if(n.type!==t)throw Error(`wrong v2 frame type`);if(!Tr(n.sessionId,this.context.sessionId)||!Tr(n.generation,this.context.generation))throw Error(`wrong v2 session or route generation`);let r=bl(n.seq),i=this.transport.open(r,n.ciphertext,Rl(this.context,zl(this.role),n));if(r!==this.lastReceived+1n)throw i.fill(0),this.close(),Error(`v2 sequence gap requires resync`);return this.lastReceived=r,i}confirmation(){if(this.sentConfirmation)throw Error(`v2 confirmation already sent`);let e=this.frame(`confirm`,H([Dl,this.handshakeHash,this.role]));return this.sentConfirmation=!0,e}acceptConfirmation(e){try{if(this.receivedConfirmation)throw Error(`v2 confirmation already received`);if(bl(e.seq)!==0n)throw Error(`v2 confirmation sequence must be 0`);let t=Gn(this.openFrame(e,`confirm`));if(!Array.isArray(t)||t.length!==3||t[0]!==Dl||!(t[1]instanceof Uint8Array)||!Tr(t[1],this.handshakeHash)||t[2]!==zl(this.role))throw Error(`invalid v2 key confirmation`);this.receivedConfirmation=!0}catch(e){throw this.close(),e}}seal(e){if(this.closed)throw Error(`v2 session closed`);if(!this.ready)throw Error(`v2 key confirmation incomplete`);return this.frame(`data`,e)}open(e){if(this.closed)throw Error(`v2 session closed`);if(!this.ready)throw Error(`v2 key confirmation incomplete`);if(bl(e.seq)<1n)throw Error(`v2 data sequence must be positive`);return this.openFrame(e,`data`)}close(){this.closed||(this.closed=!0,this.transport.close(),this.handshakeHash.fill(0))}};const Gl=`shellbell-v2-route-payload`,Kl=59e3,ql={terminalBytes:Kl,signalBytes:3e4,controlBytes:512,payloadBytes:6e4,attemptMs:15e3,directAttempts:32,wireSessions:128},Jl={transitionId:Al,target:F.object({route:F.enum([`relay`,`direct`]),sessionId:Al,attemptId:Al,generation:jl}).strict()},Yl=F.discriminatedUnion(`type`,[F.object({type:F.literal(`route.prepare`),...Jl}).strict(),F.object({type:F.literal(`route.prepared`),...Jl}).strict(),F.object({type:F.literal(`route.commit`),...Jl}).strict(),F.object({type:F.literal(`route.committed`),...Jl}).strict(),F.object({type:F.literal(`route.abort`),...Jl,reason:F.enum([`cancelled`,`timeout`,`not-ready`,`candidate-failed`])}).strict()]);function Xl(e,t){return e instanceof Uint8Array&&e.length>0&&e.length<=t}function Zl(e){let t;if(e.kind===`control`){if(t=Yl.parse(e.control),H(t).length>ql.controlBytes)throw new V(`malformed`)}else{if(!Xl(e.bytes,e.kind===`terminal`?ql.terminalBytes:ql.signalBytes))throw new V(`malformed`);t=e.bytes}let n=H([Gl,e.kind,t]);if(n.length>ql.payloadBytes)throw new V(`malformed`);return n}function Ql(e){let t=mr(e,ql.payloadBytes,{allowBytes:!0});if(!Array.isArray(t)||t.length!==3||t[0]!==Gl)throw new V(`malformed`);if(t[1]===`control`){if(H(t[2]).length>ql.controlBytes)throw new V(`malformed`);let e=Yl.parse(t[2]);return{kind:`control`,control:{...e,transitionId:e.transitionId.slice(),target:{route:e.target.route,sessionId:e.target.sessionId.slice(),attemptId:e.target.attemptId.slice(),generation:e.target.generation.slice()}}}}if(t[1]!==`terminal`&&t[1]!==`signal`||!Xl(t[2],t[1]===`terminal`?ql.terminalBytes:ql.signalBytes))throw new V(`malformed`);return{kind:t[1],bytes:t[2].slice()}}const $l=`web-v1`,J={connectionWindow:131072,streamWindow:131072,frameAllowance:256,dataBytes:16384,headHeaderBytes:16384,headPairs:128,headBodyBytes:4096,openBytes:24576,pathBytes:8192,originBytes:256,creditFlushBytes:8192,creditFlushMs:20,streamsPerPhone:24,detailChars:120,pages:16,iconBytes:65536,iconChunkBytes:16384,iconDimension:1024},eu=F.number().int().min(0).max(4294967295),tu=eu.min(1),nu=F.string().regex(/^[a-z0-9-]{1,32}$/),ru=F.string().min(1).max(128).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/),iu=F.union([F.strictObject({page:nu}),F.strictObject({origin:F.string().min(1).max(J.originBytes)})]),au=F.tuple([ru,U()]),ou=e=>e.reduce((e,[t,n])=>e+t.length+n.byteLength+4,0),su=F.enum([`refused`,`unreachable`,`timeout`,`too-large`,`locked`,`closed`,`not-found`,`start-failed`,`start-timeout`]),cu=F.string().min(1).max(J.detailChars).refine(e=>[...e].every(e=>e.charCodeAt(0)>=32&&e.charCodeAt(0)!==127)),lu=F.object({reason:cu,fix:cu.optional()}),uu=F.object({id:nu,name:cu.max(40),description:cu.optional(),address:F.string().min(1).max(J.originBytes).optional(),icon:F.string().regex(/^[a-f0-9]{64}$/).optional(),iconIssue:lu.optional(),skipped:lu.optional()}),du=F.array(uu).max(J.pages),fu=F.strictObject({type:F.literal(`web.icon`),page:nu,hash:F.string().regex(/^[a-f0-9]{64}$/)}),pu=F.strictObject({type:F.literal(`web.icon.data`),page:nu,hash:F.string().regex(/^[a-f0-9]{64}$/),offset:F.number().int().min(0).max(J.iconBytes).optional(),total:F.number().int().min(1).max(J.iconBytes).optional(),bytes:U().refine(e=>e.byteLength>0&&e.byteLength<=J.iconChunkBytes).optional()}).refine(e=>e.bytes===void 0?e.offset===void 0&&e.total===void 0:e.offset!==void 0&&e.total!==void 0&&e.offset+e.bytes.byteLength<=e.total,`icon chunk must fit its declared image`),mu=F.strictObject({authority:F.string().min(1).max(J.originBytes),family:F.union([F.literal(4),F.literal(6)])}),hu=F.discriminatedUnion(`type`,[fu,pu,F.strictObject({type:F.literal(`web.open`),stream:tu,target:iu,method:ru.max(16),path:F.string().min(1).max(J.pathBytes).startsWith(`/`),headers:F.array(au).max(J.headPairs),body:F.boolean(),upgrade:F.boolean()}).refine(e=>e.path.length+ou(e.headers)<=J.openBytes,`web.open path and headers too large`),F.strictObject({type:F.literal(`web.head`),stream:tu,status:F.number().int().min(101).max(599),headers:F.array(au).max(J.headPairs),bytes:U().refine(e=>e.byteLength<=J.headBodyBytes).optional(),end:F.boolean().optional(),authority:mu.optional()}).refine(e=>e.status===101||e.status>=200,`web.head status`).refine(e=>ou(e.headers)<=J.headHeaderBytes,`web.head headers too large`),F.strictObject({type:F.literal(`web.data`),stream:tu,bytes:U().refine(e=>e.byteLength>0&&e.byteLength<=J.dataBytes)}),F.strictObject({type:F.literal(`web.end`),stream:tu}),F.strictObject({type:F.literal(`web.credit`),stream:eu,bytes:eu.min(1)}),F.strictObject({type:F.literal(`web.reset`),stream:tu,reason:su,detail:cu.optional()}),F.strictObject({type:F.literal(`web.view`),target:iu,open:F.boolean()})]),gu=[`web.open`,`web.head`,`web.data`,`web.icon.data`];function _u(e){return gu.includes(e)}function vu(e){return e+J.frameAllowance}function yu(e){return _u(e.type)?vu(H(e).byteLength):0}function bu(e){return e.type===`web.data`?e.bytes.byteLength:e.type===`web.head`?e.bytes?.byteLength??0:0}const xu=new Set([`connection`,`keep-alive`,`proxy-authenticate`,`proxy-authorization`,`proxy-connection`,`te`,`trailer`,`transfer-encoding`,`upgrade`]),Su=F.enum([`iterm2`,`tmux`,`herdr`]),Cu=F.string().regex(/^[a-z][a-z0-9-]{0,31}$/),wu={iterm2:`iTerm2`,tmux:`tmux`,herdr:`Herdr`},Tu=F.enum([`darwin`,`linux`,`win32`,`unknown`]),Eu=F.number().int().min(0).max(255),Du=F.union([Eu,F.tuple([Eu,Eu,Eu])]),Ou=F.object({t:F.string().max(4096),fg:Du.optional(),bg:Du.optional(),b:F.boolean().optional(),i:F.boolean().optional(),u:F.boolean().optional(),s:F.boolean().optional(),f:F.boolean().optional(),n:F.number().int().min(0).max(4096).optional()}),ku=F.object({r:F.array(Ou).max(2048),w:F.boolean().optional()}),Au=F.object({x:F.number().int(),y:F.number().int()}),ju=F.object({subscribe:F.boolean(),prompts:F.boolean(),createSession:F.boolean(),focus:F.boolean(),history:F.boolean(),absoluteLines:F.boolean(),mouseClick:F.boolean().optional(),terminalInput:F.boolean().optional(),terminalPaste:F.boolean().optional(),vtStream:F.boolean().optional()}),Mu=F.string().min(1).max(64).refine(e=>[...e].every(e=>e.charCodeAt(0)>=32&&e.charCodeAt(0)!==127)),Nu=F.object({name:Cu,label:Mu,capabilities:ju,connected:F.boolean(),launchable:F.boolean()}),Pu=F.array(Nu).max(32).refine(e=>new Set(e.map(e=>e.name)).size===e.length,`adapter IDs must be unique`),Fu=F.object({backend:Cu,host:Cu,label:Mu}),Iu=F.array(Fu).max(64).refine(e=>new Set(e.map(e=>`${e.backend}:${e.host}`)).size===e.length,`launch targets must be unique`),Lu=F.object({backend:Cu,reason:F.string().min(1).max(240).refine(e=>[...e].every(e=>e.charCodeAt(0)>=32&&e.charCodeAt(0)!==127))}),Ru=F.array(Lu).max(16).refine(e=>new Set(e.map(e=>e.backend)).size===e.length,`one launch issue per backend`),zu=F.enum([`not-installed`,`not-running`,`no-session`,`api-off`,`needs-consent`,`connecting`,`automation-denied`,`iterm2-denied`,`timed-out`,`too-old`,`limited`,`failed`]),Bu=F.strictObject({name:Cu,connected:F.boolean(),issue:zu.optional(),detail:Lu.shape.reason.optional()}),Vu=F.array(Bu).max(16).refine(e=>new Set(e.map(e=>e.name)).size===e.length),Hu=[`iterm2`,`ghostty`];function Uu(e,t){let n=e=>{let t=Hu.indexOf(e);return t===-1?Hu.length:t};return n(e)-n(t)||e.localeCompare(t)}function Wu(e,t=[]){return t.filter(t=>t.backend===e).sort((e,t)=>Uu(e.host,t.host))[0]}const Gu=F.object({column:F.number().int().min(0).max(G.cols-1),row:F.number().int().min(0).max(G.rows-1),cols:F.number().int().min(1).max(G.cols),rows:F.number().int().min(1).max(G.rows),button:F.enum([`left`,`right`,`middle`]),modifiers:F.number().int().min(0).max(7)}),Ku=F.enum([`unknown`,`editing`,`running`,`finished`,`blocked`]),qu=F.string().min(1).max(64),Ju=F.enum([`no-history`,`not-started`,`agent-exited`,`not-supported`,`lookup-limit`,`ambiguous`]),Yu=F.string().min(1).max(32),Xu=F.object({state:F.enum([`finding`,`found`,`none`]),id:Yu.optional(),agent:F.string().min(1).max(32).optional(),reason:Ju.optional()}).refine(e=>(e.state===`found`||e.state===`none`&&e.reason===`not-started`)==(e.id!==void 0),`A chat has an id exactly when it is found or not yet started`).refine(e=>e.reason===void 0||e.state===`none`,`Only a chat that is none has a reason`),Zu=F.object({chat:Yu}),Qu=F.enum([`conversation-changed`,`waiting-for-you`,`unchecked`]),$u=F.object({id:tr,backend:Cu,title:F.string().max(256),cwd:F.string().max(1024).optional(),cols:F.number().int().positive(),rows:F.number().int().positive(),windowId:F.string().max(128),windowNumber:F.number().int(),tabId:F.string().max(128),tabIndex:F.number().int(),paneIndex:F.number().int(),isFocusedOnMac:F.boolean(),state:Ku,project:F.string().min(1).max(128).optional(),windowLabel:F.string().min(1).max(128).optional(),agent:F.object({kind:F.string().min(1).max(32),task:F.string().min(1).max(256).optional(),reportsState:F.literal(!0).optional()}).optional(),stateSince:F.number().int().nonnegative().optional(),activeAt:F.number().int().nonnegative().optional(),alternateScreen:F.boolean().optional(),shownIn:F.array(Mu).min(1).max(4).optional(),instance:F.string().min(1).max(64).optional(),chat:Xu.optional()}),ed=Object.freeze({minCols:40,maxCols:240,minRows:24,maxRows:100}),td=F.object({cols:F.number().int().min(ed.minCols).max(ed.maxCols),rows:F.number().int().min(ed.minRows).max(ed.maxRows)}),nd=F.union([F.object({kind:F.literal(`tab`),backend:Cu,windowId:F.string().max(128).optional(),host:Cu.optional(),initialSize:td.optional(),near:F.literal(`focused`).optional(),explicit:F.boolean().optional()}).refine(e=>e.initialSize===void 0||e.windowId===void 0,`initial size applies only to a new independent window`).refine(e=>e.near===void 0||e.windowId===void 0,`a tab goes either in a named window or next to the focused session`),F.object({kind:F.literal(`split`),sessionId:tr,direction:F.enum([`vertical`,`horizontal`])})]),rd=F.enum([`tab`,`window`,`split`]),id={sessionId:tr,cursor:Au,scrollbackTotal:F.number().int().nonnegative(),gen:F.number().int().nonnegative()},ad=`alive-v1`,od=5e3,sd=F.object({type:F.literal(`hello`),agentVersion:F.string().max(32),features:Oc.optional(),conversationEnabled:F.boolean().optional(),hostPlatform:Tu.optional(),launchableBackends:F.array(Cu).max(4).optional(),pages:du.optional(),backendCatalog:Pu.optional(),sessionLaunchTargets:Iu.optional(),sessionLaunchIssues:Ru.optional(),terminalSetup:Vu.optional(),backends:F.array(F.object({name:Cu,capabilities:ju})).max(4),computerName:F.string().max(64),accent:F.string().max(32)}),cd=F.object({type:F.literal(`sessions`),list:F.array($u).max(500),complete:F.boolean().optional()}),ld=F.object({type:F.literal(`event`),sessionId:tr,kind:qc,exitCode:F.number().int().optional(),durationMs:F.number().int().nonnegative().optional(),command:F.string().max(512).optional(),at:F.number()}),ud=F.discriminatedUnion(`type`,[F.object({type:F.literal(`notification.enroll`),generation:Dc,features:Oc.optional()}),F.object({type:F.literal(`notification.enrolled`),generation:Dc}),F.object({type:F.literal(`conn.hello`),n:U(16),features:F.array(F.string().min(1).max(32)).max(8).optional()}),F.object({type:F.literal(`session.v2.bootstrap`),bytes:U().refine(e=>e.length>0&&e.length<=1024)}),sd,F.object({type:F.literal(`alive`)}),cd,F.object({type:F.literal(`screen.snapshot`),...id,cols:F.number().int().positive(),rows:F.number().int().positive(),lines:F.array(ku).max(1e3),reset:F.boolean().optional(),degraded:F.boolean().optional()}),F.object({type:F.literal(`screen.diff`),...id,scroll:F.number().int().nonnegative().max(1e3),changed:F.array(F.object({i:F.number().int().nonnegative(),line:ku})).max(1e3)}),F.object({type:F.literal(`history`),sessionId:tr,before:F.number().int().nonnegative(),lines:F.array(ku).max(200),oldestAvailable:F.number().int().nonnegative()}),ld,F.object({type:F.literal(`ack`),reqId:qu,ok:F.boolean(),error:F.string().max(256).optional(),sessionId:tr.optional(),opened:rd.optional(),openedIn:Mu.optional()}),F.object({type:F.literal(`subscribe`),sessionId:tr.nullable()}),F.object({type:F.literal(`input.line`),reqId:qu,sessionId:tr,text:F.string().max(8192),expect:Zu.optional()}),F.object({type:F.literal(`input.text`),reqId:qu,sessionId:tr,text:F.string().max(65536)}),F.object({type:F.literal(`input.key`),reqId:qu,sessionId:tr,key:ll}),F.object({type:F.literal(`input.terminal`),reqId:qu,sessionId:tr,data:F.string().min(1).max(Kl),expect:Zu.optional()}),F.object({type:F.literal(`input.paste`),reqId:qu,sessionId:tr,text:F.string().min(1).max(Kl),submit:F.boolean(),expect:Zu.optional()}),Gu.extend({type:F.literal(`input.mouse`),reqId:qu,sessionId:tr}).refine(e=>e.column<e.cols&&e.row<e.rows,`Mouse coordinates must be inside the source grid`),F.object({type:F.literal(`history.get`),reqId:qu,sessionId:tr,before:F.number().int().nonnegative(),count:F.number().int().min(1).max(200)}),F.object({type:F.literal(`session.create`),reqId:qu,in:nd}),F.object({type:F.literal(`session.focus`),reqId:qu,sessionId:tr}),F.object({type:F.literal(`snapshot.get`),reqId:qu,sessionId:tr}),...lr.options,...Lr.options,...hu.options]);function dd(e){let t=ud.safeParse(e);if(!t.success)throw new V(`malformed`,`inner: ${F.prettifyError(t.error)}`);return t.data}const fd=e=>F.union([e,F.string().min(1).max(32)]),pd=fd(Cu),md=fd(Ku),hd=fd(qc),gd=$u.extend({backend:pd,state:md});F.discriminatedUnion(`type`,[sd.extend({launchableBackends:F.array(pd).max(4).optional(),backends:F.array(F.object({name:pd,capabilities:ju})).max(4)}),cd.extend({list:F.array(gd).max(500)}),ld.extend({kind:hd})]),F.object({type:F.literal(`notify`),sessionId:tr,kind:hd,exitCode:F.number().int().optional(),durationMs:F.number().int().nonnegative().optional()});const _d=/[\x00-\x1f\x7f-\x9f]/;function vd(e,t){if(!Number.isSafeInteger(e)||e<1||e>G.cols||t.length>2e3)return null;let n=La.create();n.update(vr(`shellbell-native-history-v1\n${e}\n${t.length}\n`));let r=0;for(let e of t){if(typeof e!=`string`||e.length>G.screenBytes||_d.test(e))return null;let t=vr(`${JSON.stringify(e.replace(/ +$/,``))}\n`);if(r+=t.byteLength,r>G.screenBytes)return null;n.update(t)}return Sr(n.digest())}const yd=new Uint8Array(16),bd=Jr(yd),xd=(e,t,n,r)=>{let i=r&1;return{s3:n<<31|r>>>1,s2:t<<31|n>>>1,s1:e<<31|t>>>1,s0:e>>>1^225<<24&-(i&1)}},Sd=e=>(e>>>0&255)<<24|(e>>>8&255)<<16|(e>>>16&255)<<8|e>>>24&255|0,Cd=e=>e>65536?8:e>1024?4:2;var wd=class{blockLen=16;outputLen=16;s0=0;s1=0;s2=0;s3=0;finished=!1;destroyed=!1;t;W;windowSize;constructor(e,t){Hr(e,16,`key`),e=di(e);let n=Xr(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=n.getUint32(8,!1),o=n.getUint32(12,!1),s=[];for(let e=0;e<128;e++)s.push({s0:Sd(r),s1:Sd(i),s2:Sd(a),s3:Sd(o)}),{s0:r,s1:i,s2:a,s3:o}=xd(r,i,a,o);let c=Cd(t||1024);if(![1,2,4,8].includes(c))throw Error(`ghash: invalid window size, expected 2, 4 or 8`);this.W=c;let l=128/c,u=this.windowSize=2**c,d=[];for(let e=0;e<l;e++)for(let t=0;t<u;t++){let n=0,r=0,i=0,a=0;for(let o=0;o<c;o++){if(!(t>>>c-o-1&1))continue;let{s0:l,s1:u,s2:d,s3:f}=s[c*e+o];n^=l,r^=u,i^=d,a^=f}d.push({s0:n,s1:r,s2:i,s3:a})}this.t=d}_updateBlock(e,t,n,r){e^=this.s0,t^=this.s1,n^=this.s2,r^=this.s3;let{W:i,t:a,windowSize:o}=this,s=0,c=0,l=0,u=0,d=(1<<i)-1,f=0;for(let p of[e,t,n,r])for(let e=0;e<4;e++){let t=p>>>8*e&255;for(let e=8/i-1;e>=0;e--){let n=t>>>i*e&d,{s0:r,s1:p,s2:m,s3:h}=a[f*o+n];s^=r,c^=p,l^=m,u^=h,f+=1}}this.s0=s,this.s1=c,this.s2=l,this.s3=u}update(e){Wr(this),Hr(e),e=di(e);let t=Jr(e),n=Math.floor(e.length/16),r=e.length%16;for(let e=0;e<n;e++)this._updateBlock($r(t[e*4+0]),$r(t[e*4+1]),$r(t[e*4+2]),$r(t[e*4+3]));return r&&(yd.set(e.subarray(n*16)),this._updateBlock($r(bd[0]),$r(bd[1]),$r(bd[2]),$r(bd[3])),Yr(bd)),this}destroy(){this.destroyed=!0;let{t:e}=this;for(let t of e)t.s0=0,t.s1=0,t.s2=0,t.s3=0}digestInto(e){Wr(this),Kr(e,this),this.finished=!0;let{s0:t,s1:n,s2:r,s3:i}=this,a=Jr(e);a[0]=t,a[1]=n,a[2]=r,a[3]=i,Zr||ti(a.subarray(0,4))}digest(){let e=new Uint8Array(16);return this.digestInto(e),this.destroy(),e}};const Td=oi(16,(e,t)=>new wd(e,t),e=>[e.length]),Ed=new Uint8Array(16);function Dd(e){if(![16,24,32].includes(e.length))throw Error(`"aes key" expected Uint8Array of length 16/24/32, got length=`+e.length)}function Od(e){return e<<1^283&-(e>>7)}function kd(e,t){let n=0;for(;t>0;t>>=1)n^=e&-(t&1),e=Od(e);return n}const Ad=(()=>{let e=new Uint8Array(256);for(let t=0,n=1;t<256;t++,n^=Od(n))e[t]=n;let t=new Uint8Array(256);t[0]=99;for(let n=0;n<255;n++){let r=e[255-n];r|=r<<8,t[e[n]]=(r^r>>4^r>>5^r>>6^r>>7^99)&255}return Yr(e),t})(),jd=e=>e<<24|e>>>8,Md=e=>e<<8|e>>>24;function Nd(e,t){if(e.length!==256)throw Error(`wrong sbox length`);let n=new Uint32Array(256).map((n,r)=>t(e[r])),r=n.map(Md),i=r.map(Md),a=i.map(Md),o=new Uint32Array(65536),s=new Uint32Array(65536),c=new Uint16Array(65536);for(let t=0;t<256;t++)for(let l=0;l<256;l++){let u=t*256+l;o[u]=n[t]^r[l],s[u]=i[t]^a[l],c[u]=e[t]<<8|e[l]}return{sbox:e,sbox2:c,T0:n,T1:r,T2:i,T3:a,T01:o,T23:s}}const Pd=Nd(Ad,e=>kd(e,3)<<24|e<<16|e<<8|kd(e,2)),Fd=(()=>{let e=new Uint8Array(16);for(let t=0,n=1;t<16;t++,n=Od(n))e[t]=n;return e})();function Id(e){Hr(e);let t=e.length;Dd(e);let{sbox2:n}=Pd,r=[];(!Zr||!ui(e))&&r.push(e=di(e));let i=ti(Jr(e)),a=i.length,o=e=>Rd(n,e,e,e,e),s=new Uint32Array(t+28);s.set(i);for(let e=a;e<s.length;e++){let t=s[e-1];e%a===0?t=o(jd(t))^Fd[e/a-1]:a>6&&e%a===4&&(t=o(t)),s[e]=s[e-a]^t}return Yr(...r),s}function Ld(e,t,n,r,i,a){return e[n<<8&65280|r>>>8&255]^t[i>>>8&65280|a>>>24&255]}function Rd(e,t,n,r,i){return e[t&255|n&65280]|e[r>>>16&255|i>>>16&65280]<<16}function zd(e,t,n,r,i){let{sbox2:a,T01:o,T23:s}=Pd,c=0;t^=e[c++],n^=e[c++],r^=e[c++],i^=e[c++];let l=e.length/4-2;for(let a=0;a<l;a++){let a=e[c++]^Ld(o,s,t,n,r,i),l=e[c++]^Ld(o,s,n,r,i,t),u=e[c++]^Ld(o,s,r,i,t,n),d=e[c++]^Ld(o,s,i,t,n,r);t=a,n=l,r=u,i=d}return{s0:e[c++]^Rd(a,t,n,r,i),s1:e[c++]^Rd(a,n,r,i,t),s2:e[c++]^Rd(a,r,i,t,n),s3:e[c++]^Rd(a,i,t,n,r)}}function Bd(e,t,n,r,i){Hr(n,16,`nonce`),Hr(r),i=ci(r.length,i);let a=n,o=Jr(a),s=Xr(a),c=Jr(r),l=Jr(i),u=t?0:12,d=r.length,f=s.getUint32(u,t);for(let n=0;n+4<=c.length;n+=4){let{s0:r,s1:i,s2:a,s3:d}=zd(e,$r(o[0]),$r(o[1]),$r(o[2]),$r(o[3]));l[n+0]=c[n+0]^$r(r),l[n+1]=c[n+1]^$r(i),l[n+2]=c[n+2]^$r(a),l[n+3]=c[n+3]^$r(d),f=f+1>>>0,s.setUint32(u,f,t)}let p=16*Math.floor(c.length/4);if(p<d){let{s0:t,s1:n,s2:a,s3:s}=zd(e,$r(o[0]),$r(o[1]),$r(o[2]),$r(o[3])),c=new Uint32Array([t,n,a,s]);ti(c);let l=qr(c);for(let e=p,t=0;e<d;e++,t++)i[e]=r[e]^l[t];Yr(c)}return i}function Vd(e,t,n,r,i){let a=i?i.length:0,o=e.create(n,r.length+a);i&&o.update(i);let s=li(8*r.length,8*a,t);o.update(r),o.update(s);let c=o.digest();return Yr(s),c}const Hd=si({blockSize:16,nonceLength:12,tagLength:16,withAAD:!0,varSizeNonce:!0},function(e,t,n){if(t.length<8)throw Error(`aes/gcm: invalid nonce length`);function r(e,t,r){let i=Vd(Td,!1,e,r,n);for(let e=0;e<t.length;e++)i[e]^=t[e];return i}function i(){let n=Id(e),r=Ed.slice(),i=Ed.slice();if(Bd(n,!1,i,i,r),t.length===12)i.set(t);else{let e=Ed.slice();Xr(e).setBigUint64(8,BigInt(t.length*8),!1);let n=Td.create(r).update(t).update(e);n.digestInto(i),n.destroy()}return{xk:n,authKey:r,counter:i,tagMask:Bd(n,!1,i,Ed)}}return{encrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=new Uint8Array(e.length+16),c=[t,n,a,o];ui(e)||c.push(e=di(e)),Bd(t,!1,a,e,s.subarray(0,e.length));let l=r(n,o,s.subarray(0,s.length-16));return c.push(l),s.set(l,e.length),Yr(...c),s},decrypt(e){let{xk:t,authKey:n,counter:a,tagMask:o}=i(),s=[t,n,o,a];ui(e)||s.push(e=di(e));let c=e.subarray(0,-16),l=e.subarray(-16),u=r(n,o,c);if(s.push(u),!ai(u,l))throw Yr(...s),Error(`aes-gcm: invalid tag`);let d=Bd(t,!1,a,c);return Yr(...s),d}}});function Ud(e){if(!(e instanceof Uint8Array)||e.length!==32)throw new V(`crypto`,`invalid notification key`)}const Wd=Pc.pick({computerFp:!0,phoneFp:!0,generation:!0});function Gd(e,t){Ud(e);let n=Wd.parse({computerFp:t.computerFp,phoneFp:t.phoneFp,generation:t.generation});return $s(La,e,vr(wc),vr(JSON.stringify([n.computerFp,n.phoneFp,n.generation])),32)}function Kd(e){let t=Rc(e);return vr(JSON.stringify([wc,t.computerFp,t.phoneFp,t.generation,t.sessionId,t.eventId]))}function qd(e,t){try{Ud(e);let n=Ic.parse(t),r=Rc(n),i=ya(12),a=vr(JSON.stringify(n));try{let t=Hd(e,i,Kd(r)).encrypt(a);return{...r,nonce:yr(i),ciphertext:yr(t)}}finally{a.fill(0)}}catch{throw new V(`crypto`,`notification seal failed`)}}const Jd=F.string().regex(/^[A-Za-z0-9_-]{22}$/),Yd=F.object({v:F.literal(1),r:F.url().max(256),c:W,e:F.string().regex(/^[A-Za-z0-9_-]{43}$/),n:F.string().min(1).max(40),p:Jd,g:Jd,b:F.literal(1).optional(),x:F.number().int().positive().max(2**32).optional()});function Xd(e){return JSON.stringify(e)}function Zd(e,t={}){let n;try{n=JSON.parse(e)}catch{throw new V(`malformed`,`qr: not json`)}let r=Yd.safeParse(n);if(!r.success)throw new V(`malformed`,`qr: ${F.prettifyError(r.error)}`);let i=r.data,a=new URL(i.r);if(a.username||a.password)throw new V(`malformed`,`qr: relay url must not contain credentials`);if(a.protocol!==`wss:`&&!(t.allowInsecure&&a.protocol===`ws:`))throw new V(`malformed`,`qr: relay must be wss://`);if(i.r.endsWith(`/`)||/[?#]/.test(i.r)||a.pathname!==`/`||a.search||a.hash)throw new V(`malformed`,`qr: relay url must be scheme://host[:port] with no path`);if(ac(br(i.e))!==i.c)throw new V(`malformed`,`qr: fingerprint mismatch`);return i}function Qd(e,t){return`${e}/ws/${t}`}function $d(){return{r:[]}}function ef(e){let t=0;for(let n of e)t++;return t}function tf(e){return e===void 0?``:typeof e==`number`?String(e):`${e[0]},${e[1]},${e[2]}`}function nf(e,t){return tf(e.fg)===tf(t.fg)&&tf(e.bg)===tf(t.bg)&&!!e.b==!!t.b&&!!e.i==!!t.i&&!!e.u==!!t.u&&!!e.s==!!t.s&&!!e.f==!!t.f}function rf(e){return e.n??ef(e.t)}function af(e){let t=[];for(let n of e){let e=t[t.length-1];if(e&&nf(e,n)){let t=rf(e)+rf(n);e.t+=n.t,t===ef(e.t)?delete e.n:e.n=t}else{let e={...n};e.n!==void 0&&e.n===ef(e.t)&&delete e.n,t.push(e)}}return t}function of(e){let t=e.slice();for(;t.length>0;){let e=t[t.length-1];if(e.bg!==void 0)break;let n=e.t.replace(/ +$/,``);if(n===``){t.pop();continue}if(n!==e.t){let r=ef(e.t)-ef(n),i=(e.n??ef(e.t))-r,a={...e,t:n};i===ef(n)?delete a.n:a.n=i,t[t.length-1]=a}break}return t}function sf(e){let t={r:[]};for(let n of e.r){let e=rf(n);if(n.t===``&&e===0)continue;let r=t.r[t.r.length-1];if(r&&r.t.length+n.t.length<=4096&&rf(r)+e<=4096){let t=rf(r)+e;r.t+=n.t,t===ef(r.t)?delete r.n:r.n=t}else{let r={t:n.t};e!==ef(n.t)&&(r.n=e),t.r.push(r)}}return e.w!==void 0&&(t.w=e.w),t}function cf(e){return`${+!!e.b}${+!!e.i}${+!!e.u}${+!!e.s}${+!!e.f}`}function lf(e){let t=e.r.map(e=>`${e.t}|${tf(e.fg)}|${tf(e.bg)}|${cf(e)}|${e.n??``}`).join(``);return e.w===!0?`${t}\x00w`:t}const uf={sdpChars:24e3,candidateChars:1024,candidatesPerSide:32,encodedBytes:3e4,bootstrapConfirmBytes:512},df=jl.refine(e=>e[0]===1&&e.subarray(1).every(e=>e===0),{message:`initial relay generation must be one`}),ff=jl.refine(e=>e[0]!==1||e.subarray(1).some(e=>e!==0),{message:`direct generation must exceed one`}),pf=F.string().min(1).max(uf.sdpChars).regex(/^[\x20-\x7e\r\n]+$/,`SDP must contain printable ASCII and line endings only`),mf=F.string().min(1).max(uf.candidateChars).startsWith(`candidate:`).regex(/^[\x20-\x7e]+$/,`ICE candidate must contain printable ASCII only`),hf={sessionId:Al,offerId:Al,generation:ff};function gf(e,t){if(/\r(?!\n)/.test(e))return!1;let n=e.split(/\r?\n/).filter(e=>e.length>0);if(n.some(e=>!/^[a-z]=/.test(e)))return!1;let r=n.filter(e=>e.startsWith(`m=`));if(r.length!==1||!/^m=application [0-9]+ (?:UDP|TCP)\/DTLS\/SCTP webrtc-datachannel$/i.test(r[0]??``)||n.some(e=>/^a=(?:candidate|remote-candidates|end-of-candidates)(?::|$)/i.test(e))||!n.some(e=>/^a=ice-ufrag:/i.test(e))||!n.some(e=>/^a=ice-pwd:/i.test(e)))return!1;let i=n.filter(e=>/^a=fingerprint:/i.test(e));if(i.length===0)return!1;for(let e of i){let n=/^a=fingerprint:sha-256 ((?:[0-9a-f]{2}:){31}[0-9a-f]{2})$/i.exec(e);if(!n?.[1]||!Tr(Cr(n[1].replaceAll(`:`,``)),t))return!1}return!0}const _f=F.discriminatedUnion(`type`,[F.object({type:F.literal(`session.v2.begin`),sessionId:Al,generation:df}).strict(),F.object({type:F.literal(`session.v2.accept`),sessionId:Al,attemptId:Al,generation:df}).strict(),F.object({type:F.literal(`session.v2.noise1`),sessionId:Al,attemptId:Al,message:U(48)}).strict(),F.object({type:F.literal(`session.v2.noise2`),sessionId:Al,attemptId:Al,message:U(48)}).strict(),F.object({type:F.literal(`session.v2.confirm`),sessionId:Al,attemptId:Al,frame:F.custom(e=>e instanceof Uint8Array&&e.length>0&&e.length<=uf.bootstrapConfirmBytes,{message:`invalid v2 confirmation frame length`})}).strict()]);function vf(e,t){return t!==void 0&&Al.safeParse(t).success&&Tr(e,t)}function yf(e,t){return!t||e.type!==t.expectedType?!1:e.type===`session.v2.begin`?t.sender===`phone`&&t.sessionId===void 0&&t.attemptId===void 0:vf(e.sessionId,t.sessionId)?e.type===`session.v2.accept`?t.sender===`computer`&&t.attemptId===void 0:vf(e.attemptId,t.attemptId)?e.type===`session.v2.noise1`?t.sender===`phone`:e.type===`session.v2.noise2`?t.sender===`computer`:t.sender===`phone`||t.sender===`computer`:!1:!1}const bf=1024;function xf(e){let t=_f.safeParse(e);if(!t.success)throw new V(`malformed`,`invalid v2 bootstrap`);let n=H(t.data);if(n.length>bf)throw new V(`malformed`,`v2 bootstrap too large`);return n}function Sf(e,t){if(e.length>bf)throw new V(`malformed`,`v2 bootstrap too large`);let n=_f.safeParse(Gn(e));if(!n.success||!yf(n.data,t))throw new V(`malformed`,`invalid or stale v2 bootstrap`);return n.data}const Cf=F.discriminatedUnion(`type`,[F.object({type:F.literal(`direct.offer`),...hf,sdp:pf,phoneDtls:U(32)}).strict(),F.object({type:F.literal(`direct.answer`),...hf,attemptId:Al,sdp:pf,computerDtls:U(32)}).strict(),F.object({type:F.literal(`direct.candidate`),...hf,index:F.number().int().min(0).max(uf.candidatesPerSide-1),candidate:mf,mid:F.string().min(1).max(64).regex(/^[\x21-\x7e]+$/).nullable(),mlineIndex:F.number().int().min(0).max(0).nullable()}).strict(),F.object({type:F.literal(`direct.end`),...hf,count:F.number().int().min(0).max(uf.candidatesPerSide)}).strict(),F.object({type:F.literal(`direct.abort`),...hf,reason:F.enum([`timeout`,`ice-failed`,`dtls-failed`,`resource-limit`,`cancelled`])}).strict()]).superRefine((e,t)=>{e.type===`direct.candidate`&&e.mid===null&&e.mlineIndex===null&&t.addIssue({code:`custom`,message:`candidate needs a media section`}),e.type===`direct.offer`&&!gf(e.sdp,e.phoneDtls)&&t.addIssue({code:`custom`,message:`invalid data-channel offer SDP`}),e.type===`direct.answer`&&!gf(e.sdp,e.computerDtls)&&t.addIssue({code:`custom`,message:`invalid data-channel answer SDP`})});function wf(e,t){if(!t||t.sender!==`phone`&&t.sender!==`computer`||!Al.safeParse(t.sessionId).success||!jl.safeParse(t.committedGeneration).success||!Tr(e.sessionId,t.sessionId))return!1;if(e.type===`direct.offer`)return t.sender===`phone`&&t.pending===void 0&&bl(e.generation)>bl(t.committedGeneration);let n=t.pending;return n!==void 0&&Al.safeParse(n.offerId).success&&jl.safeParse(n.generation).success&&bl(n.generation)>bl(t.committedGeneration)&&Tr(e.offerId,n.offerId)&&Tr(e.generation,n.generation)&&(e.type!==`direct.answer`||t.sender===`computer`)}function Tf(e){let t=Cf.safeParse(e);if(!t.success)throw new V(`malformed`,`invalid direct signal`);let n=H(t.data);if(n.length>uf.encodedBytes)throw new V(`malformed`,`direct signal too large`);return n}function Ef(e,t){if(e.length>uf.encodedBytes)throw new V(`malformed`,`direct signal too large`);let n=Cf.safeParse(Gn(e));if(!n.success||!wf(n.data,t))throw new V(`malformed`,`invalid or stale direct signal`);return n.data}var Df=class{context;role;actualRemoteCertificate;handshake;session=null;phase;constructor(e,t,n,r){if(this.context=e,this.role=t,this.actualRemoteCertificate=r,e.route!==`direct`)throw Error(`direct context required`);this.handshake=Ul(e,t,n),this.phase=t===`phone`?`new`:`noise1`}get ready(){return this.phase===`ready`&&this.session?.ready===!0}begin(){if(this.phase!==`new`||!this.handshake)throw Error(`direct handshake order`);return this.phase=`noise2`,xf({type:`session.v2.noise1`,sessionId:this.context.sessionId,attemptId:this.context.attemptId,message:this.handshake.write()})}receive(e){try{if((this.phase===`noise1`||this.phase===`noise2`)&&this.handshake){let t=this.phase===`noise1`?`session.v2.noise1`:`session.v2.noise2`,n=Sf(e,{sender:this.role===`phone`?`computer`:`phone`,expectedType:t,sessionId:this.context.sessionId,attemptId:this.context.attemptId});if(n.type!==t)throw Error(`direct handshake order`);this.handshake.read(n.message);let r=null;return this.role===`computer`&&(r=xf({type:`session.v2.noise2`,sessionId:this.context.sessionId,attemptId:this.context.attemptId,message:this.handshake.write()})),this.session=this.handshake.finish(),this.handshake=null,this.session.verifyRemoteDtls(this.actualRemoteCertificate),this.phase=`confirm`,r??xf({type:`session.v2.confirm`,sessionId:this.context.sessionId,attemptId:this.context.attemptId,frame:Bl(this.session.confirmation())})}if(this.phase!==`confirm`||!this.session)throw Error(`direct handshake order`);let t=Sf(e,{sender:this.role===`phone`?`computer`:`phone`,expectedType:`session.v2.confirm`,sessionId:this.context.sessionId,attemptId:this.context.attemptId});if(t.type!==`session.v2.confirm`)throw Error(`direct confirmation required`);this.session.acceptConfirmation(Vl(t.frame));let n=this.role===`computer`?xf({type:`session.v2.confirm`,sessionId:this.context.sessionId,attemptId:this.context.attemptId,frame:Bl(this.session.confirmation())}):null;if(!this.session.ready)throw Error(`direct confirmation incomplete`);return this.phase=`ready`,n}catch(e){throw this.close(),e}}takeReadySession(){if(!this.ready||!this.session)throw Error(`direct handshake incomplete`);let e=this.session;return this.session=null,this.phase=`closed`,e}close(){this.handshake?.close(),this.handshake=null,this.session?.close(),this.session=null,this.phase=`closed`}};function Of(e,t){return e===`relay`||t===`relay`?`turn`:e===`host`&&t===`host`?`local`:`internet`}const kf=e=>/ typ relay(?: |$)/.test(e.candidate);function Af(e){let t=/^a=fingerprint:sha-256 ((?:[0-9a-f]{2}:){31}[0-9a-f]{2})\r?$/im.exec(e);if(!t?.[1])throw Error(`missing SHA-256 SDP fingerprint`);return Cr(t[1].replaceAll(`:`,``))}function jf(e){return`${e.split(/\r?\n/).filter(e=>e.length&&!/^a=(?:candidate|remote-candidates|end-of-candidates)(?::|$)/i.test(e)).join(`\r
16
+ `)}\r\n`}var Mf=class{options;offerId;generation;attemptId;peer=null;phoneDtls;computerDtls=null;localSdp=null;remoteSdp=!1;opened=!1;verifying=!1;sentDescription=!1;sentCandidates=0;receivedCandidates=0;pendingData=[];pendingLocal=[];pendingRemote=[];handshake=null;secureSession=null;closed=!1;timer;constructor(e){this.options=e,this.offerId=e.offer?.offerId.slice()??ya(16),this.attemptId=e.offer?ya(16):null,this.generation=e.generation.slice(),this.phoneDtls=e.offer?.phoneDtls.slice()??null,this.timer=setTimeout(()=>this.fail(`timeout`),15e3)}get session(){return this.secureSession}get phase(){return this.secureSession?`cutover`:this.handshake?`noise`:this.verifying?`certificate`:this.opened?`open`:this.remoteSdp?`connecting`:this.localSdp?`offer`:`native`}get active(){return!this.closed&&this.options.current()}cancelDeadline(){clearTimeout(this.timer)}close(){this.closed||(this.closed=!0,this.cancelDeadline(),this.pendingData=[],this.pendingLocal=[],this.pendingRemote=[],this.handshake?.close(),this.secureSession?.close(),this.peer?.close())}routeStats(){return this.peer?.routeStats?.()??Promise.resolve(null)}send(e){let t=this.active&&(this.peer?.send(e)??!1);return t&&this.options.sent(e.length),t}fail(e=`closed`){this.active&&this.options.failed(e)}async start(){let e={description:(e,t)=>{this.active&&this.description(e,t)},candidate:(e,t,n)=>{if(this.active)try{this.localCandidate({candidate:e,mid:t,mlineIndex:n})}catch{this.fail(`local-candidate`)}},open:()=>{this.active&&(this.opened=!0,this.openDirect().catch(()=>this.fail(`certificate`)))},message:e=>{this.active&&(this.options.received(e.length),this.directMessage(e))},closed:()=>this.fail(`native-closed`)},t;try{t=await this.options.native(e)}catch{this.fail(`native-create`);return}if(!this.active){t.close();return}this.peer=t;try{if(this.options.offer){if(await t.answer(this.options.offer.sdp),!this.active)return;this.remoteSdp=!0}else await t.offer();if(!this.active)return;await this.flushRemote(),await this.openDirect()}catch{this.fail(`native-description`)}}description(e,t){try{let n=Af(e);if(this.localSdp=jf(e),this.options.role===`phone`&&t===`offer`)this.phoneDtls=n;else if(this.options.role===`computer`&&t===`answer`)this.computerDtls=n;else throw Error(`description role mismatch`);let r=this.signalContext(),i=t===`offer`?{type:`direct.offer`,...r,phoneDtls:n,sdp:this.localSdp}:{type:`direct.answer`,...r,attemptId:this.attemptId,computerDtls:n,sdp:this.localSdp};if(!this.options.sendSignal(i))throw Error(`signaling queue refused`);this.sentDescription=!0;for(let e of this.pendingLocal.splice(0))this.localCandidate(e);this.openDirect().catch(()=>this.fail(`certificate`))}catch{this.fail(`local-description`)}}admits(e){return this.sentCandidates+this.pendingLocal.length<(kf(e)?uf.candidatesPerSide:uf.candidatesPerSide-6)}localCandidate(e){if(this.active&&!this.options.committed()&&this.admits(e)){if(!this.sentDescription){this.pendingLocal.push(e);return}this.options.sendSignal({type:`direct.candidate`,...this.signalContext(),index:this.sentCandidates++,...e})||this.fail()}}async signal(e){if(this.active&&this.peer){if(e.type===`direct.answer`){if(this.remoteSdp||(this.computerDtls=e.computerDtls.slice(),this.attemptId=e.attemptId.slice(),await this.peer.acceptAnswer(e.sdp),!this.active))return;this.remoteSdp=!0,await this.flushRemote(),await this.openDirect()}else if(e.type===`direct.candidate`){if(e.index!==this.receivedCandidates++)throw Error(`candidate order`);this.remoteSdp?await this.peer.candidate(e.candidate,e.mid,e.mlineIndex):this.pendingRemote.push(e)}else e.type===`direct.abort`&&this.fail()}}async flushRemote(){if(this.remoteSdp&&this.peer)for(let e of this.pendingRemote.splice(0)){if(!this.active)return;await this.peer.candidate(e.candidate,e.mid,e.mlineIndex)}}signalContext(){return{sessionId:this.options.relay.sessionId,offerId:this.offerId,generation:this.generation}}async openDirect(){if(!this.active||!this.opened||!this.peer||!this.phoneDtls||!this.computerDtls||!this.attemptId||this.verifying||this.handshake||this.secureSession)return;this.verifying=!0;let e=await this.peer.remoteCertificate(this.options.role===`phone`?this.computerDtls:this.phoneDtls);if(this.active){if(this.handshake=new Df({route:`direct`,computerFp:this.options.computerFp,phoneFp:this.options.phoneFp,sessionId:this.options.relay.sessionId,generation:this.generation,attemptId:this.attemptId,phoneDtls:this.phoneDtls,computerDtls:this.computerDtls},this.options.role,this.options.keys,e),this.options.role===`phone`&&!this.send(this.handshake.begin())){this.fail();return}for(let e of this.pendingData.splice(0))this.directMessage(e)}}directMessage(e){if(this.active)try{if(!this.peer||e.length>61e3)throw Error(`direct frame bounds`);if(this.secureSession){this.options.frame(this.secureSession,e);return}if(!this.handshake){if(!this.verifying||this.pendingData.length>=4||e.length>1024)throw Error(`direct handshake missing`);this.pendingData.push(e.slice());return}let t=this.handshake.receive(e);if(t&&!this.send(t))throw Error(`direct queue refused`);this.handshake.ready&&(this.secureSession=this.handshake.takeReadySession(),this.handshake=null,this.options.ready(this.secureSession))}catch{this.fail(`direct-frame`)}}};const Nf=Uint8Array.of(1,0,0,0,0,0,0,0);var Pf=class{options;stage;startedAt=null;sessionId=null;attemptId=null;handshake=null;session=null;timer=null;keys;timeoutMs;constructor(e){if(this.options=e,W.parse(e.computerFp),W.parse(e.phoneFp),e.role!==`phone`&&e.role!==`computer`)throw Error(`invalid v2 role`);if(e.keys.staticPrivate.length!==32||e.keys.remoteStatic.length!==32||e.keys.pairKey.length!==32)throw Error(`invalid v2 pairing keys`);if(this.timeoutMs=e.timeoutMs??15e3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1||this.timeoutMs>3e4)throw Error(`invalid v2 bootstrap timeout`);this.keys={staticPrivate:e.keys.staticPrivate.slice(),remoteStatic:e.keys.remoteStatic.slice(),pairKey:e.keys.pairKey.slice()},this.stage=e.role===`phone`?`phone:new`:`computer:begin`}get ready(){return this.stage===`ready`&&this.session?.ready===!0}begin(){if(this.stage!==`phone:new`)throw Error(`v2 begin not allowed`);try{return this.startedAt=this.clock(),this.armTimer(),this.sessionId=this.freshId(),this.stage=`phone:accept`,xf({type:`session.v2.begin`,sessionId:this.sessionId,generation:Nf})}catch(e){throw this.close(),e}}receive(e){try{if(this.stage===`closed`||this.stage===`detached`||this.stage===`ready`)throw Error(`v2 bootstrap no longer accepts messages`);switch(this.stage!==`computer:begin`&&this.assertNotExpired(),this.stage){case`computer:begin`:{let t=Sf(e,{sender:`phone`,expectedType:`session.v2.begin`});if(t.type!==`session.v2.begin`)throw Error(`invalid v2 begin`);if(this.startedAt=this.clock(),this.armTimer(),this.sessionId=t.sessionId.slice(),this.attemptId=this.freshId(),Tr(this.sessionId,this.attemptId))throw Error(`repeated v2 attempt ID`);return this.handshake=this.newHandshake(),this.stage=`computer:noise1`,xf({type:`session.v2.accept`,sessionId:this.sessionId,attemptId:this.attemptId,generation:Nf})}case`phone:accept`:{let t=Sf(e,{sender:`computer`,expectedType:`session.v2.accept`,sessionId:this.requireSessionId()});if(t.type!==`session.v2.accept`)throw Error(`invalid v2 accept`);if(this.attemptId=t.attemptId.slice(),Tr(this.requireSessionId(),this.attemptId))throw Error(`repeated v2 attempt ID`);this.handshake=this.newHandshake();let n=this.handshake.write();return this.stage=`phone:noise2`,xf({type:`session.v2.noise1`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId(),message:n})}case`computer:noise1`:{let t=Sf(e,{sender:`phone`,expectedType:`session.v2.noise1`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId()});if(t.type!==`session.v2.noise1`||!this.handshake)throw Error(`invalid v2 noise1`);this.handshake.read(t.message);let n=this.handshake.write();return this.session=this.handshake.finish(),this.handshake=null,this.stage=`computer:confirm`,xf({type:`session.v2.noise2`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId(),message:n})}case`phone:noise2`:{let t=Sf(e,{sender:`computer`,expectedType:`session.v2.noise2`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId()});if(t.type!==`session.v2.noise2`||!this.handshake)throw Error(`invalid v2 noise2`);this.handshake.read(t.message),this.session=this.handshake.finish(),this.handshake=null;let n=Bl(this.session.confirmation());return this.stage=`phone:confirm`,xf({type:`session.v2.confirm`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId(),frame:n})}case`computer:confirm`:{let t=this.decodeConfirmation(e,`phone`);if(!this.session)throw Error(`v2 session missing`);this.session.acceptConfirmation(Vl(t.frame));let n=Bl(this.session.confirmation());if(!this.session.ready)throw Error(`v2 computer confirmation incomplete`);return this.markReady(),xf({type:`session.v2.confirm`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId(),frame:n})}case`phone:confirm`:{let t=this.decodeConfirmation(e,`computer`);if(!this.session)throw Error(`v2 session missing`);if(this.session.acceptConfirmation(Vl(t.frame)),!this.session.ready)throw Error(`v2 phone confirmation incomplete`);return this.markReady(),null}default:throw Error(`invalid v2 bootstrap stage`)}}catch(e){throw this.close(),e}}takeReadySession(){if(!this.ready||!this.session)throw Error(`v2 session not confirmed`);let e=this.session;return this.session=null,this.stage=`detached`,e}close(){this.stage!==`closed`&&(this.stage=`closed`,this.clearTimer(),this.handshake?.close(),this.handshake=null,this.session?.close(),this.session=null,this.keys.staticPrivate.fill(0),this.keys.remoteStatic.fill(0),this.keys.pairKey.fill(0))}decodeConfirmation(e,t){let n=Sf(e,{sender:t,expectedType:`session.v2.confirm`,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId()});if(n.type!==`session.v2.confirm`)throw Error(`invalid v2 confirmation`);return n}newHandshake(){let e={route:`relay`,computerFp:this.options.computerFp,phoneFp:this.options.phoneFp,sessionId:this.requireSessionId(),attemptId:this.requireAttemptId(),generation:Nf};try{return Ul(e,this.options.role,this.keys)}finally{this.keys.staticPrivate.fill(0),this.keys.remoteStatic.fill(0),this.keys.pairKey.fill(0)}}freshId(){return Al.parse(this.options.newId()).slice()}requireSessionId(){if(!this.sessionId)throw Error(`v2 session ID missing`);return this.sessionId}requireAttemptId(){if(!this.attemptId)throw Error(`v2 attempt ID missing`);return this.attemptId}clock(){let e=this.options.now();if(!Number.isFinite(e)||e<0)throw Error(`invalid v2 clock`);return e}armTimer(){this.clearTimer(),this.timer=setTimeout(()=>this.close(),this.timeoutMs)}clearTimer(){this.timer!==null&&clearTimeout(this.timer),this.timer=null}markReady(){this.stage=`ready`,this.clearTimer()}assertNotExpired(){if(this.startedAt===null)throw Error(`v2 bootstrap not started`);let e=this.clock()-this.startedAt;if(e<0||e>this.timeoutMs)throw Error(`v2 bootstrap expired`)}},Ff=class{options;stage;pairKey;bootstrap;timeoutMs;startedAt=null;timer=null;phoneNonce=null;connKey=null;connTag=``;seqIn=0;seqOut=0;constructor(e){if(this.options=e,W.parse(e.computerFp),W.parse(e.phoneFp),e.role!==`phone`&&e.role!==`computer`)throw Error(`invalid v2 role`);if(e.keys.pairKey.length!==32)throw Error(`invalid pair key`);if(this.timeoutMs=e.timeoutMs??15e3,!Number.isSafeInteger(this.timeoutMs)||this.timeoutMs<1)throw Error(`invalid v2 carrier timeout`);this.pairKey=e.keys.pairKey.slice(),this.bootstrap=new Pf(e),this.stage=e.role===`phone`?`phone:new`:`computer:hello`}get ready(){return this.stage===`ready`&&this.bootstrap.ready}get closed(){return this.stage===`closed`}start(){if(this.stage!==`phone:new`)throw Error(`v2 carrier cannot start`);try{return this.startDeadline(),this.phoneNonce=ya(16),this.stage=`phone:hello`,this.hello(this.phoneNonce)}catch(e){throw this.close(),e}}receive(e){if(this.stage===`closed`||this.stage===`ready`||this.stage===`phone:new`)throw Error(`v2 carrier not receiving`);try{this.stage!==`computer:hello`&&this.checkDeadline();let t=this.options.role===`phone`?this.options.computerFp:this.options.phoneFp,n=this.options.role===`phone`?this.options.phoneFp:this.options.computerFp;if(e.v!==1||e.t!==`e2e`||e.from!==t||e.to!==n)throw Error(`v2 carrier peer mismatch`);let r=Zn.parse(e.body);if(r.c.length<16||r.c.length>2048)throw Error(`v2 carrier ciphertext exceeds bound`);if(this.stage===`phone:hello`||this.stage===`computer:hello`){if(e.seq!==0)throw Error(`v2 carrier expected hello`);let i=dd(Gn(fc(this.pairKey,r,vc(t,n))));if(i.type!==`conn.hello`||!i.features?.includes(`session-v2`))throw Error(`v2 carrier requires v2 hello intent`);if(this.stage===`computer:hello`){this.startDeadline(),this.phoneNonce=i.n.slice();let e=ya(16);if(Tr(this.phoneNonce,e))throw Error(`reused hello nonce`);return this.deriveConnection(this.phoneNonce,e),this.stage=`bootstrap`,this.hello(e)}if(!this.phoneNonce||Tr(this.phoneNonce,i.n))throw Error(`invalid hello nonce`);return this.deriveConnection(this.phoneNonce,i.n),this.stage=`bootstrap`,this.frame(this.bootstrap.begin())}if(!this.connKey||e.seq!==this.seqIn+1)throw Error(`v2 carrier frame sequence mismatch`);let i=dd(Gn(fc(this.connKey,r,_c(t,n,this.connTag,e.seq))));if(i.type!==`session.v2.bootstrap`)throw Error(`v2 carrier rejects legacy terminal message`);this.seqIn=e.seq;let a=this.bootstrap.receive(i.bytes);return this.bootstrap.ready&&(this.stage=`ready`,this.clearDeadline()),a?this.frame(a):null}catch(e){throw this.close(),e}}takeReadySession(){if(!this.ready)throw Error(`v2 carrier not confirmed`);let e=this.bootstrap.takeReadySession();return this.close(),e}close(){this.stage!==`closed`&&(this.stage=`closed`,this.clearDeadline(),this.pairKey.fill(0),this.phoneNonce?.fill(0),this.phoneNonce=null,this.connKey?.fill(0),this.connKey=null,this.connTag=``,this.bootstrap.close())}hello(e){let t=this.options.role===`phone`?this.options.phoneFp:this.options.computerFp,n=this.options.role===`phone`?this.options.computerFp:this.options.phoneFp;return{v:1,t:`e2e`,from:t,to:n,seq:0,body:dc(this.pairKey,H({type:`conn.hello`,n:e,features:[`session-v2`]}),vc(t,n))}}frame(e){if(!this.connKey||this.seqOut>=2**53-1)throw Error(`v2 carrier unavailable`);let t=this.options.role===`phone`?this.options.phoneFp:this.options.computerFp,n=this.options.role===`phone`?this.options.computerFp:this.options.phoneFp,r=++this.seqOut;return{v:1,t:`e2e`,from:t,to:n,seq:r,body:dc(this.connKey,H({type:`session.v2.bootstrap`,bytes:e}),_c(t,n,this.connTag,r))}}deriveConnection(e,t){let n=hc(this.pairKey,e,t,this.options.computerFp,this.options.phoneFp);this.connKey=n.kConn,this.connTag=n.connTag}startDeadline(){if(this.startedAt=this.options.now(),!Number.isFinite(this.startedAt))throw Error(`invalid v2 carrier clock`);this.timer=setTimeout(()=>this.close(),this.timeoutMs)}checkDeadline(){let e=this.options.now();if(this.startedAt===null||!Number.isFinite(e)||e<this.startedAt||e-this.startedAt>=this.timeoutMs)throw Error(`v2 carrier handshake expired`)}clearDeadline(){this.timer&&clearTimeout(this.timer),this.timer=null}};function If(e){return{route:e.route,sessionId:e.sessionId.slice(),attemptId:e.attemptId.slice(),generation:e.generation.slice()}}function Lf(e,t){return e.route===t.route&&Tr(e.sessionId,t.sessionId)&&Tr(e.attemptId,t.attemptId)&&Tr(e.generation,t.generation)}var Rf=class{options;relay=null;active=null;staged=null;transition=null;wireIds=new Set;attemptIds=new Set;transitionIds=new Set;highGeneration=1n;directAttempts=0;lastNow=-1;deadline=null;timer=null;revoked=!1;recovering=!1;snapshot=!1;revision=0;constructor(e){if(this.options=e,W.parse(e.computerFp),W.parse(e.phoneFp),e.role!==`phone`&&e.role!==`computer`)throw Error(`invalid route role`);this.installRelay(e.relay)}get status(){return this.revoked?`closed`:this.recovering?`recovering`:this.transition?`cutover`:this.active?.reference.route??`uncommitted`}get activeRoute(){return this.active?If(this.active.reference):null}get routeRevision(){return this.revision}get needsSnapshot(){return this.snapshot}get preparationPending(){return this.transition?.phase===`computer:preparing`}get paused(){return this.revoked||this.recovering||this.transition!==null||this.active===null}get directActive(){return this.active?.reference.route===`direct`}snapshotApplied(){this.paused||(this.snapshot=!1)}stageDirect(e){if(this.sweep(),this.revoked||this.recovering||!this.active||!this.relay||this.staged||this.transition)throw Error(`route candidate unavailable`);let t=null;try{if(t=this.validate(e,`direct`),!Tr(t.reference.sessionId,this.relay.reference.sessionId))throw Error(`direct wire session mismatch`);let n=bl(t.reference.generation);if(n<=this.highGeneration)throw Error(`direct generation reused`);let r=Sr(t.reference.attemptId);if(this.attemptIds.has(r))throw Error(`direct attempt reused`);if(this.directAttempts>=ql.directAttempts)throw Error(`direct attempt capacity`);this.highGeneration=n,this.directAttempts+=1,this.attemptIds.add(r),this.staged=t,this.arm()}catch(t){throw e.session!==this.active?.session&&e.session!==this.relay?.session&&e.session.close(),t}}begin(){if(this.sweep(),this.options.role!==`phone`||this.revoked||this.recovering||!this.staged||!this.relay||this.transition)throw Error(`route prepare unavailable`);if(!this.options.prepareReady())return!1;let e=Al.parse(this.options.newId()).slice();if(this.transitionIds.has(Sr(e)))throw Error(`route transition reused`);return this.transitionIds.add(Sr(e)),this.transition={id:e,target:this.staged,phase:`phone:prepared`},this.sendControl(`route.prepare`)}approve(){return this.sweep(),!this.preparationPending||!this.transition||!this.options.prepareReady()||!this.transition.target.session.ready?!1:(this.transition.phase=`computer:commit`,this.sendControl(`route.prepared`))}receive(e,t){if(this.sweep(),this.revoked||this.recovering||!this.registered(e))return null;try{let n=e.open(t),r;try{r=Ql(n)}finally{n.fill(0)}if(r.kind===`control`){if(e!==this.relay?.session)throw Error(`route control requires relay session`);return this.control(r.control),null}if(r.kind===`signal`){if(e!==this.relay?.session)throw Error(`direct signaling requires relay session`);return r}return e!==this.active?.session||!this.directActive?(r.bytes.fill(0),null):r}catch{return this.routeLost(e),null}}sendTerminal(e){return this.sweep(),this.paused||!this.active||!this.directActive?!1:this.sendPayload(this.active,{kind:`terminal`,bytes:e})}sendSignal(e){return this.sweep(),this.revoked||this.recovering||!this.relay?!1:this.sendPayload(this.relay,{kind:`signal`,bytes:e})}abort(e=`cancelled`){if(!this.staged&&!this.transition)return;if(this.transition?.phase===`phone:committed`||!this.active){this.failAll();return}let t=this.transition;t&&this.relay&&this.sendPayload(this.relay,{kind:`control`,control:{type:`route.abort`,transitionId:t.id,target:If(t.target.reference),reason:e}}),this.discardCandidate(),t&&(this.snapshot=!0)}relayLost(){this.active?.reference.route===`direct`&&!this.transition&&!this.staged?(this.relay?.session.close(),this.relay=null):this.failAll()}routeLost(e){e===this.active?.session?this.failAll():e===this.relay?.session?this.relayLost():e===this.staged?.session&&this.abort(`candidate-failed`)}recover(e){if(this.revoked)throw e.session.close(),Error(`route owner revoked`);let t=this.validate(e,`relay`);if(this.wireIds.has(Sr(t.reference.sessionId)))throw t.session.close(),Error(`wire session reused`);this.failAll(),this.installRelay(t)}sweep(){if(this.revoked)return;let e=this.clock();this.deadline!==null&&e>=this.deadline&&this.abort(`timeout`)}close(){this.failAll(),this.revoked=!0,this.recovering=!1}validate(e,t){if(!(e.session instanceof Wl)||!e.session.ready||e.session.senderRole!==this.options.role)throw Error(`route session not ready`);let n=e.session.description;if(n.computerFp!==this.options.computerFp||n.phoneFp!==this.options.phoneFp||n.route!==t)throw Error(`route pairing mismatch`);if(t===`relay`&&bl(n.generation)!==1n)throw Error(`relay generation must be one`);return{session:e.session,send:e.send.bind(e),reference:If(n)}}installRelay(e){let t=this.validate(e,`relay`),n=Sr(t.reference.sessionId);if(this.wireIds.has(n)||this.wireIds.size>=ql.wireSessions)throw t.session.close(),Error(`wire session reused or capacity reached`);this.wireIds.add(n),this.attemptIds.clear(),this.transitionIds.clear(),this.attemptIds.add(Sr(t.reference.attemptId)),this.highGeneration=1n,this.directAttempts=0,this.relay=t,this.staged=t,this.recovering=!1,this.arm()}control(e){if(e.type===`route.prepare`){if(this.options.role!==`computer`||this.transition||!this.staged||!Lf(e.target,this.staged.reference)||this.transitionIds.has(Sr(e.transitionId)))throw Error(`invalid route prepare`);this.transitionIds.add(Sr(e.transitionId)),this.transition={id:e.transitionId.slice(),target:this.staged,phase:`computer:preparing`};return}let t=this.transition;if(!t||!Lf(e.target,t.target.reference)||!Tr(e.transitionId,t.id))throw Error(`route transition mismatch`);if(e.type===`route.abort`){this.abortWithoutSending();return}if(e.type===`route.prepared`&&t.phase===`phone:prepared`){if(!this.options.prepareReady()||!t.target.session.ready)throw Error(`route prepare gate changed`);t.phase=`phone:committed`,this.sendControl(`route.commit`);return}if(e.type===`route.commit`&&t.phase===`computer:commit`){if(!this.options.prepareReady()||!t.target.session.ready)throw Error(`route commit gate changed`);let e={type:`route.committed`,transitionId:t.id,target:If(t.target.reference)};this.activate(),(!this.relay||!this.sendPayload(this.relay,{kind:`control`,control:e}))&&this.failAll();return}if(e.type===`route.committed`&&t.phase===`phone:committed`){this.activate();return}throw Error(`route control order mismatch`)}sendControl(e){return!this.relay||!this.transition?!1:this.sendPayload(this.relay,{kind:`control`,control:{type:e,transitionId:this.transition.id,target:If(this.transition.target.reference)}})}sendPayload(e,t){let n=Zl(t);try{if(e.send(e.session.seal(n))===!0)return!0}catch{}finally{n.fill(0)}return t.kind===`control`?this.failAll():this.routeLost(e.session),!1}activate(){if(!this.staged)throw Error(`route target missing`);let e=this.active;this.active=this.staged,this.staged=null,this.transition=null,e&&e!==this.relay&&e!==this.active&&e.session.close(),this.clearTimer(),this.snapshot=!0,this.revision+=1}abortWithoutSending(){if(this.transition?.phase===`phone:committed`||!this.active){this.failAll();return}this.discardCandidate(),this.snapshot=!0}discardCandidate(){this.staged&&this.staged!==this.active&&this.staged!==this.relay&&this.staged.session.close(),this.staged=null,this.transition=null,this.clearTimer()}failAll(){for(let e of new Set([this.active,this.staged,this.relay]))e?.session.close();this.active=null,this.staged=null,this.relay=null,this.transition=null,this.clearTimer(),this.recovering=!0,this.snapshot=!0,this.revision+=1}registered(e){return e===this.relay?.session||e===this.active?.session||e===this.staged?.session}clock(){let e=this.options.now();if(!Number.isFinite(e)||e<0||e<this.lastNow)throw this.failAll(),Error(`invalid route clock`);return this.lastNow=e,e}arm(){this.clearTimer(),this.deadline=this.clock()+ql.attemptMs,this.timer=setTimeout(()=>this.abort(`timeout`),ql.attemptMs)}clearTimer(){this.timer&&clearTimeout(this.timer),this.timer=null,this.deadline=null}};function zf(e,t,n,r){if(e.seq!==0||e.from!==r||e.to!==n)return!1;try{let i=dd(Gn(fc(t,Zn.parse(e.body),vc(r,n))));return i.type===`conn.hello`&&i.features?.includes(`session-v2`)===!0}catch{return!1}}var Bf=class{options;carrier=null;owner=null;relaySession=null;direct=null;directStartedAt=null;directSetupMs=null;generation=1n;lastFailure=null;retryAt=null;retryFailures=0;nativeAttempts=0;retriesExhausted=!1;traffic={relaySent:0,relayReceived:0,directSent:0,directReceived:0};bootstrapRevision=0;reportedRevision=-1;reportedRoute=null;reportedState=``;recoveryNotified=!1;closed=!1;incoming=Promise.resolve();queued=0;clock;interval;constructor(e){this.options=e,this.clock=e.now??(()=>performance.now()),this.interval=setInterval(()=>this.poll(),100)}get activeRoute(){return this.owner?.activeRoute?.route??null}get ready(){return this.activeRoute!==null&&this.owner?.paused===!1}get routeRevision(){return this.owner?.routeRevision??0}get diagnostics(){let e=this.direct,t=this.activeRoute===`direct`?`direct`:e?.phase??`none`;return{route:this.activeRoute,ready:this.ready,phase:t,lastFailure:this.lastFailure,directSetupMs:this.directSetupMs,...this.traffic}}routeStats(){return this.activeRoute!==`direct`||!this.direct?Promise.resolve(null):this.direct.routeStats().catch(()=>null)}get state(){let{route:e,ready:t,phase:n,lastFailure:r}=this.diagnostics;return{route:e,ready:t,phase:n,lastFailure:r,retryPending:this.retryAt!==null}}sendRelay(e){let t=this.options.sendRelay(e);return t&&e.v===2&&(this.traffic.relaySent+=e.body.length),t}begin(){this.closed||this.options.role!==`phone`||(this.carrier?.close(),this.carrier=this.newCarrier(),this.bootstrapRevision+=1,this.sendRelay(this.carrier.start())||this.bootstrapFailed())}receiveRelay(e){if(this.closed)return Promise.resolve();if(++this.queued>32)return--this.queued,this.bootstrapFailed(),Promise.resolve();let t=this.incoming.then(()=>this.relay(e));return this.incoming=t.catch(()=>this.bootstrapFailed()).finally(()=>{--this.queued}),this.incoming}sendTerminal(e){return this.owner?.sendTerminal(e)??!1}relayLost(){this.owner?.relayLost(),this.carrier?.close(),this.carrier=null,this.changed()}close(){this.closed||(this.closed=!0,clearInterval(this.interval),this.carrier?.close(),this.carrier=null,this.owner?.close(),this.owner=null,this.closeDirect())}interruptDirect(){this.directFailed(`interrupted`)}newCarrier(){return new Ff({role:this.options.role,computerFp:this.options.computerFp,phoneFp:this.options.phoneFp,keys:this.options.keys,now:this.clock,newId:()=>ya(16)})}async relay(e){if(this.closed||e.from!==(this.options.role===`phone`?this.options.computerFp:this.options.phoneFp)||e.to!==(this.options.role===`phone`?this.options.phoneFp:this.options.computerFp))return;if(e.v===2){if(this.traffic.relayReceived+=e.body.length,!this.owner||!this.relaySession)return;let t=this.owner.receive(this.relaySession,Vl(e.body));if(t?.kind===`terminal`)this.options.terminal(t.bytes,e.body.length);else if(t?.kind===`signal`){let e=this.direct;try{await this.signal(t.bytes)}catch{this.direct===e&&!e?.session?.ready&&this.directFailed(`remote-signal`,e??void 0)}}this.poll();return}if(e.t!==`e2e`)return;if(this.options.role===`computer`&&e.seq===0){if(!zf(e,this.options.keys.pairKey,this.options.computerFp,this.options.phoneFp))return;this.carrier?.close(),this.carrier=this.newCarrier(),this.bootstrapRevision+=1}let t=this.carrier;if(!t)return;let n=this.bootstrapRevision,r=t.receive(e);if(r&&!this.sendRelay(r))throw Error(`bootstrap queue refused`);if(!t.ready)return;let i=t.takeReadySession();this.carrier=null;try{await this.options.commitFloor()}catch(e){throw i.close(),e}if(this.closed||n!==this.bootstrapRevision){i.close();return}this.closeDirect(),this.relaySession=i,this.generation=1n,this.nativeAttempts=0,this.retriesExhausted=!1,this.retryAt=null;let a={session:i,send:e=>this.sendRelay({v:2,t:`e2e`,from:this.options.role===`phone`?this.options.phoneFp:this.options.computerFp,to:this.options.role===`phone`?this.options.computerFp:this.options.phoneFp,body:Bl(e)})};this.owner?this.owner.recover(a):this.owner=new Rf({role:this.options.role,computerFp:this.options.computerFp,phoneFp:this.options.phoneFp,relay:a,now:this.clock,newId:()=>ya(16),prepareReady:this.options.prepareReady}),this.options.role===`phone`&&this.owner.begin(),this.recoveryNotified=!1,this.poll()}poll(){if(this.closed||(this.carrier?.closed&&this.bootstrapFailed(),!this.owner))return;try{this.owner.sweep(),this.owner.preparationPending&&this.owner.approve(),this.options.role===`phone`&&(this.owner.status===`uncommitted`||this.owner.status===`relay`&&this.direct?.session&&this.direct.session.ready)&&this.owner.begin(),this.changed(),this.retryDirect(),this.owner.status===`recovering`&&!this.carrier&&!this.recoveryNotified&&(this.recoveryNotified=!0,this.closeDirect(),this.options.failure(`recovery`))}catch{this.options.failure(`recovery`)}let e=this.state,t=JSON.stringify(e);t!==this.reportedState&&(this.reportedState=t,this.options.stateChanged?.(e))}changed(){let e=this.activeRoute,t=this.routeRevision;(this.reportedRevision!==t||this.reportedRoute!==e)&&(this.reportedRevision=t,this.reportedRoute=e,this.options.routeChanged(e,t),e===`direct`&&this.direct&&(this.directStartedAt!==null&&(this.directSetupMs=Math.round(this.clock()-this.directStartedAt)),this.directStartedAt=null,this.direct.cancelDeadline(),this.retryFailures=0,this.retryAt=null,this.lastFailure=null))}retryDirect(){if(this.options.role===`phone`&&this.options.allowDirect&&this.options.native&&!this.retriesExhausted&&!this.direct&&!this.carrier&&this.ready&&this.activeRoute===`relay`&&this.options.prepareReady()&&!(this.retryAt!==null&&this.clock()<this.retryAt)){if(this.nativeAttempts>=ql.directAttempts){this.retriesExhausted=!0,this.bootstrapFailed();return}this.nativeAttempts+=1,this.retryAt=null,this.startDirect()}}bootstrapFailed(){this.carrier?.close(),this.carrier=null,this.options.failure(`bootstrap`)}async startDirect(e){if(this.closed||this.direct||!this.ready||!this.relaySession||!this.options.native)return;this.generation=e?new DataView(e.generation.buffer,e.generation.byteOffset,8).getBigUint64(0,!0):this.generation+1n;let t=new Mf({role:this.options.role,keys:this.options.keys,computerFp:this.options.computerFp,phoneFp:this.options.phoneFp,relay:this.relaySession.description,generation:e?.generation??yl(this.generation),offer:e,native:this.options.native,current:()=>!this.closed&&this.direct===t,committed:()=>this.activeRoute===`direct`,sendSignal:e=>this.sendSignal(e),sent:e=>{this.traffic.directSent+=e},received:e=>{this.traffic.directReceived+=e},ready:e=>{this.owner?.stageDirect({session:e,send:e=>t.send(Bl(e))}),this.options.role===`phone`&&this.owner?.begin()},frame:(e,t)=>{let n=this.owner?.receive(e,Vl(t));n?.kind===`terminal`&&this.options.terminal(n.bytes,t.length),this.poll()},failed:e=>this.directFailed(e,t)});this.direct=t,this.directStartedAt=this.clock(),await t.start()}async signal(e){if(!this.relaySession||!this.owner)return;let t=this.direct;if(this.activeRoute===`direct`&&t?.session?.ready)return;let n=Ef(e,{sender:this.options.role===`phone`?`computer`:`phone`,sessionId:this.relaySession.description.sessionId,committedGeneration:this.relaySession.description.generation,...t&&{pending:{offerId:t.offerId,generation:t.generation}}});if(n.type===`direct.offer`){if(!this.options.native||this.options.role!==`computer`)return;await this.startDirect(n);return}await t?.signal(n)}sendSignal(e){return this.owner?.sendSignal(Tf(e))??!1}directFailed(e=`closed`,t){if(t&&this.direct!==t)return;let n=this.direct;if(!n)return;let r=this.diagnostics.phase,i=Math.min(6e4,5e3*2**this.retryFailures);if(this.retryFailures=Math.min(this.retryFailures+1,4),this.retryAt=this.clock()+Math.min(6e4,i*(.8+.4*ya(1)[0]/255)),this.lastFailure=e,!n.session?.ready)try{this.sendSignal({type:`direct.abort`,...n.signalContext(),reason:e===`timeout`?`timeout`:e===`certificate`?`dtls-failed`:`ice-failed`})}catch{}let a=n?.session;a&&this.owner?.routeLost(a),this.closeDirect(),this.options.failure(`direct`,{code:e,phase:r}),this.poll()}closeDirect(){let e=this.direct;this.direct=null,e&&e.close()}};function Vf(e,t){return nr.every(n=>e?.includes(n)&&t.includes(n))?[...nr,...e?.includes(`native-history-v1`)&&t.includes(`native-history-v1`)?[rr]:[]]:[]}function Hf(e){if(e.length>4096)return!1;for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let n=e.charCodeAt(++t);if(!(n>=56320&&n<=57343))return!1}else if(n>=56320&&n<=57343)return!1}return!0}const Uf=Ou.extend({t:Ou.shape.t.refine(Hf)}).strict(),Wf=ku.extend({r:F.array(Uf)}).strict(),Gf=Wf.extend({r:F.array(Uf).max(2048)}),Kf=F.number().int().min(0).max(2**53-1),qf={kind:F.literal(`history`),generation:Kf,requestId:K,before:Kf},Jf=F.custom(e=>Array.isArray(e)&&e.length>0&&e.length<=G.historyLines),Yf=F.strictObject({...qf,status:F.literal(`page`),from:Kf,to:Kf,oldestAvailable:Kf,lines:Jf});function Xf(e){return e.to===e.before&&e.lines.length<=2**53-1-e.from&&e.from+e.lines.length===e.to&&e.oldestAvailable<=e.from}const Zf=Yf.refine(Xf),Qf=Yf.extend({nextBefore:Kf}).refine(e=>Xf(e)&&e.nextBefore===e.from),$f=F.strictObject({...qf,status:F.literal(`boundary`),reason:F.enum([`end`,`truncated`]),oldestAvailable:Kf}).refine(e=>e.reason===`end`?e.before===e.oldestAvailable:e.before<e.oldestAvailable),ep=F.discriminatedUnion(`status`,[Zf,$f]),tp=F.discriminatedUnion(`status`,[Qf,$f]),np=F.strictObject({r:F.unknown(),w:F.boolean().optional()}),rp={ok:!1,code:`invalid-transfer`},ip={ok:!1,code:`history-line-too-large`};function ap(e){let t=np.safeParse(e);if(!t.success||!Array.isArray(t.data.r))return rp;if(t.data.r.length>2048)return ip;let n={r:[],...t.data.w===void 0?{}:{w:t.data.w}},r=0,i=0;for(let e of t.data.r){let t=Uf.safeParse(e);if(!t.success)return rp;if(r+=t.data.n??ef(t.data.t),r>G.historyCells||(i+=H(t.data).length,i>G.historyBytes))return ip;n.r.push(t.data)}let a=H(n).length;return a>G.historyBytes?ip:{ok:!0,line:n,bytes:a}}F.unknown().transform((e,t)=>{let n=()=>(t.addIssue({code:`custom`,message:`invalid history record`}),F.NEVER);try{let t=tp.safeParse(e);if(!t.success)return n();let r;if(t.data.status===`boundary`)r=t.data;else{let e=[],i=0;for(let r of t.data.lines){let t=ap(r);if(!t.ok||(i+=t.bytes,i>G.historyBytes))return n();e.push(t.line)}r={...t.data,lines:e}}return H(r).length>G.historyBytes?n():r}catch{return n()}});function op(e){try{let t=ep.safeParse(e);if(!t.success)return rp;if(t.data.status===`boundary`){let e=t.data;return{ok:!0,record:e,bytes:H(e)}}let n=t.data,r=[],i=0,a;for(let e=n.lines.length-1;e>=0;e--){let t=ap(n.lines[e]);if(!t.ok){if(t.code===`invalid-transfer`)return rp;break}if(i+=t.bytes,i>G.historyBytes)break;r.unshift(t.line);let o=n.from+e,s={...n,from:o,nextBefore:o,lines:r.slice()},c=H(s);c.length<=G.historyBytes&&(a={ok:!0,record:s,bytes:c})}return a??{...ip,before:n.before}}catch{return rp}}const sp=F.number().int().min(0).max(2**53-1),cp=sp.min(1),lp=Au.extend({x:sp,y:F.number().int().min(-1).max(2**53-1)}).strict(),up=F.strictObject({cols:cp,rows:cp,cursor:lp,lines:F.array(Wf),scrollbackTotal:sp,gen:sp,reset:F.boolean().optional(),degraded:F.boolean().optional()});function dp(e){return e.lines.length===e.rows&&e.cursor.x<=e.cols&&e.cursor.y<e.rows&&fp(e.lines,e.cols)}function fp(e,t){return e.every(e=>{let n=0;for(let r of e.r)if(n+=r.n??ef(r.t),n>t)return!1;return!0})}function pp(e){let t=0,n=0;for(let r of e){t+=r.r.length;for(let e of r.r)n+=ef(e.t)}return{runs:t,points:n}}function mp(e){let{runs:t,points:n}=pp(e);return t<=G.runs&&n<=G.codePoints}const hp=up.extend({kind:F.literal(`snapshot`),cols:cp.max(G.cols),rows:cp.max(G.rows),lines:F.array(Gf).max(G.rows)}).refine(e=>dp(e)&&mp(e.lines)),gp=F.strictObject({scroll:sp.max(G.rows),changed:F.array(F.strictObject({i:sp.max(G.rows-1),line:Gf})).max(G.rows),cursor:lp.extend({x:sp.max(G.cols),y:lp.shape.y.max(G.rows-1)}),scrollbackTotal:sp,gen:cp}),_p=gp.extend({kind:F.literal(`diff`)}).refine(e=>{let t=new Set(e.changed.map(e=>e.i)),n=e.changed.map(e=>e.line);return t.size===e.changed.length&&fp(n,G.cols)&&mp(n)}),vp=F.discriminatedUnion(`kind`,[hp,_p]);function yp(e){let t=vp.safeParse(e);if(!t.success)throw new V(`malformed`);let n;try{n=H(t.data)}catch{throw new V(`malformed`)}if(n.length>G.screenBytes)throw new V(`malformed`);return{record:t.data,bytes:n}}function bp(e){let{kind:t,...n}=e;return n}function xp(e){let t=up.safeParse(e);if(!t.success||!dp(t.data))return{ok:!1,code:`invalid-transfer`};let n=t.data;if(n.cols>G.cols||n.rows>G.rows||pp(n.lines).points>G.codePoints)return{ok:!1,code:`screen-too-large`};for(let e=0;e<2;e++){let t=e===0?n:{...n,lines:n.lines.map(sf),degraded:!0};try{let{record:e,bytes:n}=yp({kind:`snapshot`,...t});if(e.kind===`snapshot`)return{ok:!0,snapshot:bp(e),bytes:n}}catch{}}return{ok:!1,code:`screen-too-large`}}function Sp(e){let t=gp.safeParse(e);if(!t.success)throw new V(`malformed`);return yp({kind:`diff`,...t.data}).bytes}var Cp=class{options;lanes=[null,null];outstanding=[];state=`open`;nextLane=0;lastSequence=0;acknowledgedThrough=0;constructor(e){if(!cr.shape.subscriptionId.safeParse(e.subscriptionId).success||!cr.shape.sessionId.safeParse(e.sessionId).success)throw Error(`Invalid stream sender identity`);this.options={...e}}canOffer(e){return this.tick()===`open`&&this.lanes[+(e===`history`)]===null}offer(e,t){if(this.tick()!==`open`)return{accepted:!1,reason:`closed`};let n=sr.safeParse(e);if(!n.success||!(t instanceof Uint8Array)||t.length===0)throw Error(`Invalid stream transfer`);let r=+(n.data.kind===`history`),i=r===1?G.historyBytes:G.screenBytes;if(t.length>i)return{accepted:!1,reason:`too-large`};if(this.lanes[r])return{accepted:!1,reason:`busy`};let a;try{a=this.options.newTransferId()}catch(e){throw this.cancel(),e}if(!cr.shape.transferId.safeParse(a).success)throw Error(`Invalid stream transfer identity`);return this.state===`open`?(this.lanes[r]={id:a,meta:n.data,bytes:new Uint8Array(t),count:Math.ceil(t.length/G.chunkBytes),nextIndex:0,acknowledged:0,startedAt:null,progressAt:null},{accepted:!0,transferId:a}):{accepted:!1,reason:`closed`}}pump(){if(this.tick()!==`open`)return 0;let e=0;for(;e<G.unacked&&this.inFlight<G.unacked&&this.tick()===`open`;){let t=this.nextLane,n=this.lanes[t];if((!n||n.nextIndex===n.count)&&(t=1-t,n=this.lanes[t]),!n||n.nextIndex===n.count)break;if(this.lastSequence===2**53-1){this.cancel();break}let r=this.lastSequence+1,i=n.nextIndex,a={type:`stream.chunk`,subscriptionId:this.options.subscriptionId,sessionId:this.options.sessionId,transferId:n.id,sequence:r,index:i,count:n.count,totalBytes:n.bytes.length,data:n.bytes.slice(i*G.chunkBytes,(i+1)*G.chunkBytes),meta:{...n.meta}},o;try{o=this.options.send(a)}catch(e){throw this.cancel(),e}if(o&&e++,this.state!==`open`||!o)break;this.lastSequence=r,n.nextIndex++,n.startedAt===null&&(n.startedAt=this.options.now(),n.progressAt=n.startedAt),this.outstanding.push({sequence:r,transfer:n}),this.nextLane=1-t}return e}acknowledge(e,t){if(e!==this.options.subscriptionId||this.tick()!==`open`)return`ignored`;if(!Number.isSafeInteger(t)||t<1||t>this.lastSequence)return`invalid`;if(t<=this.acknowledgedThrough)return`duplicate`;let n=this.options.now();for(let e of this.outstanding){if(e.sequence>t)break;e.transfer.acknowledged++,e.transfer.progressAt=n,e.transfer.acknowledged===e.transfer.count&&(this.lanes[+(e.transfer.meta.kind===`history`)]=null)}return this.outstanding=this.outstanding.filter(e=>e.sequence>t),this.acknowledgedThrough=t,`advanced`}tick(){let e=this.nextDeadline();return e!==null&&this.options.now()>=e&&this.stop(`stalled`),this.state}nextDeadline(){let e=1/0;for(let t of this.lanes)t&&t.startedAt!==null&&t.progressAt!==null&&(e=Math.min(e,t.startedAt+G.totalMs,t.progressAt+G.progressMs));return Number.isFinite(e)?e:null}cancel(){this.stop(`closed`)}stop(e){this.state=e,this.lanes[0]=null,this.lanes[1]=null,this.outstanding=[]}get inFlight(){return this.outstanding.length}get retainedBytes(){return(this.lanes[0]?.bytes.length??0)+(this.lanes[1]?.bytes.length??0)}};const wp=(e,t)=>{let n=setTimeout(e,t);return()=>clearTimeout(n)};var Tp=class{options;available;window;streamWindow;highWater;lowWater;streams=new Map;closed=!1;pumping=!1;constructor(e){this.options=e,this.window=e.connectionWindow??J.connectionWindow,this.available=this.window,this.streamWindow=e.streamWindow??J.streamWindow,this.highWater=e.highWater??65536,this.lowWater=e.lowWater??32768}get outstanding(){return this.window-this.available}frame(e){this.closed||(this.queue(`stream`in e?e.stream:0).items.push({kind:`frame`,message:e}),this.pump())}write(e,t){if(this.closed)return!1;let n=this.queue(e);return t.byteLength>0&&(n.items.push({kind:`bytes`,data:t}),n.queuedBytes+=t.byteLength),this.pump(),n.queuedBytes>this.highWater&&(n.paused=!0),!n.paused}end(e){this.closed||(this.queue(e).items.push({kind:`end`}),this.pump())}reset(e,t,n){return this.streams.delete(e),!this.closed&&this.sendNow({type:`web.reset`,stream:e,reason:t,...n&&{detail:n}})===!0}forget(e){this.streams.delete(e)}dropIcon(e){let t=this.streams.get(0);t&&(t.items=t.items.filter(t=>t.kind!==`frame`||t.message.type!==`web.icon.data`||t.message.page!==e),t.items.length||this.streams.delete(0))}control(e){return!this.closed&&this.sendNow(e)===!0}receiveCredit(e){if(e.stream===0){if(e.bytes>this.outstanding)return!1;this.available+=e.bytes}else{let t=this.streams.get(e.stream);t&&(t.credit+=e.bytes)}return this.pump(),!0}queuedBytes(e){return this.streams.get(e)?.queuedBytes??0}sending(e){return this.streams.has(e)}get openStreams(){return this.streams.size}close(){this.closed=!0,this.streams.clear()}queue(e){let t=this.streams.get(e);return t||(t={items:[],credit:this.streamWindow,queuedBytes:0,paused:!1,ending:!1},this.streams.set(e,t)),t}settle(e,t){t.ending&&t.items.length===0&&this.streams.get(e)===t&&(this.streams.delete(e),this.options.settled?.(e))}sendNow(e){let t=this.options.send(e);return t===!1&&this.close(),t}notAdmitted(e,t,n=0,r=0){this.available+=n,t.credit+=r,this.streams.get(e)===t&&(this.streams.delete(e),this.options.refused?.(e))}pump(){if(!this.pumping){this.pumping=!0;try{let e=!0;for(;e&&!this.closed;){e=!1;for(let[t,n]of[...this.streams]){if(this.closed)return;this.streams.get(t)===n&&this.step(t,n)&&(e=!0)}}}finally{this.pumping=!1}}}step(e,t){let n=t.items[0];if(!n)return!1;if(n.kind===`end`)return t.items.shift(),t.ending=!0,this.sendNow({type:`web.end`,stream:e})===!0?(this.settle(e,t),!0):(this.notAdmitted(e,t),!1);if(n.kind===`frame`){let r=yu(n.message),i=bu(n.message);if(r>this.available||i>t.credit)return!1;t.items.shift(),this.available-=r,t.credit-=i;let a=n.message;return(a.type===`web.open`&&!a.body&&!a.upgrade||a.type===`web.head`&&a.end===!0)&&(t.ending=!0),this.sendNow(a)===!0?(this.options.frameSent?.(a),a.type===`web.icon.data`&&t.items.length===0&&(t.ending=!0),this.settle(e,t),!0):(this.notAdmitted(e,t,r,i),!1)}let r=this.available-J.frameAllowance-Ep(e),i=Math.min(n.data.byteLength,J.dataBytes,t.credit,r);if(i<=0||i<n.data.byteLength&&i<1024&&i<t.credit)return!1;let a={type:`web.data`,stream:e,bytes:n.data.subarray(0,i)},o=vu(H(a).byteLength);return i===n.data.byteLength?t.items.shift():n.data=n.data.subarray(i),this.available-=o,t.credit-=i,t.queuedBytes-=i,this.sendNow(a)===!0?(this.settle(e,t),t.paused&&t.queuedBytes<=this.lowWater&&(t.paused=!1,this.options.drained?.(e)),!0):(this.notAdmitted(e,t,o,i),!1)}};function Ep(e){return H({type:`web.data`,stream:e,bytes:new Uint8Array}).byteLength+4}var Dp=class{options;connectionWindow;streamWindow;timer;inFlight=0;pendingConnection=0;pendingStream=new Map;streamInFlight=new Map;cancelFlush=null;closed=!1;constructor(e){this.options=e,this.connectionWindow=e.connectionWindow??J.connectionWindow,this.streamWindow=e.streamWindow??J.streamWindow,this.timer=e.timer??wp}charged(e){let t=vu(e);return this.inFlight+=t,this.inFlight>this.connectionWindow?!1:(this.pendingConnection+=t,this.schedule(),!0)}body(e,t){if(t===0)return!0;let n=(this.streamInFlight.get(e)??0)+t;return this.streamInFlight.set(e,n),n<=this.streamWindow}consumed(e,t){t<=0||this.closed||!this.streamInFlight.has(e)||(this.pendingStream.set(e,(this.pendingStream.get(e)??0)+t),this.schedule())}forget(e){this.streamInFlight.delete(e),this.pendingStream.delete(e)}flush(){if(this.cancelFlush?.(),this.cancelFlush=null,!this.closed){if(this.pendingConnection>0){let e=this.pendingConnection;this.pendingConnection=0,this.inFlight-=e,this.options.sendCredit({type:`web.credit`,stream:0,bytes:e})}for(let[e,t]of[...this.pendingStream]){this.pendingStream.delete(e);let n=this.streamInFlight.get(e);n!==void 0&&(this.streamInFlight.set(e,n-t),this.options.sendCredit({type:`web.credit`,stream:e,bytes:t}))}}}close(){this.closed=!0,this.cancelFlush?.(),this.cancelFlush=null}schedule(){if(this.closed)return;let e=this.pendingConnection;for(let t of this.pendingStream.values())e=Math.max(e,t);if(e>=J.creditFlushBytes){this.flush();return}this.cancelFlush??=this.timer(()=>{this.cancelFlush=null,this.flush()},J.creditFlushMs)}},Op=`0.17.0`;const kp=/^owner-([1-9][0-9]*)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;function Ap(e){if(!/^[1-9][0-9]*$/.test(e))return null;let t=Number(e);return Number.isInteger(t)&&t<=2147483647?t:null}function jp(e){try{return process.kill(e,0),!0}catch(e){let t=e.code;if(t===`ESRCH`)return!1;if(t===`EPERM`)return!0;throw e}}function Mp(e,n){try{t.unlinkSync(N(e,n))}catch(e){if(e.code!==`ENOENT`)throw e}try{t.rmdirSync(e)}catch(e){if(![`ENOENT`,`ENOTEMPTY`,`EEXIST`].includes(e.code??``))throw e}}function Np(e){let n=`${A(e)}.lock-candidate-`;for(let r of t.readdirSync(j(e))){if(!r.startsWith(n))continue;let i=`owner-${r.slice(n.length)}`,a=kp.exec(i),o=a&&Ap(a[1]);if(!o)continue;let s=N(j(e),r);try{if(jp(o)||!t.lstatSync(s).isDirectory())continue;let e=t.readdirSync(s);e.length===0?t.rmdirSync(s):e.length===1&&e[0]===i&&t.lstatSync(N(s,i)).isFile()&&Mp(s,i)}catch{}}}function Pp(e){let n=`${e}.lock`,r=`${process.pid}-${ce()}`,i=`${e}.lock-candidate-${r}`,a=`owner-${r}`;t.mkdirSync(i,{mode:448});let o=!1;try{t.writeFileSync(N(i,a),``,{mode:384,flag:`wx`});for(let r=0;r<3;r++){try{t.renameSync(i,n),o=!0;try{Np(e)}catch{}return()=>Mp(n,a)}catch(e){if(![`EEXIST`,`ENOTEMPTY`].includes(e.code??``))throw e}try{if(!t.lstatSync(n).isDirectory())throw Error(`Invalid control guard ${n}; inspect it before retrying`);let e=t.readdirSync(n);if(e.length===0)continue;let r=e[0],i=kp.exec(r),a=i&&Ap(i[1]);if(e.length!==1||!a||!t.lstatSync(N(n,r)).isFile())throw Error(`Invalid control guard ${n}; inspect its owner marker before retrying`);if(jp(a))throw Error(`Control endpoint busy (guard owner pid ${a})`);Mp(n,r)}catch(e){if(e.code!==`ENOENT`)throw e}}throw Error(`Control endpoint busy; could not acquire ${n} after three attempts`)}finally{o||Mp(i,a)}}var Y=class extends Error{kind;constructor(e){super(`shellbell: ${e} Linux host state; inspect ownership, permissions and host initialization`),this.kind=e}};function X(e){try{return p(e)}catch(e){if(e.code===`ENOENT`)return;throw new Y(`unsafe`)}}function Fp(e,t){return e.dev===t.dev&&e.ino===t.ino}function Z(e,t){let n=X(e);if(!n)throw new Y(`missing`);if(!n.isDirectory()||n.isSymbolicLink()||n.uid!==t||(n.mode&4095)!=448)throw new Y(`unsafe`);return n}function Ip(e){let t=P(e),n=X(t);if(n){if(n.isSymbolicLink()||!n.isDirectory())throw new Y(`unsafe`);return y(t)}return N(Lp(j(t)),A(t))}function Lp(e){if(X(e))try{return y(e)}catch{throw new Y(`unsafe`)}return N(Lp(j(e)),A(e))}function Rp(e,t,n,r=!0){let i;try{let a=X(e);if(!a)throw new Y(`missing`);let s=e=>{if(!e.isFile()||e.isSymbolicLink()||n!==void 0&&(e.uid!==n||(e.mode&4095)!=384))throw new Y(`unsafe`);if(e.size>t)throw new Y(`invalid`)};s(a),i=h(e,o.O_RDONLY|o.O_NOFOLLOW|o.O_NONBLOCK);let c=l(i);if(s(c),!Fp(a,c))throw new Y(`unsafe`);let u=Buffer.alloc(t+ +!!r),d=0;for(;d<u.length;){let e=_(i,u,d,u.length-d,null);if(e===0)break;d+=e}let f=l(i),p=X(e);if(s(f),!p||!Fp(c,p)||!Fp(c,f)||c.size!==f.size||c.mtimeMs!==f.mtimeMs||c.ctimeMs!==f.ctimeMs)throw new Y(`unsafe`);if(s(p),d>t||d!==f.size)throw new Y(`invalid`);return u.subarray(0,d)}catch(e){throw e instanceof Y?e:new Y(`unsafe`)}finally{i!==void 0&&a(i)}}function zp(e={}){let t=e.uid??process.getuid?.(),n=e.euid??process.geteuid?.();if(!Number.isInteger(t)||t===void 0||t<=0||t!==n)throw Error(`shellbell: Linux hosting requires matching non-root real and effective users`);let r;try{let t=Rp(e.machineIdPath??`/etc/machine-id`,256,void 0,!1).toString(`utf8`);if(!/^[0-9a-fA-F]{32}\n?$/.test(t)||/^0{32}\n?$/.test(t))throw Error();r=Buffer.from(t.trim().toLowerCase(),`hex`)}catch{throw Error(`shellbell: Linux machine identity is unavailable or invalid; provision /etc/machine-id before host initialization`)}let i=oe(`sha256`,`shellbell.local-host-scope.v1`).update(r).digest(`hex`),a=i.slice(0,32);return{uid:t,machineId:r.toString(`hex`),hostDigest:i,hostScope:a}}const Bp=new WeakMap,Vp=new Set([16914836,61267,1481003842,2435016766]);function Hp(e,t){let n=Bp.get(e),r=n?.root??j(j(e.runtimeDir)),i=n?.fsType??(e=>C(e).type);try{if(Z(r,e.linuxHost.uid),!Vp.has(Number(i(r))))throw new Y(`unsafe`);for(let n of[N(r,`shellbell`),e.runtimeDir]){if(!X(n)){if(!t)continue;try{m(n,{mode:448})}catch(e){if(e.code!==`EEXIST`)throw e}}if(Z(n,e.linuxHost.uid),!Vp.has(Number(i(n))))throw new Y(`unsafe`)}X(e.runtimeDir)&&Up(e.runtimeDir,e.linuxHost.uid,0,i)}catch{throw Error(`shellbell: Shellbell can't use your login session's runtime folder (XDG_RUNTIME_DIR). Log in to this computer as yourself, directly or over SSH, rather than through sudo or su, and try again. The folder must be private to you (0700) and on local storage.`)}}function Up(e,t,n,r){if(n>2)throw new Y(`unsafe`);let i=v(e);if(i.length>256)throw new Y(`unsafe`);for(let a of i){let i=N(e,a),o=X(i);if(!o||o.uid!==t||o.isSymbolicLink())throw new Y(`unsafe`);if(o.isDirectory()){if(Z(i,t),!Vp.has(Number(r(i))))throw new Y(`unsafe`);Up(i,t,n+1,r)}else if(!o.isFile()&&!o.isSocket()||(o.mode&4095)!=384)throw new Y(`unsafe`)}}function Wp(e,t){if(j(t)!==j(e.runtimeDir))throw new Y(`unsafe`);Z(t,e.linuxHost.uid);let n=Bp.get(e)?.fsType??(e=>C(e).type);if(!Vp.has(Number(n(t))))throw new Y(`unsafe`);Up(t,e.linuxHost.uid,0,n)}function Gp(e={}){let{uid:t,hostDigest:n,hostScope:r}=zp(e),i=e.env??process.env,a=e.home??D(),o=i.SHELLBELL_DIR;if(o!==void 0&&!M(o))throw Error(`shellbell: SHELLBELL_DIR must be absolute`);let s=i.XDG_STATE_HOME&&M(i.XDG_STATE_HOME)?i.XDG_STATE_HOME:N(a,`.local`,`state`),c=Ip(o??N(s,`shellbell`,`hosts`,r));X(c)&&Z(c,t);let l=i.XDG_RUNTIME_DIR??`/run/user/${t}`;if(!M(l))throw Error(`shellbell: XDG_RUNTIME_DIR must be absolute`);let u=N(P(l),`shellbell`,ae(`sha256`).update(c).digest(`hex`).slice(0,32)),d={dir:c,serviceOwner:N(c,`service-owner.json`),identity:N(c,`identity.json`),config:N(c,`config.json`),pairings:N(c,`pairings.json`),log:N(c,`agent.log`),runtimeDir:u,sock:N(u,`agent.sock`),pid:N(u,`agent.pid`),linuxHost:{uid:t,hostDigest:n,hostScope:r}};if(Buffer.byteLength(d.sock)>107)throw Error(`shellbell: Linux socket path exceeds 107 bytes; choose a shorter XDG_RUNTIME_DIR`);return Bp.set(d,{root:P(l),fsType:e.runtimeFsType??(e=>C(e).type)}),Hp(d,!1),d}function Kp(e){Hp(e,!0)}const qp=F.object({v:F.literal(1),relayUrl:F.string().url(),computerName:F.string().min(1).max(64),accent:F.string().min(1).max(32),notifyMinCommandMs:F.number().int().nonnegative().default(1e4),idleQuietMs:F.number().int().positive().default(4e3),idleMinActiveMs:F.number().int().nonnegative().default(1500),turn:F.boolean().optional(),showAgentConversations:F.boolean().optional(),terminalPlugins:F.array(F.string().min(1).max(4096).refine(e=>e.startsWith(`/`)&&e.endsWith(`.mjs`)&&[...e].every(e=>e.charCodeAt(0)>=32&&e.charCodeAt(0)!==127))).max(29).optional()}),Jp=F.object({phoneFp:F.string().regex(/^[a-z2-7]{26}$/),name:F.string().min(1).max(64),platform:F.enum([`ios`,`android`]),ed25519Pub:F.string(),x25519Pub:F.string(),kPair:F.string(),minProtocolVersion:F.literal(2).optional(),pairedAt:F.string(),lastSeenAt:F.string().nullable()}),Yp=F.object({v:F.literal(1),phones:F.array(Jp)});function Xp(e,t){if(!e||e.phoneFp!==t.phoneFp||e.kPair!==t.kPair)return t;if(e.ed25519Pub!==t.ed25519Pub||e.x25519Pub!==t.x25519Pub)throw Error(`shellbell: pairing identity changed without a new pairing key`);return e.minProtocolVersion===2?{...t,minProtocolVersion:2}:t}const Zp=F.object({v:F.literal(1),hostDigest:F.string().regex(/^[0-9a-f]{64}$/),installationId:F.string().uuid()}).strict();function Qp(e){try{let t=ic(JSON.parse(e.toString(`utf8`))),n=tc(t.ed25519.priv,t.x25519.priv,t.createdAt);if(!Buffer.from(n.ed25519.pub).equals(Buffer.from(t.ed25519.pub))||!Buffer.from(n.x25519.pub).equals(Buffer.from(t.x25519.pub)))throw Error();return{identity:t,fp:ac(t.ed25519.pub)}}catch{throw new Y(`invalid`)}}function $p(e){try{return qp.parse(JSON.parse(e.toString(`utf8`)))}catch{throw new Y(`invalid`)}}function em(e){try{let{phones:t}=Yp.parse(JSON.parse(e.toString(`utf8`)));for(let e of t){let t=br(e.ed25519Pub);if(t.length!==32||br(e.x25519Pub).length!==32||br(e.kPair).length!==32||ac(t)!==e.phoneFp)throw Error()}return t}catch{throw new Y(`invalid`)}}function tm(e,t){let n=Z(e,t),r=Rp(N(e,`identity.json`),65536,t),i=Rp(N(e,`config.json`),65536,t),a=Rp(N(e,`pairings.json`),1048576,t);if(Qp(r),$p(i),em(a),!Fp(n,Z(e,t)))throw new Y(`unsafe`);return{identity:r,config:i,pairings:a}}function nm(e){try{if(!X(e.dir))return{status:`absent`};let t=Z(e.dir,e.linuxHost.uid);for(let t of v(e.dir)){let n=/^owner-[1-9][0-9]*-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,r=`owner-${t.slice(34)}`,i=t.startsWith(`service-owner.json.lock-candidate-`)&&n.test(r);if(t===`service-owner.json.lock`||i){let a=N(e.dir,t),o;try{o=Z(a,e.linuxHost.uid);let t=v(a),s=t[0];if(!(i&&t.length===0)){if(t.length!==1||!s||!n.test(s)||i&&s!==r)throw new Y(`unsafe`);Rp(N(a,s),0,e.linuxHost.uid)}if(!Fp(o,Z(a,e.linuxHost.uid)))throw new Y(`unsafe`)}catch(t){let n=X(a);if(!n)continue;try{if(i&&o&&Fp(o,n)&&v(a).length===0&&Fp(n,Z(a,e.linuxHost.uid)))continue}catch(e){if(e instanceof Y&&e.kind===`missing`||e.code===`ENOENT`)continue;throw e}throw t}continue}let a=X(N(e.dir,t));if(a&&(!a.isFile()||a.isSymbolicLink()||a.uid!==e.linuxHost.uid||(a.mode&4095)!=384))throw new Y(`unsafe`)}let n=N(e.dir,`host.json`);if(!X(n))return{status:`unmarked`,reason:`Host marker missing; explicit host initialization or recovery required`};let r,i=Rp(n,4096,e.linuxHost.uid);try{r=Zp.parse(JSON.parse(i.toString(`utf8`)))}catch{throw new Y(`invalid`)}if(r.hostDigest!==e.linuxHost.hostDigest)return{status:`wrong-host`,reason:`State belongs to a different host; choose this host's state directory`};let a=tm(e.dir,e.linuxHost.uid);if(!i.equals(Rp(n,4096,e.linuxHost.uid))||!Fp(t,Z(e.dir,e.linuxHost.uid)))throw new Y(`unsafe`);return{status:`ready`,bytes:a}}catch(e){return{status:e instanceof Y&&e.kind===`unsafe`?`unsafe`:`invalid`,reason:`Host state failed validation; inspect files and recover explicitly`}}}function rm(e){let t=nm(e);return t.status===`ready`?{status:`ready`}:t}function im(e,t){return t===`unmarked`||t===`wrong-host`?`Shellbell found a state folder at ${e} that this computer didn't create. It may have been copied from another computer, and two computers must never share one identity, so Shellbell won't use it. Move the folder aside to start fresh, or see the Linux guide to move Shellbell from another computer.`:`Shellbell's state folder at ${e} failed its safety checks. It must belong to you, must not be writable by anyone else, and should hold only Shellbell's files. Run \`shellbell doctor\` for details.`}function am(e,t=rm(e).status){return Error(t===`absent`?"shellbell: Shellbell isn't set up on this computer yet. Run `shellbell install`.":`shellbell: ${im(e.dir,t)}`)}function om(e){let t=nm(e);if(!(`bytes`in t))throw am(e,t.status);return t.bytes}function sm(e){let{status:t}=rm(e);if(t!==`ready`)throw am(e,t)}function cm(e){return Qp(om(e).identity)}function lm(e){return $p(om(e).config)}function um(e){return em(om(e).pairings)}const dm=[`emerald`,`blue`,`amber`,`violet`,`rose`,`cyan`,`lime`,`orange`];function fm(e=process.env.SHELLBELL_DIR??N(D(),`.shellbell`)){return{dir:e,serviceOwner:N(e,`service-owner.json`),identity:N(e,`identity.json`),pairings:N(e,`pairings.json`),config:N(e,`config.json`),log:N(e,`agent.log`),sock:N(e,`agent.sock`),pid:N(e,`agent.pid`)}}function pm(e){if(e.linuxHost){sm(e);return}m(e.dir,{recursive:!0,mode:448}),i(e.dir,448)}function mm(e,t,n){vm(e,t,t=>{n?.(),b(t,e)})}const hm=new Set([`EPERM`,`ENOTSUP`,`EOPNOTSUPP`,`EXDEV`]);function gm(e,t){try{return vm(e,t,n=>{try{f(n,e)}catch(n){if(!hm.has(n.code??``))throw n;_m(e,t)}ee(n)}),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}}function _m(e,t){let n=h(e,`wx`,384),r=l(n),i=!1;try{c(n,384);let e=typeof t==`string`?Buffer.from(t):t,r=0;for(;r<e.byteLength;){let t=E(n,e,r,e.byteLength-r);if(t<=0)throw Error(`secret file write made no progress`);r+=t}u(n),i=!0}finally{if(a(n),!i)try{let t=p(e);t.dev===r.dev&&t.ino===r.ino&&ee(e)}catch{}}}function vm(e,t,n){let r=`${e}.tmp-${process.pid}`,o=null;try{let s;try{s=h(r,`wx`,384)}catch(t){if(t.code!==`EEXIST`)throw t;r=`${e}.tmp-${process.pid}-${ce()}`,s=h(r,`wx`,384)}try{let e=l(s);o={dev:e.dev,ino:e.ino};let n=typeof t==`string`?Buffer.from(t):t,r=0;for(;r<n.byteLength;){let e=E(s,n,r,n.byteLength-r);if(e<=0)throw Error(`atomic file write made no progress`);r+=e}u(s)}finally{a(s)}i(r,384),n(r)}catch(e){try{if(o){let e=p(r);e.dev===o.dev&&e.ino===o.ino&&ee(r)}}catch{}throw e}}function ym(e){let t;try{t=g(e,`utf8`)}catch(t){throw Error(`shellbell: cannot read ${e}: ${t.message}`)}try{return JSON.parse(t)}catch{throw Error(`shellbell: ${e} is not valid JSON`)}}function bm(){return{v:1,relayUrl:`wss://relay.shellbell.dev`,computerName:O().replace(/\.local$/,``)||`Mac`,accent:dm[0],notifyMinCommandMs:1e4,idleQuietMs:3e4,idleMinActiveMs:1500}}function xm(e){return Em(e,()=>{if(km(e),e.linuxHost)return lm(e);if(!X(e.dir))return bm();let t=Z(e.dir,process.getuid());if(!X(e.config))return bm();let n=Rp(e.config,wm,process.getuid());if(!Fp(t,Z(e.dir,process.getuid())))throw new Y(`unsafe`);let r;try{r=JSON.parse(n.toString(`utf8`))}catch{throw new Tm(`invalid`,e.config,`not valid JSON`)}return Dm(e,r)})}function Sm(e){return e.linuxHost?xm(e):jm(e,()=>{let t=xm(e);return X(e.config)||Mm(e,t),t})}function Cm(e,t){return jm(e,()=>t(xm(e)))}const wm=65536;var Tm=class extends Error{code;constructor(e,t,n=e){super(`shellbell: config ${n} at ${t}`),this.code=e,this.name=`ConfigEditError`}};function Em(e,t){try{return t()}catch(t){throw t instanceof Tm?t:new Tm(t instanceof Y?t.kind===`invalid`?`invalid`:`unsafe`:`io`,e.config)}}function Dm(e,t){let n=qp.safeParse(t);if(!n.success)throw new Tm(`invalid`,e.config);return n.data}function Om(e){if(e.linuxHost){sm(e);return}Z(e.dir,process.getuid())}function km(e){if([e.dir,e.config].some(e=>Buffer.byteLength(e)>4096||e.includes(`\0`))||j(P(e.config))!==P(e.dir))throw new Tm(`unsafe`,e.config)}function Am(e,t){let n=`${A(e)}.lock`;for(let r of v(j(e))){if(r!==n&&!r.startsWith(`${n}-candidate-`))continue;let i=N(j(e),r);if(X(i)){Z(i,t);for(let e of v(i)){let n=X(N(i,e));if(n&&(!n.isFile()||n.isSymbolicLink()||n.uid!==t||(n.mode&4095)!=384))throw new Y(`unsafe`)}}}}function jm(e,t){let n=Em(e,()=>{if(km(e),!e.linuxHost&&!X(e.dir))try{m(e.dir,{recursive:!0,mode:448})}catch(e){if(e.code!==`EEXIST`)throw e}Om(e);let t=e.config;e.linuxHost&&(Kp(e),t=N(e.runtimeDir,`config-${ae(`sha256`).update(e.config).digest(`hex`)}`)),Am(t,e.linuxHost?.uid??process.getuid());try{return Pp(t)}catch(t){throw t instanceof Error&&t.message.startsWith(`Control endpoint busy`)?new Tm(`busy`,e.config):t instanceof Error&&t.message.startsWith(`Invalid control guard`)?new Tm(`unsafe`,e.config):t}}),r;try{r=t()}catch(e){try{n()}catch{}throw e}return Em(e,n),r}function Mm(e,t){Em(e,()=>{let n=`${JSON.stringify(Dm(e,t),null,2)}\n`;if(Buffer.byteLength(n)>wm)throw new Tm(`invalid`,e.config);mm(e.config,n,()=>{Om(e),xm(e)})})}function Nm(e,t){return jm(e,()=>{let n=Dm(e,t(xm(e)));return Mm(e,n),n})}function Pm(e){if(e.linuxHost)return um(e);if(pm(e),!s(e.pairings))return[];let t=Yp.safeParse(ym(e.pairings));if(!t.success)throw Error(`shellbell: invalid pairings at ${e.pairings}: ${F.prettifyError(t.error)}`);return t.data.phones}function Fm(e,t){pm(e);let n=new Map(Pm(e).map(e=>[e.phoneFp,e])),r=t.map(e=>Xp(n.get(e.phoneFp),e)),i=Yp.parse({v:1,phones:r}),a=`${JSON.stringify(i,null,2)}\n`;if(e.linuxHost){if(Buffer.byteLength(a)>1048576)throw Error(`shellbell: Linux pairings exceed their state size limit`);em(Buffer.from(a))}return mm(e.pairings,a,e.linuxHost?()=>sm(e):void 0),i.phones}const Im=new Set([`Error`,`TypeError`,`RangeError`,`ReferenceError`,`SyntaxError`,`URIError`,`EvalError`,`AggregateError`,`AbortError`,`TimeoutError`,`ProtocolError`,`BackendUnavailable`,`SessionGone`,`Unsupported`,`BadWindow`,`HerdrError`,`ITerm2AuthError`,`ConfigEditError`,`NativeControllerError`,`ControlV2ClientError`]);function Lm(e){try{if(!(e instanceof Error))return`unknown`;let t=e.name;return typeof t==`string`&&Im.has(t)?t:`Error`}catch{return`unknown`}}function Rm(e){return typeof e==`string`&&(Im.has(e)||e===`unknown`)}function zm(e){let t=e=>Rm(e?.err)?{err:e.err}:void 0,n={debug:()=>{},info:(n,r)=>e.info(n,t(r)),warn:(n,r)=>e.warn(n,t(r)),error:(n,r)=>e.error(n,t(r)),child:()=>n};return n}const Bm=1048576;function Vm(e){return e.isFile()&&e.uid===process.getuid?.()&&e.nlink===1}function Hm(e,t){return e.dev===t.dev&&e.ino===t.ino}function Um(e,t){let n;try{let i;try{i=p(e)}catch(e){if(e.code!==`ENOENT`)return}if(i&&!Vm(i))return;n=h(e,o.O_WRONLY|o.O_APPEND|o.O_NOFOLLOW|o.O_NONBLOCK|(i?0:o.O_CREAT|o.O_EXCL),384);let a=l(n),s=p(e);if(!Vm(a)||!Vm(s)||!Hm(a,s)||i&&!Hm(i,a))return;c(n,384),r(n,t)}catch{}finally{if(n!==void 0)try{a(n)}catch{}}}function Wm(e){let t;try{let n=p(e);if(!Vm(n)||n.size<Bm)return;t=h(e,o.O_RDWR|o.O_NOFOLLOW|o.O_NONBLOCK);let r=l(t);if(!Vm(r)||!Hm(n,r)||r.size<Bm)return;c(t,384);let i=Math.max(0,r.size-Bm),a=Buffer.alloc(r.size-i);for(let e=0;e<a.length;){let n=_(t,a,e,a.length-e,i+e);if(n===0)return;e+=n}for(let t=4;t>=1;t--)s(`${e}.${t}`)&&b(`${e}.${t}`,`${e}.${t+1}`);mm(`${e}.1`,a);let u=p(e);Vm(u)&&Hm(u,r)&&Vm(l(t))&&d(t,0)}catch{}finally{if(t!==void 0)try{a(t)}catch{}}}function Gm(e,t={}){let n=e.stdout??process.stdout.isTTY===!0,r=(r,i,a)=>{if(r===`debug`&&!e.verbose)return;let o={t:new Date().toISOString(),level:r,msg:i,...t,...a};if(e.file){Wm(e.file);try{Um(e.file,`${JSON.stringify(o)}\n`)}catch{}}if(n){let e=Object.keys({...t,...a}).length?` ${JSON.stringify({...t,...a})}`:``,n=`${o.t.slice(11,19)} ${r.padEnd(5)} ${i}${e}`;(r===`error`||r===`warn`?process.stderr:process.stdout).write(`${n}\n`)}};return{debug:(e,t)=>r(`debug`,e,t),info:(e,t)=>r(`info`,e,t),warn:(e,t)=>r(`warn`,e,t),error:(e,t)=>r(`error`,e,t),child:n=>Gm(e,{...t,...n})}}function Km(e){if(!qm(e.reported)||!qm(e.before)||e.before>e.reported||!Number.isSafeInteger(e.count)||e.count<1||e.count>G.historyLines||e.capture===null||typeof e.capture!=`object`)throw RangeError(`invalid history read request`)}function qm(e){return Number.isSafeInteger(e)&&e>=0}var Jm=class extends Error{hint;constructor(e,t){super(e),this.hint=t,this.name=`BackendUnavailable`}},Ym=class extends Error{constructor(e){super(`session gone: ${e}`),this.name=`SessionGone`}},Xm=class extends Error{code;constructor(e){super(`Terminal input ${e}`),this.code=e,this.name=`TerminalInputError`}},Zm=class extends Error{constructor(e){super(`unsupported: ${e}`),this.name=`Unsupported`}},Qm=class extends Error{constructor(e=`No terminal app on this computer can show a new session.`){super(e),this.name=`NotShownOnComputer`}},$m=class extends Error{constructor(e){super(`bad-window: ${e}`),this.name=`BadWindow`}};async function eh(e,t){let n;try{return await Promise.race([Promise.resolve().then(e),new Promise((e,r)=>{n=setTimeout(()=>r(Error(`Terminal adapter deadline exceeded`)),t),n.unref()})])}finally{n&&clearTimeout(n)}}function th(e,t){return`${e}:${t}`}const nh=Su.options,rh=new Set([`iterm2`]);function ih(e){let t=e.indexOf(`:`);if(t<=0)return null;let n=Cu.safeParse(e.slice(0,t));return n.success?{name:n.data,native:e.slice(t+1)}:null}var ah=class{log;listTimeoutMs;conversationPermits=new Map;conversationSupported(e){let t=ih(e),n=t?this.members.get(t.name):void 0;return!!n&&n.isConnected!==!1&&!!n.conversationReference}async conversationReference(e,t){let n=ih(e);if(!n||t.aborted)return null;let r=this.members.get(n.name);if(!r||r.isConnected===!1||!r.conversationReference)return null;let i=this.conversationPermits.get(e);if(i?i.count>=12:this.conversationPermits.size>=20)return null;let a,o=new Promise(e=>{a=e}),s=i??{tail:Promise.resolve(),count:0},c=s.tail;s.tail=c.then(()=>o),s.count++,this.conversationPermits.set(e,s);let l=()=>{};try{if(i){let e=()=>{},n=new Promise(n=>{e=n,t.addEventListener(`abort`,e,{once:!0})});if(await Promise.race([c,n]),t.removeEventListener(`abort`,e),t.aborted)return null}let r=this.members.get(n.name);if(!r||r.isConnected===!1||!r.conversationReference)return null;let a=this.historyMembership.get(n.name),o=!0;l=this.on(t=>{(r.isConnected===!1||(t.type===`session-removed`||t.type===`conversation-changed`)&&t.sessionId===e)&&(o=!1)});let s=await r.conversationReference(n.native,t);return s&&o&&!t.aborted&&this.historyMembership.get(n.name)===a&&this.members.get(n.name)===r&&this.members.get(n.name)?.isConnected!==!1?s:null}catch{return null}finally{l(),a(),--s.count===0&&this.conversationPermits.get(e)===s&&this.conversationPermits.delete(e)}}notificationRevision=0;async notificationFacts(e){let t=ih(e);if(!t)return;let n=this.members.get(t.name);if(!n||n.isConnected===!1)return;let r=this.notificationRevision,i=await n.notificationFacts?.(t.native);if(i&&i.sessionId===t.native&&this.members.get(t.name)===n&&r===this.notificationRevision&&this.connected().some(e=>e.name===t.name))return{...i,sessionId:e,revision:JSON.stringify([r,i.revision])}}members=new Map;labels=new Map;hostCommands=new Map;hostedLaunchers=new Map;hostedPending=0;sessionLaunchers=new Map;setupReporters=new Map;setupListeners=new Set;sessionStartups=new Map;startupWaiters=new Map;unsubs=new Map;historyMembership=new Map;historyPermits=new Map;inputCount=0;inputBytes=0;inputQueues=new Map;handlers=new Set;constructor(e,t=8e3){this.log=e,this.listTimeoutMs=t}orderedNames(){let e=new Set([...this.members.keys(),...this.sessionLaunchers.keys()]);for(let t of nh)e.delete(t);return[...nh,...[...e].sort()]}defaultLabel(e){let t=Su.safeParse(e);return t.success?wu[t.data]:e}catalog(){return this.orderedNames().map(e=>{let t=this.memberConnected(e);return{name:e,label:this.labels.get(e)??this.defaultLabel(e),capabilities:this.members.get(e)?.capabilities??{subscribe:!1,prompts:!1,createSession:!1,focus:!1,history:!1,absoluteLines:!1},connected:t,launchable:!t&&(this.sessionLaunchers.get(e)?.available()??!1)}})}registerHostedLauncher(e,t){let n=Fu.parse(e),r=`${n.backend}:${n.host}`;if(!this.hostedLaunchers.has(r)&&this.hostedLaunchers.size>=64)throw new Jm(`Too many terminal launch targets`,`Disable a launch target first.`);let i={target:n,launcher:t};return this.hostedLaunchers.set(r,i),this.emit({type:`layout-changed`}),()=>{this.hostedLaunchers.get(r)===i&&(this.hostedLaunchers.delete(r),this.emit({type:`layout-changed`}))}}launchTargets(){return[...this.hostedLaunchers.values()].filter(({target:e,launcher:t})=>t.available()&&(this.memberConnected(e.backend)||this.sessionLaunchers.get(e.backend)?.available())).map(({target:e})=>({...e})).sort((e,t)=>`${e.backend}:${e.host}`.localeCompare(`${t.backend}:${t.host}`))}launchIssues(){let e=new Set(this.launchTargets().map(e=>e.backend)),t=new Map;for(let{target:n,launcher:r}of this.hostedLaunchers.values()){if(e.has(n.backend)||t.has(n.backend))continue;let i=r.unavailableReason?.();i&&t.set(n.backend,i)}return Ru.parse([...t].map(([e,t])=>({backend:e,reason:t})))}preferredHost(e){return Wu(e,this.launchTargets())?.host}async requireShownOnComputer(e,t){if(!rh.has(e.name)&&!(e.shownOnComputer&&await eh(()=>e.shownOnComputer(t),5e3)))throw new Qm(`This session is not open in a terminal window on your computer, so it cannot be split or extended from the phone.`)}async createHostedSession(e,t=!1){let n=`${e.backend}:${e.host}`,r=this.hostedLaunchers.get(n);if(e.windowId!==void 0||!r?.launcher.available())throw new Jm(`Terminal launch target is unavailable`,`Check the selected terminal app on your computer.`);if(this.hostedPending>=8)throw new Jm(`Terminal startup is busy`,`Wait for the current startup to finish.`);this.hostedPending++;let i=(async()=>{if(this.hostedLaunchers.get(n)!==r)throw new Ym(n);let i=this.members.get(e.backend),a;if(!i||i.isConnected===!1){let t=await this.startSession(e.backend,e.initialSize);i=t.backend,a=t.sessionId}if(this.hostedLaunchers.get(n)!==r||this.members.get(e.backend)!==i)throw new Ym(n);let o=e.initialSize?await r.launcher.create(i,a,e.initialSize):t?await r.launcher.create(i,a,void 0,{tab:!0}):await r.launcher.create(i,a);if(this.hostedLaunchers.get(n)!==r||this.members.get(e.backend)!==i||i.isConnected===!1)throw new Ym(n);return{sessionId:th(e.backend,o.sessionId),opened:o.opened,openedIn:r.target.label}})().finally(()=>{this.hostedPending--});return eh(()=>i,3e4)}get capabilities(){let e=[...this.members.values()].filter(e=>e.isConnected!==!1).map(e=>e.capabilities),t=t=>e.some(e=>e[t]);return{subscribe:t(`subscribe`),prompts:t(`prompts`),createSession:t(`createSession`)||[...this.sessionLaunchers.values()].some(e=>e.available()),focus:t(`focus`),history:t(`history`),absoluteLines:e.length>0&&e.every(e=>e.absoluteLines)}}add(e,t,n){let r=Nu.parse({name:e.name,label:t??this.defaultLabel(e.name),capabilities:e.capabilities,connected:!1,launchable:!1});if(!this.orderedNames().includes(e.name)&&this.orderedNames().length>=32)throw new Jm(`Too many terminal adapters`,`Disable an adapter before adding another.`);let i={},a=e.on(t=>{this.members.get(e.name)===e&&this.historyMembership.get(e.name)===i&&this.emit(sh(e.name,t))});if(typeof a!=`function`)throw Error(`Terminal adapter subscription is invalid`);let o=this.unsubs.get(e.name);this.labels.set(e.name,r.label),this.hostCommands.set(e.name,n??(e.name===`tmux`||e.name===`herdr`?[e.name]:[])),this.members.set(e.name,e),this.historyMembership.set(e.name,i),this.unsubs.set(e.name,a);try{o?.()}catch(t){this.log.warn(`backend subscription cleanup failed`,{backend:e.name,err:Lm(t)})}this.emit({type:`layout-changed`})}remove(e){let t=this.unsubs.get(e);this.unsubs.delete(e),this.members.delete(e),this.labels.delete(e),this.hostCommands.delete(e),this.historyMembership.delete(e);try{t?.()}catch(t){this.log.warn(`backend subscription cleanup failed`,{backend:e,err:Lm(t)})}this.emit({type:`layout-changed`})}connected(){let e=[];for(let t of this.orderedNames()){let n=this.members.get(t);n&&n.isConnected!==!1&&e.push({name:n.name,capabilities:n.capabilities})}return e}registerSessionLauncher(e,t){if(Cu.parse(e),!this.orderedNames().includes(e)&&this.orderedNames().length>=32)throw new Jm(`Too many terminal adapters`,`Disable an adapter before adding another.`);return this.sessionLaunchers.set(e,t),this.sessionStartups.delete(e),this.emit({type:`layout-changed`}),()=>{this.sessionLaunchers.get(e)===t&&(this.sessionLaunchers.delete(e),this.sessionStartups.delete(e),this.emit({type:`layout-changed`}))}}launchable(){return this.orderedNames().filter(e=>!this.memberConnected(e)&&this.sessionLaunchers.get(e)?.available())}async startSession(e,t){let n=this.sessionLaunchers.get(e);if(!n?.available())throw new Ym(`backend ${e}`);let r=this.startupWaiters.get(e)??0;if(r>=8)throw new Jm(`Terminal startup is busy`,`Try again after the current startup finishes.`);this.startupWaiters.set(e,r+1);try{let r=this.sessionStartups.get(e);if(!r){let i=Promise.resolve().then(()=>{if(this.sessionLaunchers.get(e)!==n)throw new Ym(`backend ${e}`);return t?n.start(t):n.start()}).then(e=>({...e})).finally(()=>{this.sessionStartups.get(e)===i&&this.sessionStartups.delete(e)});r=i,this.sessionStartups.set(e,i)}let i=await r;if(this.sessionLaunchers.get(e)!==n||this.members.get(e)!==i.backend||i.backend.isConnected===!1)throw new Ym(`backend ${e}`);let a=i.sessionId;return i.sessionId=void 0,{backend:i.backend,sessionId:a}}finally{let t=(this.startupWaiters.get(e)??1)-1;t===0?this.startupWaiters.delete(e):this.startupWaiters.set(e,t)}}member(e){return this.members.get(e)}registerSetupReporter(e,t){return this.setupReporters.set(e,t),()=>{this.setupReporters.get(e)===t&&this.setupReporters.delete(e)}}onSetupChanged(e){return this.setupListeners.add(e),()=>this.setupListeners.delete(e)}notifySetupChanged(){for(let e of this.setupListeners)try{e()}catch{}}terminalSetup(){return this.orderedNames().flatMap(e=>{let t=this.setupReporters.get(e),n=this.memberConnected(e);if(!t&&!this.members.has(e))return[];let r={};try{r=t?.(n)??{}}catch{r=n?{}:{issue:`failed`}}return[{name:e,connected:n,...r.issue?{issue:r.issue}:{},...r.issue&&r.detail?{detail:r.detail}:{}}]}).slice(0,16)}connectTerminal(e){let t=this.setupReporters.get(e)?.connect;if(!t)return!1;try{t().catch(e=>this.log.debug(`terminal connect failed`,{error:Lm(e)}))}catch(e){this.log.debug(`terminal connect failed`,{error:Lm(e)})}return!0}status(){return this.orderedNames().map(e=>({name:e,connected:this.memberConnected(e)}))}nameOf(e){return ih(e)?.name??null}capabilitiesOf(e){let t=this.nameOf(e);return t?this.members.get(t)?.capabilities??null:null}async connect(){}async close(){let e=[...this.members.values()],t=[...this.unsubs.values()];this.sessionLaunchers.clear(),this.hostedLaunchers.clear(),this.sessionStartups.clear(),this.historyMembership.clear(),this.unsubs.clear(),this.members.clear(),this.labels.clear(),this.hostCommands.clear();for(let e of t)try{e()}catch(e){this.log.warn(`backend subscription cleanup failed`,{err:Lm(e)})}await Promise.all(e.map(async e=>{try{await eh(()=>e.close(),this.listTimeoutMs)}catch(t){this.log.warn(`backend close failed`,{backend:e.name,err:Lm(t)})}}))}async listSessions(){let e=this.orderedNames().map(e=>({name:e,backend:this.members.get(e),membership:this.historyMembership.get(e)})),t=(await Promise.all(e.map(async e=>({...e,sessions:await this.safeListSessions(e.backend,e.name)})))).filter(({name:e,backend:t,membership:n})=>t&&this.members.get(e)===t&&this.historyMembership.get(e)===n),n=new Set;for(let{name:e,backend:r}of t)try{for(let e of r?.representedWindows?.()??[])n.add(JSON.stringify([e.backend,e.windowId]))}catch(t){this.log.warn(`terminal window relationships unavailable`,{backend:e,err:Lm(t)})}let r=[];for(let{name:e,backend:i,sessions:a}of t)for(let o of a){try{let r=i?.nativeWindowIdOf?.(o.id);if(r&&n.has(JSON.stringify([e,r])))continue;let a=i?.hostedProcess?.(o.id);if(a&&t.some(t=>t.name!==e&&this.memberConnected(t.name)&&this.hostCommands.get(t.name)?.includes(a)))continue}catch(t){this.log.warn(`terminal host relationship unavailable`,{backend:e,err:Lm(t)})}r.push(oh(e,o))}return r}projectFolder(e){let t=ih(e),n=t?this.members.get(t.name):void 0;if(t&&n?.projectFolder)try{return n.projectFolder(t.native)}catch(e){this.log.warn(`session project folder unavailable`,{backend:t.name,err:Lm(e)});return}}memberConnected(e){let t=this.members.get(e);return!!t&&t.isConnected!==!1}async safeListSessions(e,t){if(!e)return[];let n=this.historyMembership.get(t);try{let r=await eh(()=>e.listSessions(),this.listTimeoutMs);return this.members.get(t)!==e||this.historyMembership.get(t)!==n?[]:r}catch(e){return this.log.warn(`listSessions failed for backend; returning the other backends' sessions`,{backend:t,err:Lm(e)}),[]}}target(e){let t=ih(e),n=t?this.members.get(t.name):void 0;if(!t||!n)throw new Ym(e);return{backend:n,native:t.native}}async getScreen(e,t){let{backend:n,native:r}=this.target(e);return t===void 0?n.getScreen(r):n.getScreen(r,t)}async getHistory(e,t,n){let{backend:r,native:i}=this.target(e);return r.getHistory(i,t,n)}async getHistoryPage(e,t){let{backend:n,native:r}=this.target(e);if(Km(t),t.signal.aborted)return{status:`cancelled`};let i=n.getHistoryPage;if(!i)return{status:`unavailable`,reason:`unsupported`};if(this.historyPermits.has(e)||this.historyPermits.size>=10)return{status:`unavailable`,reason:`busy`};let a={};this.historyPermits.set(e,a);let o=this.historyMembership.get(n.name);try{let e=await i.call(n,r,t);return t.signal.aborted?{status:`cancelled`}:this.historyMembership.get(n.name)===o?e:{status:`reset`}}catch(e){if(t.signal.aborted)return{status:`cancelled`};if(this.historyMembership.get(n.name)!==o)return{status:`reset`};throw e}finally{this.historyPermits.get(e)===a&&this.historyPermits.delete(e)}}async sendText(e,t,n,r){let{backend:i,native:a}=this.target(e);return this.enqueueInput(e,i,t,()=>i.sendText(a,t),n,r)}async clickMouse(e,t,n){let{backend:r,native:i}=this.target(e);if(!r.capabilities.mouseClick||!r.clickMouse)throw new Zm(`mouse input`);return this.enqueueInput(e,r,``,()=>r.clickMouse(i,t),n)}async sendInput(e,t,n,r){let{backend:i,native:a}=this.target(e);if(!i.capabilities.terminalInput||!i.sendInput)throw new Zm(`terminal input`);return this.enqueueInput(e,i,t,()=>i.sendInput(a,t),n,r)}openVtStream(e){let{backend:t,native:n}=this.target(e);if(!t.capabilities.vtStream||!t.openVtStream)throw new Zm(`vt stream`);return t.openVtStream(n)}async paste(e,t,n,r,i){let{backend:a,native:o}=this.target(e);if(!a.capabilities.terminalPaste||!a.paste)throw new Zm(`terminal paste`);return this.enqueueInput(e,a,t,()=>a.paste(o,t,n),r,i)}enqueueInput(e,t,n,r,i,a){let o=Buffer.byteLength(n);if(this.inputCount>=256||this.inputBytes+o>1048576)return Promise.reject(new Xm(`busy`));let s=this.inputQueues.get(e);if(s||(s={backend:t,membership:this.historyMembership.get(t.name),tail:Promise.resolve(),pending:0,valid:!0},this.inputQueues.set(e,s)),!s.valid||s.backend!==t)return Promise.reject(new Xm(`cancelled`));let c=s;c.pending++,this.inputCount++,this.inputBytes+=o;let l=()=>this.members.get(t.name)===t&&t.isConnected!==!1&&this.historyMembership.get(t.name)===c.membership,u=()=>{if(!c.valid||i?.()===!1)throw new Xm(`cancelled`);if(!l())throw new Ym(e)},d=c.tail.then(async()=>{u(),a&&(await a(),u()),await r(),c.valid&&l()&&this.emit({type:`input-accepted`,sessionId:e})});return c.tail=d.catch(e=>{(!(e instanceof Xm)||!Qu.safeParse(e.code).success)&&(c.valid=!1)}),d.finally(()=>{this.inputCount--,this.inputBytes-=o,--c.pending===0&&this.inputQueues.get(e)===c&&this.inputQueues.delete(e)})}async createSession(e){let t=e=>({sessionId:e,opened:`tab`});if(e.kind===`split`){let{backend:t,native:n}=this.target(e.sessionId),r={kind:`split`,sessionId:n,direction:e.direction};return await this.requireShownOnComputer(t,r),{sessionId:th(t.name,await t.createSession(r)),opened:`split`}}if(e.explicit===!0||e.initialSize!==void 0){let{near:t,explicit:n,...r}=e;return this.createWindow(r)}if(e.windowId!==void 0){let n=ih(e.windowId);if(!n||n.name!==e.backend)throw new $m(e.windowId);let r=this.members.get(e.backend);if(!r||r.isConnected===!1)throw new Ym(e.windowId);if(rh.has(e.backend))return t(th(r.name,await r.createSession({kind:`tab`,backend:e.backend,windowId:n.native})));let i=await this.createTab(r,n.native,e.host);if(i===void 0)throw new Qm(`That window isn't open on your computer any more, so the tab couldn't open there. Open a new window instead.`);return i}if(e.near===`focused`){let n=this.members.get(e.backend);if(n&&n.isConnected!==!1&&n.focusedWindow){let r=await eh(()=>n.focusedWindow(),5e3).catch(()=>void 0);if(r!==void 0){if(rh.has(e.backend))try{return t(th(n.name,await n.createSession({kind:`tab`,backend:e.backend,windowId:r})))}catch(t){let i=await n.listSessions().catch(()=>null);if(!i||i.some(e=>e.windowId===r))throw t;this.log.warn(`focused window closed before its tab`,{backend:e.backend,err:Lm(t)})}else{let t=await this.createTab(n,r,e.host);if(t!==void 0)return t}}}}let{near:n,explicit:r,...i}=e;return this.createWindow(i,n===`focused`)}async createTab(e,t,n){let r={kind:`tab`,backend:e.name,windowId:t},i=()=>e.shownOnComputer?eh(()=>e.shownOnComputer(r),5e3):Promise.resolve(!1);if(!await i())return;let a=await e.createSession(r);if(await i().catch(()=>!1))return{sessionId:th(e.name,a),opened:`tab`};try{if(!e.discardSession)throw Error(`no discard`);await e.discardSession(a)}catch(t){throw this.log.warn(`unshown tab not closed`,{backend:e.name,err:Lm(t)}),new Qm(`The new tab didn't stay where your computer shows it, and it could not be closed. Check the session list.`)}return this.createWindow({kind:`tab`,backend:e.name,...n!==void 0&&{host:n}})}async createWindow(e,t=!1){if(e.host!==void 0)return this.createHostedSession(e,t);if(!rh.has(e.backend)){let n=this.preferredHost(e.backend);if(n===void 0)throw new Qm;return this.createHostedSession({kind:`tab`,backend:e.backend,host:n,...e.initialSize?{initialSize:e.initialSize}:{}},t)}let n=this.members.get(e.backend);if(!n||n.isConnected===!1){let t=await this.startSession(e.backend,e.initialSize);if(t.sessionId)return{sessionId:th(e.backend,t.sessionId),opened:`window`};n=t.backend}let r=await n.createSession({kind:`tab`,backend:e.backend,windowId:void 0,...e.initialSize?{initialSize:e.initialSize}:{}});return{sessionId:th(n.name,r),opened:`window`}}async focus(e){let{backend:t,native:n}=this.target(e);return t.focus(n)}setWatched(e){let t=new Map;for(let e of this.members.keys())t.set(e,[]);for(let n of e){let e=ih(n);e&&t.get(e.name)?.push(e.native)}for(let[e,n]of t)try{this.members.get(e)?.setWatched?.(n)}catch(t){this.log.warn(`setWatched failed for backend`,{backend:e,err:Lm(t)})}}setReported(e,t){let n=ih(e);if(n)try{this.members.get(n.name)?.setReported?.(n.native,t)}catch(e){this.log.warn(`setReported failed for backend`,{backend:n.name,err:Lm(e)})}}on(e){return this.handlers.add(e),()=>this.handlers.delete(e)}emit(e){if(e.type===`session-removed`){let t=this.inputQueues.get(e.sessionId);t&&(t.valid=!1)}for(let e of this.inputQueues.values())(e.backend.isConnected===!1||this.members.get(e.backend.name)!==e.backend)&&(e.valid=!1);[`layout-changed`,`session-added`,`session-removed`,`title-changed`].includes(e.type)&&this.notificationRevision++;for(let t of[...this.handlers])if(this.handlers.has(t))try{t(e)}catch(e){this.log.error(`backend event handler threw`,{err:Lm(e)})}}};function oh(e,t){return{...t,id:th(e,t.id),windowId:th(e,t.windowId),tabId:th(e,t.tabId),backend:e}}function sh(e,t){return`sessionId`in t?{...t,sessionId:th(e,t.sessionId)}:t}function ch(e,t){let n;try{n=new URL(e)}catch{return`must be a valid URL, e.g. wss://relay.example.com`}return e.endsWith(`/`)||/[?#]/.test(e)||n.pathname!==`/`||n.username||n.password?`relay url must be scheme://host[:port] with no path, query or credentials`:e.length>256?`relay url is too long for a pairing code (at most 256 characters)`:n.protocol===`wss:`?null:n.protocol===`ws:`?t?null:`ws:// is insecure; pass --insecure or set SHELLBELL_ALLOW_INSECURE_RELAY=1 for LAN dev`:`relay url must use wss:// (ws:// only with --insecure, for LAN dev)`}function lh(e,t,n,r){let i;if(t===`relay`){let t=ch(n,r);if(t)return{error:t};i={...e,relayUrl:n}}else if(t===`name`)i={...e,computerName:n};else if(t===`accent`){if(!dm.includes(n))return{error:`unknown accent ${n} (must be one of ${dm.join(`, `)})`};i={...e,accent:n}}else if(t===`turn`){if(n!==`on`&&n!==`off`)return{error:`turn must be on or off`};let{turn:t,...r}=e;i=n===`off`?{...r,turn:!1}:r}else if(t===`conversations`){if(n!==`on`&&n!==`off`)return{error:`conversations must be on or off`};let{showAgentConversations:t,...r}=e;i=n===`off`?{...r,showAgentConversations:!1}:r}else if(fh(t)){if(!/^\d+$/.test(n))return{error:`${t} must be a complete decimal integer`};let r=Number(n);if(!Number.isSafeInteger(r))return{error:`${t} must be a safe decimal integer`};i={...e,[t]:r}}else return{error:`unknown key ${t} (expected ${ph()})`};let a=qp.safeParse(i);return a.success?{next:a.data}:{error:a.error.issues.map(e=>e.message).join(`; `)}}const uh=[`notifyMinCommandMs`,`idleQuietMs`,`idleMinActiveMs`],dh=[`relay`,`name`,`accent`,...uh,`turn`,`conversations`];function fh(e){return uh.includes(e)}function ph(){return`${dh.slice(0,-1).join(`, `)}, or ${dh.at(-1)}`}function mh(e,t){switch(t){case`relay`:return e.relayUrl;case`name`:return e.computerName;case`accent`:return e.accent;case`turn`:return e.turn===!1?`off`:`on`;case`conversations`:return e.showAgentConversations===!1?`off`:`on`;default:return String(e[t])}}function hh(e){let t=qp.parse(e);return ae(`sha256`).update(JSON.stringify({v:t.v,relayUrl:t.relayUrl,computerName:t.computerName,accent:t.accent,notifyMinCommandMs:t.notifyMinCommandMs,idleQuietMs:t.idleQuietMs,idleMinActiveMs:t.idleMinActiveMs,...t.terminalPlugins?.length?{terminalPlugins:t.terminalPlugins}:{},...t.turn===!1?{turn:!1}:{},...t.showAgentConversations===!1?{showAgentConversations:!1}:{}})).digest(`hex`)}const gh={claude:{name:`Claude Code`,from:`2.1.286`,through:`2.1.310`},codex:{name:`Codex`,from:`0.164.0`,through:`0.166.0`},gemini:{name:`Gemini CLI`,from:`0.62.0`,through:`0.62.0`}},_h=/^\d{1,6}(?:\.\d{1,6}){0,3}$/;function vh(e){return typeof e==`string`&&_h.test(e)?e:null}function yh(e,t){let n=e.split(`.`).map(Number),r=t.split(`.`).map(Number);for(let e=0;e<Math.max(n.length,r.length);e++){let t=(n[e]??0)-(r[e]??0);if(t)return Math.sign(t)}return 0}function bh(e,t){if(!Object.hasOwn(gh,e))return`tested`;let n=gh[e];return yh(t,n.through)>0?`newer`:yh(t,n.from)<0?`older`:`tested`}const xh=new Map;function Sh(){return[...xh.values()].map(e=>({...e}))}function Ch(e,t,n){if(bh(e,t)!==`newer`)return;let r=`${e}@${t}`;if(xh.has(r)||xh.size>=16)return;let i=gh[e].name;xh.set(r,{agent:e,name:i,version:t}),n(`agent-version-newer-than-tested`,{agent:e,version:t,tested:gh[e].through})}const wh=F.object({name:Cu,connected:F.boolean()}),Th=F.array(wh).max(32),Eh=F.object({pid:F.number().int().positive().max(2**53-1),agentVersion:F.string().min(1),computerFp:W,stateDir:F.string().min(1).refine(M,`state directory must be absolute`),serviceInstance:F.uuid().nullable()}),Dh=F.strictObject({agent:F.string().min(1).max(32),name:F.string().min(1).max(64),version:F.string().regex(_h)}),Oh=F.array(Dh).max(16),kh={controlVersion:F.literal(1),process:Eh,backends:Th,terminalReady:F.boolean(),newerAgents:Oh.optional()};function Ah(e,t){(e.backends.length<nh.length||nh.some((t,n)=>e.backends[n]?.name!==t)||new Set(e.backends.map(e=>e.name)).size!==e.backends.length||e.backends.slice(nh.length).some((e,t,n)=>t>0&&e.name<n[t-1].name))&&t.addIssue({code:`custom`,path:[`backends`],message:`backend status must contain each known backend in protocol order`}),e.terminalReady!==e.backends.some(e=>e.connected)&&t.addIssue({code:`custom`,path:[`terminalReady`],message:`terminal readiness must match backend connectivity`})}const jh=F.string().min(1).max(64),Mh=F.object({route:F.enum([`relay`,`direct`]).nullable(),ready:F.boolean(),phase:F.string().max(32),lastFailure:F.string().max(32).nullable(),relaySent:F.number().int().nonnegative(),relayReceived:F.number().int().nonnegative(),directSent:F.number().int().nonnegative(),directReceived:F.number().int().nonnegative()}),Nh=F.object({...kh,relayOnline:F.boolean(),sessions:F.number().int().nonnegative().max(2**53-1),phones:F.array(F.object({phoneFp:W,name:jh,lastSeenAt:F.string().nullable()})).max(10),connected:F.array(F.object({phoneFp:W,name:jh,viewed:F.string().nullable(),transport:Mh.optional()})).max(10)}).superRefine(Ah);function Ph(e,t=process.env){if(!e)return null;let n=t.SHELLBELL_SERVICE_INSTANCE;if(n===void 0)return null;if(!F.uuid().safeParse(n).success)throw Error(`SHELLBELL_SERVICE_INSTANCE must be a valid UUID`);return n}const Fh=(t,n,r)=>new Promise((i,a)=>{let o=e(t,n,{shell:!1,stdio:[`pipe`,`pipe`,`pipe`]}),s=0,c=0,l=[],u=!1,d=e=>{u||(u=!0,clearTimeout(f),o.kill(),a(e))},f=setTimeout(()=>d(Error(`${t} timed out`)),r.timeoutMs);o.stdout.on(`data`,e=>{if(s+=e.length,s>r.maxOutputBytes)return d(Error(`${t} output limit exceeded`));r.captureOutput&&l.push(e)}),o.stderr.on(`data`,e=>{c+=e.length,c>r.maxOutputBytes&&d(Error(`${t} output limit exceeded`))}),o.on(`error`,d),o.on(`close`,(e,n)=>{if(!u){if(u=!0,clearTimeout(f),n||e===null)return a(Error(`${t} terminated by signal`));i({exitCode:e,stdout:r.captureOutput?Buffer.concat(l):Buffer.alloc(0)})}}),o.stdin.on(`error`,d),o.stdin.end(r.input)});function Ih(e){try{return t.lstatSync(e)}catch(e){if(e.code===`ENOENT`)return;throw e}}function Lh(e,t){return e?.dev===t.dev&&e.ino===t.ino}function Rh(e){let t=process.platform===`darwin`?103:process.platform===`linux`?107:null;if(t===null)throw Error(`Unsupported control socket platform: ${process.platform}`);if(Buffer.byteLength(e)>t)throw Error(`Control socket path is too long (maximum ${t} bytes): ${e}`)}async function zh(e){return new Promise((t,n)=>{let r=le(e),i=setTimeout(()=>a(Error(`Control socket probe timed out: ${e}`)),1e3),a=(e,a=!1)=>{clearTimeout(i),r.destroy(),e?n(e):t(a)};r.once(`connect`,()=>a(void 0,!0)),r.once(`error`,e=>{e.code===`ENOENT`||e.code===`ECONNREFUSED`?a():a(e)})})}var Bh=class{sockPath;onConnection;log;pidPath;admit;server;clients=new Set;ownedSocket;ownedPid;lifecycle=Promise.resolve();constructor(e,t,n,r,i){this.sockPath=e,this.onConnection=t,this.log=n,this.pidPath=r,this.admit=i}serialize(e){let t=this.lifecycle.then(e);return this.lifecycle=t.catch(()=>{}),t}start(){return this.serialize(async()=>{if(this.server)return;if(this.ownedSocket||this.ownedPid)throw Error(`Control endpoint cleanup pending; stop it before restarting`);Rh(this.sockPath),Rh(N(j(this.sockPath),`.s12345678`));let e=Pp(this.sockPath);try{this.admit?.(),this.checkPid();let e=Ih(this.sockPath);if(e){if(!e.isSocket())throw Error(`Control socket path is not a socket: ${this.sockPath}`);if(await zh(this.sockPath))throw Error(`Control endpoint already running: ${this.sockPath}`);if(!Lh(Ih(this.sockPath),e))throw Error(`Control socket changed during startup; retry`);t.unlinkSync(this.sockPath);for(let n of t.readdirSync(j(this.sockPath))){if(!/^\.s[A-Za-z0-9_-]{8}$/.test(n))continue;let r=N(j(this.sockPath),n);Lh(Ih(r),e)&&t.unlinkSync(r)}}let n=await this.bind();t.chmodSync(n,384);let r=t.lstatSync(n);if(t.linkSync(n,this.sockPath),this.ownedSocket=r,this.pidPath){this.checkPid();let e=String(process.pid);mm(this.pidPath,e),this.ownedPid={identity:t.lstatSync(this.pidPath),contents:e}}this.admit?.()}catch(e){try{this.removeOwned()}finally{await this.closeListener()}throw e}finally{e()}})}checkPid(){if(!this.pidPath)return;let e=Ih(this.pidPath);if(!e)return;if(!e.isFile())throw Error(`PID path must be a regular file: ${this.pidPath}`);let n=Ap(t.readFileSync(this.pidPath,`utf8`).trim());if(n===null)throw Error(`Invalid PID file; inspect ${this.pidPath} before retrying`);if(jp(n))throw Error(`shellbell is already running (pid ${n})`)}async bind(){for(let e=0;e<8;e++){let e=N(j(this.sockPath),`.s${se(6).toString(`base64url`)}`),t=ue(e=>{this.clients.add(e),e.once(`close`,()=>this.clients.delete(e)),e.on(`error`,()=>{}),this.onConnection(e)});this.server=t;try{return await new Promise((n,r)=>{t.once(`error`,r);let i=process.umask(127);try{t.listen(e,()=>{t.removeListener(`error`,r),n()})}finally{process.umask(i)}}),e}catch(e){if(await this.closeListener(),e.code!==`EADDRINUSE`)throw e}}throw Error(`Control endpoint private socket names are in use after eight attempts`)}removeOwned(){if(this.ownedSocket&&=(Lh(Ih(this.sockPath),this.ownedSocket)&&t.unlinkSync(this.sockPath),void 0),this.pidPath&&this.ownedPid){let e=Ih(this.pidPath);e?.isFile()&&Lh(e,this.ownedPid.identity)&&t.readFileSync(this.pidPath,`utf8`)===this.ownedPid.contents&&t.unlinkSync(this.pidPath),this.ownedPid=void 0}}async closeListener(){for(let e of this.clients)e.destroy();this.clients.clear();let e=this.server;this.server=void 0,e&&await new Promise((t,n)=>e.close(e=>{e&&e.code!==`ERR_SERVER_NOT_RUNNING`?n(e):t()}))}stop(){return this.serialize(async()=>{let e;try{(this.ownedSocket||this.ownedPid)&&(e=Pp(this.sockPath),this.removeOwned())}catch(e){throw this.log.warn(`Control endpoint cleanup failed; shared paths retained for retry`,{error:Lm(e)}),e}finally{try{await this.closeListener()}finally{e?.()}}})}};const Vh={lineBytes:65536,queuedBytes:262144,connections:16,initialRequestMs:5e3,requestMs:5e3,challengeMs:6e4};function Hh(e){let t;try{t=JSON.stringify(e)}catch{return null}if(t===void 0)return null;let n=new TextEncoder().encode(`${t}\n`);return n.byteLength-1<=Vh.lineBytes?n:null}function Uh(e,t){let n=e.writableLength;if(e.destroyed||!Number.isFinite(n)||n<0||n+t.byteLength>Vh.queuedBytes)return e.destroy(),!1;try{return e.write(t),!0}catch{return e.destroy(),!1}}var Wh=class{onLine;onError;maxBytes;chunks=[];bytes=0;terminal=!1;constructor(e){this.onLine=e.onLine,this.onError=e.onError;let t=e.maxBytes??Vh.lineBytes;this.maxBytes=Number.isFinite(t)?Math.max(0,Math.min(t,Vh.lineBytes)):Vh.lineBytes}push(e){if(this.terminal||e.byteLength===0)return;let t=0;for(;t<e.byteLength&&!this.terminal;){let n=e.indexOf(10,t),r=n===-1?e.byteLength:n,i=r-t;if(this.bytes+i>this.maxBytes){this.fail(`line-too-large`);return}if(i>0&&(this.chunks.push(Uint8Array.from(e.subarray(t,r))),this.bytes+=i),n===-1)return;let a=this.decodeLine();if(a===null)return;this.reset(),this.onLine(a),t=n+1}}finish(){this.terminal||(this.bytes>0?this.fail(`incomplete-line`):(this.terminal=!0,this.reset()))}decodeLine(){let e=new Uint8Array(this.bytes),t=0;for(let n of this.chunks)e.set(n,t),t+=n.byteLength;try{return new TextDecoder(`utf-8`,{fatal:!0,ignoreBOM:!0}).decode(e)}catch{return this.fail(`invalid-utf8`),null}}fail(e){this.terminal||(this.terminal=!0,this.reset(),this.onError(e))}reset(){this.chunks=[],this.bytes=0}};const Gh=F.number().int().positive().max(2**53-1),Kh=F.string().regex(/^[A-Za-z0-9_-]{22}$/),qh=F.string().min(1).max(64),Jh=F.object({pid:Gh,agentVersion:F.string().min(1),computerFp:W,stateDir:F.string().min(1).refine(M,`state directory must be absolute`),serviceInstance:F.uuid().nullable()}).strict(),Yh=F.object({name:Cu,connected:F.boolean()}).strict(),Xh=F.object({phoneFp:W,name:qh,lastSeenAt:F.string().nullable()}).strict(),Zh=F.object({phoneFp:W,name:qh,viewed:F.string().nullable(),transport:Mh.strict().optional()}).strict(),Qh=F.object({controlVersion:F.literal(1),process:Jh,backends:F.array(Yh),terminalReady:F.boolean(),relayOnline:F.boolean(),sessions:F.number().int().nonnegative().max(2**53-1),phones:F.array(Xh).max(10),connected:F.array(Zh).max(10),newerAgents:Oh.optional()}).strict().superRefine((e,t)=>{Nh.safeParse(e).success||t.addIssue({code:`custom`,message:`status must satisfy LocalStatus semantics`})}),$h=F.object({}).strict(),eg=F.object({version:F.literal(2),runtime:Jh,capabilities:F.tuple([F.literal(`status`),F.literal(`devices`),F.literal(`pairing`),F.literal(`revoke`)])}).strict(),tg=F.array(Xh).max(10),ng=F.object({removed:F.boolean()}).strict(),rg=F.object({flowId:Kh,qrText:F.string().min(1).refine(e=>new TextEncoder().encode(e).byteLength<=Vh.lineBytes),expiresAt:Gh}).strict(),ig={hello:eg,status:Qh,"status.config":F.object({revision:F.string().regex(/^[0-9a-f]{64}$/)}).strict(),"settings.conversations.apply":F.object({revision:F.string().regex(/^[0-9a-f]{64}$/)}).strict(),devices:tg,"devices.revoke":ng,"pairing.open":rg,"pairing.close":$h,"pairing.confirm":$h,terminals:F.object({terminals:Vu}).strict(),"terminals.connect":F.object({started:F.boolean(),terminals:Vu}).strict()},ag={v:F.literal(2),id:Gh},og={...ag,expect:Jh},sg=F.discriminatedUnion(`cmd`,[F.object({...og,cmd:F.literal(`settings.conversations.apply`),args:F.object({revision:F.string().regex(/^[0-9a-f]{64}$/)}).strict()}).strict(),F.object({...ag,cmd:F.literal(`hello`)}).strict(),F.object({...ag,cmd:F.literal(`status`)}).strict(),F.object({...ag,cmd:F.literal(`status.config`)}).strict(),F.object({...ag,cmd:F.literal(`devices`)}).strict(),F.object({...ag,cmd:F.literal(`terminals`)}).strict(),F.object({...og,cmd:F.literal(`terminals.connect`),args:F.object({name:Cu}).strict()}).strict(),F.object({...og,cmd:F.literal(`devices.revoke`),args:F.object({phoneFp:W}).strict()}).strict(),F.object({...og,cmd:F.literal(`pairing.open`)}).strict(),F.object({...og,cmd:F.literal(`pairing.close`),args:F.object({flowId:Kh}).strict()}).strict(),F.object({...og,cmd:F.literal(`pairing.confirm`),args:F.object({flowId:Kh,challengeId:Kh,phoneFp:W,accept:F.boolean()}).strict()}).strict()]),cg=F.enum([`bad-request`,`unsupported-version`,`handshake-required`,`runtime-mismatch`,`configuration-mismatch`,`pairing-busy`,`stale-flow`,`stale-challenge`,`response-too-large`,`operation-failed`]),lg=F.object({v:F.literal(2),id:Gh,ok:F.literal(!0),data:F.unknown()}).strict().refine(e=>Object.hasOwn(e,`data`)),ug=F.object({v:F.literal(2),id:Gh,ok:F.literal(!1),error:F.object({code:cg}).strict()}).strict(),dg=F.union([lg,ug]),fg=F.object({v:F.literal(2),event:F.literal(`pairing.request`),flowId:Kh,challengeId:Kh,phoneFp:W,name:qh}).strict(),pg=F.object({v:F.literal(2),event:F.literal(`pairing.closed`),flowId:Kh}).strict(),mg=F.discriminatedUnion(`event`,[fg,pg]),hg=[`status`,`devices`,`pairing`,`revoke`];function gg(e,t){return e.pid===t.pid&&e.agentVersion===t.agentVersion&&e.computerFp===t.computerFp&&e.stateDir===t.stateDir&&e.serviceInstance===t.serviceInstance}function _g(e){if(!e||typeof e!=`object`)return;let t=e.id;return typeof t==`number`&&Number.isSafeInteger(t)&&t>0?t:void 0}var vg=class{agent;log;peers=new Set;owner;stopped=!1;newId;constructor(e,t,n){this.agent=e,this.log=t,this.newId=n?.newId??(()=>se(16).toString(`base64url`))}get hasPairOwner(){return this.owner!==void 0}accept(e){let t=new yg(this,e,this.agent);return this.stopped?t.close():this.peers.add(t),t}confirm(e,t){let n=this.owner;if(!n||n.resolve||this.stopped)return Promise.resolve(!1);let r=this.newId();return new Promise(i=>{if(this.owner!==n)return i(!1);n.resolve=i,n.challengeId=r,n.phoneFp=e,n.name=t,n.opening||this.emitRequest(n,t)})}activate(e,t){let n=this.owner;n&&n.peer===e&&n.flowId===t&&(n.opening=!1,n.resolve&&n.phoneFp&&n.challengeId&&this.emitRequest(n,n.name??``))}emitRequest(e,t){if(!e.resolve||!e.challengeId||!e.phoneFp)return;let n=e.resolve,r=Math.max(0,(e.expiresAt??Date.now())-Date.now());e.timer=setTimeout(()=>{this.owner===e&&e.resolve===n&&(e.resolve=void 0,e.challengeId=void 0,e.phoneFp=void 0,n(!1))},Math.min(Vh.challengeMs,r)),e.timer.unref(),e.peer.event({v:2,event:`pairing.request`,flowId:e.flowId,challengeId:e.challengeId,phoneFp:e.phoneFp,name:t})||this.clearOwner(e,!1,!0)}notifyClosed(){let e=this.owner;e&&(this.clearOwner(e,!1,!1),e.peer.event({v:2,event:`pairing.closed`,flowId:e.flowId}))}stop(){this.stopped=!0;let e=this.owner;e&&this.clearOwner(e,!0,!1);for(let e of this.peers)e.close();this.peers.clear()}removed(e){this.peers.delete(e);let t=this.owner;t?.peer===e&&this.clearOwner(t,!0,!1)}open(e){if(this.owner||this.agent.pairingOpen)return`pairing-busy`;try{let t=this.newId(),n={peer:e,flowId:t,opening:!0};this.owner=n;let r=this.agent.openPairing();return this.owner!==n||!this.agent.pairingOpen?(this.clearOwner(n,!0,!1),`operation-failed`):(n.expiresAt=r.expiresAt,{flowId:t,...r})}catch{let t=this.owner;return t?.peer===e&&this.clearOwner(t,!0,!1),`operation-failed`}}close(e,t){let n=this.owner;if(!n||n.peer!==e||n.flowId!==t)return`stale-flow`;this.clearOwner(n,!0,!1)}answer(e,t){let n=this.owner;if(!n||n.peer!==e||n.flowId!==t.args.flowId)return`stale-flow`;if(n.expiresAt===void 0||Date.now()>=n.expiresAt)return this.clearOwner(n,!0,!0),`stale-flow`;if(!n.resolve||n.challengeId!==t.args.challengeId||n.phoneFp!==t.args.phoneFp)return`stale-challenge`;let r=n.resolve;n.timer&&clearTimeout(n.timer),n.timer=void 0,n.resolve=void 0,n.challengeId=void 0,n.phoneFp=void 0,n.name=void 0,r(t.args.accept)}clearOwner(e,t,n){if(this.owner!==e)return;this.owner=void 0;let r=e.resolve;if(e.timer&&clearTimeout(e.timer),e.timer=void 0,e.resolve=void 0,e.challengeId=void 0,e.phoneFp=void 0,e.name=void 0,r?.(!1),t)try{this.agent.closePairing()}catch{this.log.warn(`native pairing close failed`)}n&&e.peer.event({v:2,event:`pairing.closed`,flowId:e.flowId})}},yg=class{hub;socket;agent;helloRuntime;lastId=0;closed=!1;constructor(e,t,n){this.hub=e,this.socket=t,this.agent=n}get handshaken(){return this.helloRuntime!==void 0}close(){this.closed||(this.closed=!0,this.hub.removed(this),this.socket.destroy())}handle(e){if(this.closed||this.socket.destroyed)return;let t=_g(e);if(this.handshaken&&t!==void 0){if(t<=this.lastId){this.close();return}this.lastId=t}if(e&&typeof e==`object`&&e.v!==2){t!==void 0&&this.failure(t,`unsupported-version`),this.close();return}let n=sg.safeParse(e);if(!n.success){t===void 0?this.close():this.failure(t,`bad-request`);return}let r=n.data;if(!this.handshaken){if(r.id!==1||r.cmd!==`hello`){this.close();return}this.lastId=1,this.helloRuntime={...this.runtime()},this.success(r,{version:2,runtime:this.helloRuntime,capabilities:hg});return}if(r.cmd===`hello`){this.close();return}let i=this.helloRuntime,a=this.runtime();if(`expect`in r&&(!i||!gg(r.expect,i)||!gg(r.expect,a))){this.failure(r.id,`runtime-mismatch`);return}switch(r.cmd){case`status`:this.success(r,this.status());return;case`status.config`:this.success(r,{revision:this.agent.configurationRevision});return;case`settings.conversations.apply`:try{let e=this.agent.applyConversationSetting(r.args.revision);e===null?this.failure(r.id,`configuration-mismatch`):this.success(r,{revision:e})}catch{this.failure(r.id,`operation-failed`)}return;case`devices`:this.success(r,this.devices());return;case`devices.revoke`:try{this.success(r,{removed:this.agent.unpairExact(r.args.phoneFp)})}catch{this.failure(r.id,`operation-failed`)}return;case`terminals`:this.success(r,{terminals:this.agent.terminalSetup()});return;case`terminals.connect`:{let e=this.agent.connectTerminal(r.args.name);this.success(r,{started:e,terminals:this.agent.terminalSetup()});return}case`pairing.open`:{let e=this.hub.open(this);typeof e==`string`?this.failure(r.id,e):this.success(r,e)?this.hub.activate(this,e.flowId):this.hub.close(this,e.flowId);return}case`pairing.close`:{let e=this.hub.close(this,r.args.flowId);e?this.failure(r.id,e):this.success(r,{})&&this.event({v:2,event:`pairing.closed`,flowId:r.args.flowId});return}case`pairing.confirm`:{let e=this.hub.answer(this,r);e?this.failure(r.id,e):this.success(r,{});return}}}event(e){return mg.safeParse(e).success?this.write(e):!1}runtime(){return this.agent.localStatus.process}status(){let e=this.agent;return{...e.localStatus,relayOnline:e.relayOnline,sessions:e.sessionList.length,phones:this.devices(),connected:e.connectedPhones}}devices(){return this.agent.pairingList.map(e=>({phoneFp:e.phoneFp,name:e.name,lastSeenAt:e.lastSeenAt}))}success(e,t){if(!ig[e.cmd].safeParse(t).success)return this.failure(e.id,`operation-failed`),!1;let n={v:2,id:e.id,ok:!0,data:t};if(!dg.safeParse(n).success)return this.failure(e.id,`operation-failed`),!1;let r=Hh(n);return r?this.writeFrame(r):(this.failure(e.id,`response-too-large`),!1)}failure(e,t){let n={v:2,id:e,ok:!1,error:{code:t}};return dg.safeParse(n).success?this.write(n):!1}write(e){let t=Hh(e);return t?this.writeFrame(t):!1}writeFrame(e){return Uh(this.socket,e)?!0:(this.close(),!1)}};const bg={unavailable:`Local control unavailable`,"upgrade-required":`Local control upgrade required`,"protocol-error":`Local control protocol error`,timeout:`Local control timed out`,"delivery-unknown":`Local control mutation outcome unknown`,busy:`Local control request already pending`,closed:`Local control closed`,"server-error":`Local control server rejected request`},xg=new Set([`hello`,`status`,`status.config`,`devices`,`terminals`]);var Q=class extends Error{code;serverCode;constructor(e,t){super(bg[e]),this.code=e,this.serverCode=t,this.name=`ControlV2ClientError`}};function Sg(e,t={}){return new Promise((n,r)=>{let i;try{i=(t.connector??le)(e)}catch{r(new Q(`unavailable`));return}let a=!1,o=!1,s=!1,c=0,l,u,d,f=setTimeout(()=>p(new Q(`timeout`)),Vh.requestMs);function p(e){if(a)return;a=!0,clearTimeout(f);let n=l;l=void 0,d=void 0,n&&(clearTimeout(n.timer),n.reject(n.mutation&&n.attempted?new Q(`delivery-unknown`):e)),o||r(e),i.destroy(),t.onDisconnect?.(e)}function m(e,t){if(a)return Promise.reject(new Q(`closed`));if(l)return Promise.reject(new Q(`busy`));if(c===2**53-1)return p(new Q(`protocol-error`)),Promise.reject(new Q(`protocol-error`));let n=!xg.has(e),r=sg.safeParse({v:2,id:c+1,cmd:e,...n?{expect:u}:{},...t===void 0?{}:{args:t}});if(!r.success)return Promise.reject(new Q(`protocol-error`));let o=Hh(r.data);if(o===null)return Promise.reject(new Q(`protocol-error`));let s=i.writableLength;return i.destroyed||!Number.isFinite(s)||s<0||s+o.byteLength>Vh.queuedBytes?(p(new Q(`unavailable`)),Promise.reject(new Q(`unavailable`))):(c++,new Promise((t,r)=>{let a={id:c,command:e,mutation:n,attempted:!1,resolve:e=>t(e),reject:r,timer:setTimeout(()=>p(new Q(`timeout`)),Vh.requestMs)};l=a,a.attempted=!0,Uh(i,o)||p(new Q(`unavailable`))}))}let h=new Wh({onError:()=>p(new Q(`protocol-error`)),onLine:e=>{if(a)return;let n;try{n=JSON.parse(e)}catch{p(new Q(`protocol-error`));return}if(typeof n==`object`&&n&&`event`in n){let e=mg.safeParse(n);if(!e.success){p(new Q(`protocol-error`));return}let r=e.data;if(r.event===`pairing.closed`&&r.flowId!==d)return;if(r.flowId!==d){p(new Q(`protocol-error`));return}r.event===`pairing.closed`?(d=void 0,t.onPairingClosed?.(r)):t.onPairingRequest?.(r);return}let r=l;if(r?.command===`hello`&&typeof n==`object`&&n&&!(`v`in n)&&`ok`in n&&typeof n.ok==`boolean`){p(new Q(`upgrade-required`));return}let i=dg.safeParse(n);if(!i.success||!r||i.data.id!==r.id){p(new Q(`protocol-error`));return}if(!i.data.ok){clearTimeout(r.timer),l=void 0;let e=new Q(`server-error`,i.data.error.code);r.reject(e),r.command===`hello`&&p(e);return}let o=ig[r.command].safeParse(i.data.data);if(!o.success){p(new Q(`protocol-error`));return}r.command===`pairing.open`&&(d=o.data.flowId),clearTimeout(r.timer),l=void 0,r.resolve(o.data)}});i.on(`data`,e=>h.push(e)),i.on(`error`,()=>p(new Q(`unavailable`)));let g=()=>{h.finish(),p(new Q(`unavailable`))};i.once(`end`,g),i.once(`close`,g);let _=()=>{a||s||(s=!0,clearTimeout(f),m(`hello`).then(e=>{a||(u={...e.runtime},o=!0,n({runtime:{...e.runtime},status:()=>m(`status`),applyConversationSetting:async e=>{try{return(await m(`settings.conversations.apply`,{revision:e})).revision}catch(e){if(e instanceof Q&&e.code===`server-error`&&e.serverCode===`bad-request`)return null;throw e}},configurationRevision:async()=>{try{return(await m(`status.config`)).revision}catch(e){if(e instanceof Q&&e.code===`server-error`&&e.serverCode===`bad-request`)return null;throw e}},devices:()=>m(`devices`),terminals:async()=>{try{return(await m(`terminals`)).terminals}catch(e){if(Cg(e))return null;throw e}},connectTerminal:async e=>{try{return await m(`terminals.connect`,{name:e})}catch(e){if(Cg(e))return null;throw e}},revoke:e=>m(`devices.revoke`,{phoneFp:e}),openPairing:()=>m(`pairing.open`),closePairing:async e=>{await m(`pairing.close`,{flowId:e})},confirm:async(e,t,n,r)=>{await m(`pairing.confirm`,{flowId:e,challengeId:t,phoneFp:n,accept:r})},close:()=>p(new Q(`closed`))}))},e=>p(e)))};i.once(`connect`,_),i.connecting||_()})}function Cg(e){return e instanceof Q&&e.code===`server-error`&&e.serverCode===`bad-request`}var wg=class{agent;log;admission;pairingMode;endpoint;pending=new Map;pairClients=new Set;controlSockets=new Set;v2;pairingConfirm=(e,t)=>new Promise(n=>{if(this.pending.has(e)){this.log.warn(`pairing confirm requested twice for the same phone; declining the newer one`,{phone:e.slice(0,8)}),n(!1);return}let r=setTimeout(()=>{this.pending.delete(e),n(!1)},6e4);this.pending.set(e,t=>{clearTimeout(r),this.pending.delete(e),n(t)});for(let n of this.pairClients)this.writeLegacy(n,{event:`request`,phoneFp:e,name:t})||this.pairClients.delete(n)});constructor(e,t,n,r,i,a,o=`terminal`){this.agent=t,this.log=n,this.admission=a,this.pairingMode=o,this.endpoint=new Bh(e,e=>this.handle(e),n,r,i),this.v2=new vg(t,n)}get hasPairClients(){return this.pairClients.size>0}get hasNativePairOwner(){return this.v2.hasPairOwner}nativePairingConfirm=(e,t)=>this.v2.confirm(e,t);notifyClosed(e=`closed`){for(let e of this.pending.values())e(!1);this.pending.clear();for(let t of this.pairClients)this.writeLegacy(t,{event:`closed`,reason:e})||this.pairClients.delete(t);this.pairClients.clear(),this.v2.notifyClosed()}async start(){this.admission?await this.admission(()=>this.endpoint.start()):await this.endpoint.start()}async stop(){for(let e of this.pending.values())e(!1);for(let e of this.controlSockets)e.destroy();this.controlSockets.clear();for(let e of this.pairClients)e.destroy();this.pairClients.clear(),this.v2.stop(),await this.endpoint.stop()}handle(e){if(this.controlSockets.size>=Vh.connections){e.destroy();return}this.controlSockets.add(e);let t=!0,n,r,i=setTimeout(()=>e.destroy(),Vh.initialRequestMs),a=new Wh({onLine:a=>{if(e.destroyed)return;let o;try{o=JSON.parse(a)}catch{if(n===`v2`){e.destroy();return}this.writeLegacy(e,{ok:!1,error:`bad json`});return}if(n===`v2`){r?.handle(o),t&&r?.handshaken&&(t=!1,clearTimeout(i));return}if(n===void 0&&o&&typeof o==`object`&&Object.hasOwn(o,`v`)){n=`v2`,r=this.v2.accept(e),r.handle(o),r.handshaken&&(t=!1,clearTimeout(i));return}if(n===`legacy`&&o&&typeof o==`object`&&Object.hasOwn(o,`v`)){e.destroy();return}n=`legacy`;let s=o;if(!s||typeof s!=`object`||typeof s.cmd!=`string`){this.writeLegacy(e,{ok:!1,error:`bad request`});return}t&&(t=!1,clearTimeout(i));try{let t=this.dispatch(s,e);this.writeLegacy(e,{ok:!0,data:t})}catch(t){this.writeLegacy(e,{ok:!1,error:t.message})}},onError:()=>e.destroy()});e.on(`data`,e=>a.push(new Uint8Array(e))),e.once(`end`,()=>a.finish()),e.once(`close`,()=>{clearTimeout(i),this.controlSockets.delete(e),this.pairClients.delete(e),r?.close()}),e.on(`error`,()=>this.log.debug(`control socket error`))}writeLegacy(e,t){let n=Hh(t);if(n&&Uh(e,n))return!0;let r=Hh({ok:!1,error:`response too large`});return r!==null&&Uh(e,r)}dispatch(e,t){let n=this.agent;if(this.pairingMode===`native`&&[`pair-open`,`pair-close`,`confirm`].includes(e.cmd))throw Error(`pairing is managed by the Shellbell app`);if(this.v2.hasPairOwner&&[`pair-open`,`pair-close`,`confirm`].includes(e.cmd))throw Error(`native pairing active`);switch(e.cmd){case`status`:return{...n.localStatus,relayOnline:n.relayOnline,sessions:n.sessionList.length,phones:n.pairingList.map(e=>({phoneFp:e.phoneFp,name:e.name,lastSeenAt:e.lastSeenAt})),connected:n.connectedPhones};case`devices`:return n.pairingList.map(e=>({phoneFp:e.phoneFp,name:e.name,lastSeenAt:e.lastSeenAt}));case`unpair`:return{removed:n.unpair(String(e.args?.target??``))};case`pair-open`:{let e=n.openPairing();return this.pairClients.add(t),e}case`pair-close`:return n.closePairing(),{};case`confirm`:{let t=String(e.args?.phoneFp??``),n=this.pending.get(t);if(!n)throw Error(`no pending request`);return n(!!e.args?.accept),{}}default:throw Error(`unknown command: ${e.cmd}`)}}};function Tg(e,t,n,r){return new Promise((i,a)=>{let o=Hh({cmd:t,args:n});if(!o){a(Error(`control socket request too large`));return}let s=!1,c=le(e),l=r?.timeoutMs??5e3,u=e=>{s||(s=!0,clearTimeout(d),c.destroy(),e())},d=setTimeout(()=>u(()=>a(Error(`control socket timed out`))),l),f=new Wh({maxBytes:r?.maxResponseBytes,onError:e=>u(()=>a(Error(e===`line-too-large`?`control socket response too large`:`control socket sent a malformed response`))),onLine:e=>{f.finish(),u(()=>{let t;try{if(t=JSON.parse(e),typeof t!=`object`||!t||typeof t.ok!=`boolean`)throw Error()}catch{a(Error(`control socket sent a malformed response`));return}t.ok?i(t.data):a(Error(t.error??`control error`))})}});c.on(`error`,e=>u(()=>a(e))),c.once(`connect`,()=>{Uh(c,o)||u(()=>a(Error(`control socket write failed`)))}),c.once(`close`,()=>u(()=>a(Error(`control socket closed without a response`)))),c.once(`end`,()=>u(()=>a(Error(`control socket closed without a response`)))),c.on(`data`,e=>{s||f.push(new Uint8Array(e))}),c.once(`end`,()=>f.finish())})}function Eg(e,t){let n=le(e),r=!1,i,a=()=>{r||(r=!0,i?.finish(),n.end())};n.on(`error`,t.onError);let o=Hh({cmd:`pair-open`});return n.once(`connect`,()=>{(o===null||!Uh(n,o))&&t.onError(Error(`control socket write failed`))}),i=new Wh({onError:()=>{n.destroy(),t.onError(Error(`control socket sent a malformed message`))},onLine:e=>{if(r)return;let i;try{i=JSON.parse(e)}catch{t.onError(Error(`control socket sent a malformed message`));return}i.event===`request`&&i.phoneFp?t.onRequest(i.phoneFp,i.name??``).then(e=>{if(r)return;let t=Hh({cmd:`confirm`,args:{phoneFp:i.phoneFp,accept:e}});if(t===null||!Uh(n,t))throw Error(`control socket write failed`)}).catch(e=>t.onError(e)):i.event===`closed`?t.onClose(i.reason===`replaced`||i.reason===`paired`?i.reason:`closed`):i.ok&&i.data?.qrText?t.onOpen(i.data.qrText,i.data.expiresAt):i.ok===!1&&t.onError(Error(i.error??`control error`))}}),n.on(`data`,e=>i.push(new Uint8Array(e))),n.once(`end`,()=>{r=!0,i?.finish()}),n.once(`close`,()=>{r=!0,i?.finish()}),{close:a}}function Dg(e){if(e.linuxHost)return cm(e);let t;try{t=g(e.identity,`utf8`)}catch(t){if(t.code===`ENOENT`)return null;throw Error(`shellbell: cannot read identity at ${e.identity}`)}try{let e=ic(JSON.parse(t));return{identity:e,fp:ac(e.ed25519.pub)}}catch{throw Error(`shellbell: invalid identity at ${e.identity}`)}}function Og(e){if(e.linuxHost)return cm(e);pm(e);let t;return s(e.identity)?t=kg(e):(t=ec(),gm(e.identity,`${JSON.stringify(rc(t),null,2)}\n`)||(t=kg(e))),{identity:t,fp:ac(t.ed25519.pub)}}function kg(e){try{return ic(ym(e.identity))}catch(t){throw Error(`shellbell: invalid identity at ${e.identity}: ${t.message}`)}}const Ag=[`dev.bilalahmad.shellbell`,`dev.bilalahmad.shellbell.host.agent`,`dev.bilalahmad.shellbell.host.manual`];async function jg(e,t,n){if(!Number.isSafeInteger(t)||t<0)throw Error(`Invalid service UID`);let r=()=>Error(`Legacy Shellbell installation requires migration before starting the new service; preserve identity and remove old registrations explicitly.`);if(n)for(let e of Ag){try{p(N(n,`Library`,`LaunchAgents`,`${e}.plist`))}catch(e){if(e.code===`ENOENT`)continue;throw e}throw r()}for(let n of[...Ag.map(e=>`gui/${t}/${e}`),`system/dev.bilalahmad.shellbell.power`]){let t=await e(`/bin/launchctl`,[`print`,n],{timeoutMs:5e3,maxOutputBytes:65536,captureOutput:!1});if(t.exitCode===0)throw r();if(t.exitCode!==113)throw Error(`Could not verify legacy Shellbell registration absence`)}}const Mg=[`/opt/homebrew/bin`,`/usr/local/bin`,`/usr/bin`,`/bin`],Ng=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Pg(e){for(let t of e){let e=t.codePointAt(0);if(!(e===9||e===10||e===13||e>=32&&e<=55295||e>=57344&&e<=65533||e>=65536&&e<=1114111))throw Error(`invalid XML character in service definition`)}}function Fg(e,t){if(!e||!M(e))throw Error(`${t} must be an absolute path`);return Pg(e),e}function Ig(e){if(Fg(e.stateDir,`stateDir`),Fg(e.nodePath,`nodePath`),!Ng.test(e.serviceInstance))throw Error(`serviceInstance must be a UUID`);let t=[j(e.nodePath),...e.env.PATH?.split(`:`)??[],...Mg].filter(e=>e.length>0&&M(e)),n={SHELLBELL_DIR:e.stateDir,SHELLBELL_SERVICE_INSTANCE:e.serviceInstance,PATH:[...new Set(t)].join(`:`)};for(let t of[`HERDR_SOCKET_PATH`,`XDG_CONFIG_HOME`]){let r=e.env[t];r&&(n[t]=Fg(r,t))}for(let e of Object.values(n))Pg(e);return n}const Lg=`sh.bilal.shellbell`;N(D(),`Library`,`LaunchAgents`,`${Lg}.plist`);const Rg=1048576,zg=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Bg=new Set([`SHELLBELL_DIR`,`SHELLBELL_SERVICE_INSTANCE`,`PATH`,`HERDR_SOCKET_PATH`,`XDG_CONFIG_HOME`]),Vg=new Set([`Label`,`ProgramArguments`,`EnvironmentVariables`,`RunAtLoad`,`KeepAlive`,`StandardOutPath`,`StandardErrorPath`]);function Hg(e){return Pg(e),e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&apos;`)}function Ug(e){let t=Hg,n=e.environment??{PATH:`/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin`},r=Object.entries(n).map(([e,n])=>`<key>${t(e)}</key><string>${t(n)}</string>`).join(``);return`<?xml version="1.0" encoding="UTF-8"?>
17
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
18
+ <plist version="1.0"><dict>
19
+ <key>Label</key><string>${Lg}</string>
20
+ <key>ProgramArguments</key><array>
21
+ <string>${t(e.nodePath)}</string><string>${t(e.cliPath)}</string><string>start</string><string>--service</string>
22
+ </array>
23
+ <key>EnvironmentVariables</key><dict>${r}</dict>
24
+ <key>RunAtLoad</key><true/>
25
+ <key>KeepAlive</key><true/>
26
+ <key>StandardOutPath</key><string>${t(e.logPath)}</string>
27
+ <key>StandardErrorPath</key><string>${t(e.logPath)}</string>
28
+ </dict></plist>
29
+ `}function Wg(e,t){if(typeof e!=`string`||!e||!M(e))throw Error(`invalid service definition: ${t} must be an absolute path`);return Hg(e),e}function Gg(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`invalid service definition`);let n=e;for(let e of Object.keys(n))if(!Vg.has(e))throw Error(`unrecognized service definition key: ${e}`);if(n.Label!==`sh.bilal.shellbell`||!Array.isArray(n.ProgramArguments)||n.ProgramArguments.length!==4||n.ProgramArguments[2]!==`start`||n.ProgramArguments[3]!==`--service`||n.RunAtLoad!==!0||n.KeepAlive!==!0||n.StandardOutPath!==n.StandardErrorPath)throw Error(`unrecognized Shellbell service definition`);let r=n.EnvironmentVariables;if(!r||typeof r!=`object`||Array.isArray(r))throw Error(`invalid service environment`);let i=r;for(let[e,t]of Object.entries(i)){if(!Bg.has(e))throw Error(`unrecognized service environment: ${e}`);if(typeof t!=`string`)throw Error(`invalid service environment: ${e}`);Hg(e),Hg(t),(e===`HERDR_SOCKET_PATH`||e===`XDG_CONFIG_HOME`)&&Wg(t,e)}if(typeof i.PATH!=`string`||!i.PATH||i.PATH.split(`:`).some(e=>!e||!M(e)))throw Error(`invalid service PATH`);let a=i.SHELLBELL_DIR===void 0?N(t,`.shellbell`):Wg(i.SHELLBELL_DIR,`SHELLBELL_DIR`),o=i.SHELLBELL_SERVICE_INSTANCE;if(o!==void 0&&(typeof o!=`string`||!zg.test(o)))throw Error(`invalid service instance`);return{nodePath:Wg(n.ProgramArguments[0],`nodePath`),cliPath:Wg(n.ProgramArguments[1],`cliPath`),stateDir:a,serviceInstance:o??null,environment:i,logPath:Wg(n.StandardOutPath,`logPath`)}}function Kg(e){if(Wg(e.nodePath,`nodePath`),Wg(e.cliPath,`cliPath`),Wg(e.stateDir,`stateDir`),Wg(e.logPath,`logPath`),!e.serviceInstance||!zg.test(e.serviceInstance))throw Error(`serviceInstance must be a UUID`);let t=e.environment;if(t.SHELLBELL_DIR!==e.stateDir||t.SHELLBELL_SERVICE_INSTANCE!==e.serviceInstance)throw Error(`service definition and environment disagree`);if(!t.PATH||t.PATH.split(`:`).some(e=>!e||!M(e)))throw Error(`invalid service PATH`);for(let[e,n]of Object.entries(t)){if(!Bg.has(e))throw Error(`unsupported service environment: ${e}`);if(typeof n!=`string`)throw Error(`invalid service environment: ${e}`);Hg(e),Hg(n),(e===`HERDR_SOCKET_PATH`||e===`XDG_CONFIG_HOME`)&&Wg(n,e)}}function qg(e={}){let t=e.run??Fh,n=e.uid??te().uid;if(!Number.isSafeInteger(n)||n<0)throw Error(`invalid service UID`);let r=e.homeDir??D(),i=e.definitionPath??N(r,`Library`,`LaunchAgents`,`sh.bilal.shellbell.plist`),a=`gui/${n}`,o=`${a}/${Lg}`,s;function c(e,t){return e===null||t===null?e===t:e.stat.dev===t.stat.dev&&e.stat.ino===t.stat.ino&&e.stat.uid===t.stat.uid&&e.stat.mode===t.stat.mode&&e.stat.size===t.stat.size&&e.stat.mtimeMs===t.stat.mtimeMs&&e.stat.ctimeMs===t.stat.ctimeMs&&e.raw.equals(t.raw)}function l(){let e;try{e=p(i)}catch(e){if(e.code===`ENOENT`)return null;throw e}return!e.isFile()||e.isSymbolicLink()||e.uid!==n||e.mode&18||e.size>Rg?{stat:e,raw:Buffer.alloc(0)}:{stat:e,raw:g(i)}}function u(e){if(!c(e,l()))throw Error(`service definition changed or was replaced during operation`)}function d(e){let t=l();if(!t?.raw.equals(e))throw Error(`service definition changed after publication`);s=t}async function f(e,n,r=!1,i){let a=await t(e,n,{input:i,timeoutMs:5e3,maxOutputBytes:e===`/usr/bin/plutil`?Rg:65536,captureOutput:r});if(!Number.isInteger(a.exitCode))throw Error(`${e} returned invalid exit status`);return a}async function h(e){let t=await f(`/usr/bin/plutil`,[`-convert`,`json`,`-o`,`-`,`-`],!0,e);if(t.exitCode!==0)throw Error(`plutil could not parse service definition`);let n;try{n=JSON.parse(t.stdout.toString(`utf8`))}catch{throw Error(`plutil returned invalid service definition JSON`)}return Gg(n,r)}async function _(){let e;try{e=p(i)}catch(e){if(e.code===`ENOENT`)return null;throw e}if(!e.isFile()||e.isSymbolicLink()||e.uid!==n||e.mode&18||e.size>Rg)throw Error(`unsafe service definition metadata`);let t=g(i);if(t.length>Rg)throw Error(`service definition too large`);let r=await h(t),a={stat:e,raw:t};return u(a),{...a,definition:r}}async function v(){let e=await f(`/bin/launchctl`,[`print`,o]);if(e.exitCode===0)return!0;if(e.exitCode===113)return!1;throw Error(`launchctl print failed (${e.exitCode})`)}async function y(){try{let e=await f(`/bin/launchctl`,[`print-disabled`,a],!0),t=new TextDecoder(`utf-8`,{fatal:!0}).decode(e.stdout).trim().split(/\r?\n/).map(e=>e.trim());if(e.exitCode!==0||t.shift()!==`disabled services = {`||t.pop()!==`}`)return null;let n=t.filter(e=>e.includes(`"${Lg}"`));return n.length===0?!0:n.length===1?n[0]===`"sh.bilal.shellbell" => disabled`||n[0]===`"sh.bilal.shellbell" => true`?!1:n[0]===`"sh.bilal.shellbell" => enabled`||n[0]===`"sh.bilal.shellbell" => false`||null:null}catch{return null}}let b={kind:`launchd`,definitionPath:i,async inspect(){let e=await _(),t=await v();if(u(e),!e&&t)throw Error(`loaded Shellbell job has no valid installed definition`);if(s!==void 0&&!c(s,e))throw Error(`service definition changed or was replaced after inspection`);return s===void 0&&(s=e),{installed:!!e,startupEnabled:e?await y():!1,loaded:t,raw:e?.raw??null,definition:e?.definition??null}},async setStartupEnabled(e){let t=await b.inspect();if(!t.installed)throw Error(`service is not installed`);if(t.startupEnabled!==e){if((await f(`/bin/launchctl`,[e?`enable`:`disable`,o])).exitCode!==0)throw Error(`launchctl startup preference change failed`);if((await b.inspect()).startupEnabled!==e)throw Error(`launchctl startup preference could not be verified`)}},async write(e){await jg(t,n,r),Kg(e);let a=await _();if(s!==void 0&&!c(s,a))throw Error(`service definition changed or was replaced after inspection`);if(!a&&await v())throw Error(`loaded Shellbell job has no installed definition`);let o=Ug({...e});m(j(i),{recursive:!0,mode:448}),mm(i,o,()=>u(a)),d(Buffer.from(o))},async restore(e){if(e!==null&&e.length>Rg)throw Error(`service definition too large`);let a=await _();if(s!==void 0&&!c(s,a))throw Error(`service definition changed or was replaced after inspection`);if(e===null){if(!a)return;if(s===void 0)throw Error(`refusing to remove unexpected service definition replacement`);u(a),w(i),s=null;return}if(s===void 0)throw Error(`service definition changed unexpectedly`);if(await h(e),a)mm(i,e,()=>u(a));else if(await jg(t,n,r),m(j(i),{recursive:!0,mode:448}),!gm(i,e))throw Error(`service definition changed or was replaced after inspection`);d(e)},async load(){await jg(t,n,r);let e=await b.inspect();if(!e.installed)throw Error(`service definition is not installed`);if(e.startupEnabled===null)throw Error(`service startup preference is unresolved`);let s=e.startupEnabled===!1;try{if(s&&await b.setStartupEnabled(!0),!e.loaded){let e=await f(`/bin/launchctl`,[`bootstrap`,a,i]);if(e.exitCode!==0)throw Error(`launchctl bootstrap failed (${e.exitCode})`)}let t=await f(`/bin/launchctl`,[`kickstart`,`-p`,o],!0);if(t.exitCode!==0)throw Error(`launchctl kickstart failed (${t.exitCode})`);let n=t.stdout.toString(`utf8`).trim();if(!/^[1-9][0-9]*$/.test(n))throw Error(`invalid launchctl PID output`);let r=Number(n);if(!Number.isSafeInteger(r)||r>2147483647)throw Error(`invalid launchctl PID output`);return r}finally{s&&await b.setStartupEnabled(!1)}},async unload(){if(!(await b.inspect()).loaded)return;let e=await f(`/bin/launchctl`,[`bootout`,o]);if(e.exitCode!==0)throw Error(`launchctl bootout failed (${e.exitCode})`);if(await v())throw Error(`launchctl bootout did not unload service`)}};return b}function Jg(e){s(e)?i(e,384):T(e,``,{mode:384})}const Yg=F.string().refine(e=>Buffer.byteLength(e,`utf8`)<=4096&&M(e)&&![...e].some(e=>e.charCodeAt(0)<32||e.charCodeAt(0)===127)),Xg=F.enum([`desktop`,`headless`]),Zg=F.enum([`prepared`,`source-stopped`,`destination-started`,`recovery-required`]),Qg=F.enum([`manual`,`persistent`,`desktop`]),$g=F.strictObject({id:F.uuid(),source:F.enum([`desktop`,`headless`,`legacy-native`]).nullable(),target:Xg,sourceManager:F.enum([`desktop-child`,`native-manual`,`native-persistent`,`launchd`,`systemd`]).nullable(),sourceInstance:F.uuid().nullable(),stateDir:Yg,computerFp:W,targetBundlePath:Yg.nullable(),targetVersion:F.string().min(1).max(256),phase:Zg}),e_=F.strictObject({v:F.literal(1),revision:F.uuid(),mode:Xg,consented:F.boolean(),startupEnabled:F.boolean(),transition:$g.nullable()}),t_=2097152,n_=F.number().int().positive().max(2**53-1),r_=F.uuid(),i_=F.string().regex(/^[0-9a-f]{64}$/),a_=F.string().refine(e=>Buffer.byteLength(e,`utf8`)<=4096),o_=F.enum([`manual`,`persistent`]);function s_(e){if(e===`desktop`)throw new j_(`conflict`);return e}const c_=F.enum([`prepared`,`source-stop-requested`,`source-stopped`,`destination-start-requested`,`awaiting-approval`,`destination-ready`,`recovery-required`]),l_=F.strictObject({PATH:a_.refine(e=>e.split(`:`).every(e=>Yg.safeParse(e).success)),SHELLBELL_DIR:Yg,SHELLBELL_SERVICE_INSTANCE:F.uuid(),HERDR_SOCKET_PATH:Yg.optional(),XDG_CONFIG_HOME:Yg.optional()}),u_=F.strictObject({mode:Qg,stateDir:Yg,computerFp:W,serviceInstance:F.uuid(),bundlePath:Yg,bundleId:F.literal(`sh.bilal.shellbell.host`),agentVersion:F.string().min(1),environment:l_}).refine(e=>e.environment.SHELLBELL_DIR===e.stateDir&&e.environment.SHELLBELL_SERVICE_INSTANCE===e.serviceInstance),d_=F.strictObject({id:F.uuid(),definitionPath:Yg,rawBase64:F.string().max(1398104).refine(e=>/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)&&Buffer.from(e,`base64`).byteLength<=1048576&&Buffer.from(e,`base64`).toString(`base64`)===e),sha256:i_,wasLoaded:F.boolean(),stateDir:Yg,computerFp:W}),f_=F.strictObject({id:F.uuid(),action:F.enum([`start`,`stop`,`restart`,`remove`,`recover`]),phase:c_}),p_=f_.extend({source:u_.nullable(),destination:u_.nullable(),recoveryId:F.uuid().nullable(),restoreLegacy:F.strictObject({restartPrevious:F.boolean()}).optional()}).refine(e=>e.restoreLegacy===void 0||e.action===`recover`),m_=F.strictObject({v:F.literal(1),revision:r_,selection:u_.nullable(),transition:p_.nullable(),recovery:d_.nullable()}).refine(e=>e.transition?.recoveryId==null||e.transition.recoveryId===e.recovery?.id),h_=F.strictObject({registration:F.enum([`not-registered`,`enabled`,`requires-approval`,`not-found`,`unknown`]),loaded:F.boolean(),pid:n_.nullable(),bundlePath:Yg.nullable()}),g_=F.discriminatedUnion(`ok`,[F.strictObject({v:F.literal(1),ok:F.literal(!0),status:F.enum([`not-registered`,`enabled`,`requires-approval`,`not-found`])}),F.strictObject({v:F.literal(1),ok:F.literal(!1),error:F.strictObject({code:F.enum([`unavailable`,`denied`,`invalid-bundle`,`operation-failed`])})})]),__=F.strictObject({revision:r_.nullable(),runtime:Jh.extend({stateDir:Yg}).nullable()}),v_=F.strictObject({revision:r_.nullable(),mode:F.enum([`desktop`,`headless`,`legacy-native`]).nullable(),consented:F.boolean(),startupEnabled:F.boolean().nullable(),transition:$g.nullable()}),y_=F.strictObject({desktopLogin:h_.shape.registration.optional(),desktop:h_.optional(),ownership:v_.optional(),revision:r_.nullable(),selection:u_.nullable(),transition:f_.nullable(),recoveryAvailable:F.boolean(),manualRecoveryAvailable:F.boolean().optional(),legacy:F.strictObject({installed:F.boolean(),loaded:F.boolean(),stateDir:Yg.nullable()}),manual:h_,persistent:h_,local:F.strictObject({kind:F.enum([`verified`,`foreign`,`absent`,`unverified`]),status:ig.status.safeExtend({process:Jh.extend({stateDir:Yg})}).nullable()})}),b_=F.strictObject({saved:qp.strict(),savedRevision:i_,appliedRevision:i_.nullable(),applied:F.enum([`not-running`,`unknown`,`matches`,`restart-required`])}),x_=F.string().regex(/^[a-z][a-z0-9-]{0,31}$/),S_=F.strictObject({agents:F.array(F.strictObject({kind:x_,name:F.string().min(1).max(64),state:F.enum([`ready`,`needs-setup`,`hooks-off`,`blocked`,`coming-soon`]),helper:F.boolean(),skipped:F.boolean(),detail:F.string().min(1).max(512).optional()})).max(32)}),C_=F.strictObject({kinds:F.array(x_).min(1).max(32)}),w_={hello:F.strictObject({version:F.literal(1),agentVersion:F.string().min(1),capabilities:F.tuple([F.literal(`status`),F.literal(`settings`),F.literal(`lifecycle`),F.literal(`pairing`),F.literal(`devices`),F.literal(`diagnostics`)])}),status:y_,"desktop.setup":y_,"desktop.login.set":y_,"desktop.start":y_,"desktop.stop":y_,"ownership.convert":y_,"ownership.recover":y_,"settings.get":b_,"settings.set":b_,"service.start":y_,"service.stop":y_,"service.restart":y_,"service.remove":y_,"service.recover":y_,diagnostics:F.strictObject({checks:F.array(F.strictObject({name:F.string().min(1).max(64),ok:F.boolean(),severity:F.enum([`pass`,`warning`,`error`]),detail:F.string().max(1024),fix:F.string().max(2048).optional(),required:F.boolean().optional()})).max(32)}),devices:ig.devices,terminals:F.strictObject({supported:F.boolean(),terminals:Vu}),"terminals.connect":F.strictObject({supported:F.boolean(),started:F.boolean(),terminals:Vu}),agents:S_,"agents.setup":S_,"agents.skip":S_,"agents.remove":S_,"devices.revoke":ig[`devices.revoke`],"pairing.open":rg,"pairing.close":ig[`pairing.close`],"pairing.confirm":ig[`pairing.confirm`]},$={v:F.literal(1),id:n_},T_=F.strictObject({expect:__}),E_=T_.extend({ownerRevision:r_.nullable()}),D_=mg.options[0],O_=D_.shape.flowId,k_=F.discriminatedUnion(`cmd`,[F.strictObject({...$,cmd:F.literal(`desktop.login.set`),args:E_.extend({enabled:F.boolean()})}),F.strictObject({...$,cmd:F.literal(`desktop.setup`),args:E_.extend({consent:F.literal(!0)})}),F.strictObject({...$,cmd:F.literal(`desktop.start`),args:E_}),F.strictObject({...$,cmd:F.literal(`desktop.stop`),args:E_}),F.strictObject({...$,cmd:F.literal(`ownership.convert`),args:E_.extend({target:Xg,consent:F.literal(!0)})}),F.strictObject({...$,cmd:F.literal(`ownership.recover`),args:E_.extend({intentId:F.uuid()})}),F.strictObject({...$,cmd:F.literal(`hello`)}),F.strictObject({...$,cmd:F.literal(`status`)}),F.strictObject({...$,cmd:F.literal(`settings.get`)}),F.strictObject({...$,cmd:F.literal(`diagnostics`)}),F.strictObject({...$,cmd:F.literal(`devices`)}),F.strictObject({...$,cmd:F.literal(`terminals`)}),F.strictObject({...$,cmd:F.literal(`agents`)}),F.strictObject({...$,cmd:F.literal(`agents.setup`),args:C_}),F.strictObject({...$,cmd:F.literal(`agents.skip`),args:C_}),F.strictObject({...$,cmd:F.literal(`agents.remove`),args:F.strictObject({kind:x_})}),F.strictObject({...$,cmd:F.literal(`terminals.connect`),args:F.strictObject({name:Cu})}),F.strictObject({...$,cmd:F.literal(`settings.set`),args:T_.extend({configRevision:i_,changes:F.array(F.strictObject({key:F.enum(dh),value:a_})).min(1).max(dh.length).refine(e=>new Set(e.map(e=>e.key)).size===e.length)})}),F.strictObject({...$,cmd:F.literal(`service.start`),args:T_.extend({mode:o_,consent:F.literal(!0),migrateLegacy:F.boolean(),stateDir:Yg.optional()})}),F.strictObject({...$,cmd:F.literal(`service.stop`),args:T_}),F.strictObject({...$,cmd:F.literal(`service.restart`),args:T_}),F.strictObject({...$,cmd:F.literal(`service.remove`),args:T_}),F.strictObject({...$,cmd:F.literal(`service.recover`),args:T_.extend({action:F.enum([`continue`,`restore-legacy`,`discard-backup`,`use-manual`]),restartPrevious:F.boolean(),consent:F.literal(!0)}).refine(e=>!e.restartPrevious||e.action===`restore-legacy`)}),F.strictObject({...$,cmd:F.literal(`devices.revoke`),args:T_.extend({phoneFp:W})}),F.strictObject({...$,cmd:F.literal(`pairing.open`),args:T_}),F.strictObject({...$,cmd:F.literal(`pairing.close`),args:T_.extend({flowId:O_})}),F.strictObject({...$,cmd:F.literal(`pairing.confirm`),args:T_.extend({flowId:O_,challengeId:D_.shape.challengeId,phoneFp:W,accept:F.boolean()})})]),A_=F.enum([`bad-request`,`unsupported-version`,`handshake-required`,`busy`,`unavailable`,`conflict`,`unsafe-state`,`invalid-config`,`upgrade-required`,`startup-unavailable`,`delivery-unknown`,`approval-required`,`recovery-required`,`operation-failed`,`response-too-large`,`timeout`]);var j_=class extends Error{code;constructor(e){super(e),this.code=e,this.name=`NativeControllerError`}};F.discriminatedUnion(`ok`,[F.strictObject({...$,ok:F.literal(!0),data:F.union(Object.values(w_))}),F.strictObject({...$,ok:F.literal(!1),error:F.strictObject({code:A_})})]);const M_=F.discriminatedUnion(`event`,[D_.extend({v:F.literal(1)}),mg.options[1].extend({v:F.literal(1)})]);function N_(){throw new j_(`unsafe-state`)}function P_(e,t){return Fp(e,t)&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ctimeMs===t.ctimeMs&&e.mode===t.mode&&e.uid===t.uid}function F_(e){return e instanceof j_?e:new j_(e instanceof Y?`unsafe-state`:`operation-failed`)}var I_=class{options;root;path;uid;newId;constructor(e){this.options=e,(!Yg.safeParse(e.root).success||!Number.isSafeInteger(e.uid)||e.uid<0)&&N_(),this.root=e.root.replace(/\/+$/,``)||`/`,this.path=N(this.root,e.filename),this.uid=e.uid,this.newId=e.newId??ce}inspect(){try{return this.checkAncestors(),X(this.root)?this.readSnapshot(Z(this.root,this.uid)).record:null}catch{return N_()}}async mutate(e,t){let n,r,i=!0;try{this.checkAncestors(),X(this.root)||m(this.root,{recursive:!0,mode:448});let a=Z(this.root,this.uid);r=h(this.root,o.O_RDONLY|o.O_NOFOLLOW|o.O_NONBLOCK),Fp(a,l(r))||N_(),n=this.acquireGuard(a);let s=this.readSnapshot(a);if((s.record?.revision??null)!==e)throw new j_(`conflict`);return await t({get current(){return structuredClone(s.record)},publish:e=>{if(!i)throw new j_(`operation-failed`);try{let t=this.options.schema.safeParse({...e,revision:this.newId()});(!t.success||t.data.revision===s.record?.revision)&&N_();let i=Buffer.from(JSON.stringify(t.data));return i.length>this.options.maxBytes&&N_(),this.publish(i,a,s,()=>n.assert()),u(r),s=this.readSnapshot(a),structuredClone(t.data)}catch(e){throw F_(e)}}})}catch(e){throw F_(e)}finally{i=!1;try{n?.release()}finally{r!==void 0&&a(r)}}}checkAncestors(){let e=this.root;for(;;){let t=X(e);t&&(!t.isDirectory()||t.isSymbolicLink())&&N_();let n=j(e);if(n===e)return;e=n}}checkRoot(e){this.checkAncestors(),Fp(e,Z(this.root,this.uid))||N_()}readSnapshot(e){this.checkRoot(e);let t=X(this.path);if(!t)return this.checkRoot(e),{record:null,stat:void 0,bytes:null};let n=Rp(this.path,this.options.maxBytes,this.uid),r=X(this.path);(!r||!P_(t,r))&&N_(),this.checkRoot(e);let i;try{i=JSON.parse(new TextDecoder(`utf-8`,{fatal:!0}).decode(n))}catch{return N_()}let a=this.options.schema.safeParse(i);return a.success?{record:a.data,stat:r,bytes:n}:N_()}checkSnapshot(e,t){let n=this.readSnapshot(e);(t.stat?!n.stat||!P_(t.stat,n.stat)||!t.bytes?.equals(n.bytes):n.stat!==void 0)&&N_()}publish(e,t,n,r){r(),this.checkSnapshot(t,n);let i=`${this.path}.tmp-${ce()}`,s,c;try{s=h(i,o.O_WRONLY|o.O_CREAT|o.O_EXCL|o.O_NOFOLLOW,384),c=l(s);let a=0;for(;a<e.length;){let t=E(s,e,a,e.length-a);if(t<=0)throw new j_(`operation-failed`);a+=t}u(s);let d=l(s);this.checkSnapshot(t,n);let f=X(i);(!f||!Fp(c,d)||!P_(d,f)||!f.isFile()||f.uid!==this.uid||(f.mode&4095)!=384||d.size!==e.length)&&N_(),r(),b(i,this.path)}finally{s!==void 0&&a(s);try{this.checkRoot(t);let e=X(i);c&&e&&Fp(c,e)&&w(i)}catch{}}}acquireGuard(e){let t=`${this.path}.lock`,n=`owner-${process.pid}-${ce()}`,r=`${this.path}.lock-candidate-${n.slice(6)}`,i,o,s=!1,c=(r,i,a=n,s=o,c=!1)=>{try{if(this.checkRoot(e),!Fp(i,Z(r,this.uid)))return!1;let n=X(N(r,a));if(n&&(!s||!P_(s,n)))return!1;if(r===t){if(!n||!s)return!1;let e=`${this.path}.lock-candidate-${a.slice(6)}`;if(X(e)||(b(r,e),r=e,!Fp(i,Z(r,this.uid)))||(n=X(N(r,a)),!n||!P_(s,n)))return!1;if(c)return!0}return n&&w(N(r,a)),x(r),!0}catch{return!1}};try{this.checkRoot(e),m(r,{mode:448}),i=Z(r,this.uid);let u=h(N(r,n),`wx`,384);try{o=l(u)}finally{a(u)}for(let a=0;a<3;a++){if(this.checkRoot(e),X(t)){let e=Z(t,this.uid),n=v(t),r=n[0],i=r&&/^owner-([1-9][0-9]*)-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/.exec(r),a=i&&Ap(i[1]);(n.length!==1||!r||!a)&&N_();let o=X(N(t,r));if(Rp(N(t,r),0,this.uid),jp(a))throw new j_(`busy`);Fp(e,Z(t,this.uid))||N_();let s=X(N(t,r));(!o||!s||!P_(o,s))&&N_(),c(t,e,r,o,!0)||N_()}try{b(r,t),s=!0;let a=Z(t,this.uid);return Fp(i,a)||N_(),{assert:()=>{this.checkRoot(e),Fp(a,Z(t,this.uid))||N_();let r=X(N(t,n));(!r||!o||!P_(o,r))&&N_()},release:()=>c(t,a)}}catch(e){if(![`EEXIST`,`ENOTEMPTY`,`ENOENT`].includes(e.code??``))throw e}}throw new j_(`busy`)}finally{!s&&i&&c(r,i)}}},L_=class extends I_{constructor(e){super({root:e.stateDir,uid:e.uid,filename:`service-owner.json`,maxBytes:16384,schema:e_})}};function R_(e){if(e?.mode===`desktop`)throw Error(`Service is desktop-owned; use Shellbell or explicitly convert it to headless mode`);if(e?.transition)throw Error(`An ownership conversion needs explicit recovery before headless service changes`)}function z_(e){let t;try{t=new L_({...e,stateDir:Ip(e.stateDir)}).inspect()}catch{return null}return t?.mode===`desktop`?`The Shellbell app runs Shellbell on this Mac. Use the app to pair phones and change settings.`:t?.transition?`The Shellbell app is switching how Shellbell runs on this Mac. Open the app to finish, then try again.`:null}function B_(e){let t=U_(new L_({...e,stateDir:Ip(e.stateDir)})),n=t?.transition;t?.mode===`headless`&&n?.target===`headless`&&e.serviceInstance===n.id&&[`source-stopped`,`destination-started`].includes(n.phase)||R_(t)}async function V_(e,t){let n=new L_({...e,stateDir:Ip(e.stateDir)}),r=U_(n);return R_(r),H_(n,r?.revision??null,async e=>(R_(e.current),t()))}async function H_(e,t,n){let r=!1,i;return e.mutate(t,async e=>{try{return await n(e)}catch(e){throw r=!0,i=e,e}}).catch(e=>{throw r?i:W_(e)})}function U_(e){try{return e.inspect()}catch(e){throw W_(e)}}function W_(e){if(!(e instanceof j_))return e;let t={busy:`shellbell: Another Shellbell change is in progress, such as the Mac app starting or stopping its service. Try again in a moment.`,conflict:"shellbell: Shellbell's service ownership changed while this ran. Check `shellbell status`, then try again.","operation-failed":`shellbell: Shellbell couldn't read or save its service ownership record in its state folder. Check that the folder is yours and has free space, then try again.`,"unsafe-state":`shellbell: Shellbell's state folder has unsafe permissions or ownership; it must belong to you and not be writable by others.`};return t[e.code]?Error(t[e.code]):e}async function G_(e,t){let n=new L_(e),r=U_(n);return R_(r),!e.create&&!r&&!s(e.stateDir)?t():H_(n,r?.revision??null,async n=>{R_(n.current);let r=await t(),i=e.startupPreference?e.startupPreference(r):r.startupEnabled;if(i!==null&&(r.installed||n.current)&&(!n.current||n.current.startupEnabled!==i))try{n.publish({v:1,mode:`headless`,consented:!0,startupEnabled:i,transition:null})}catch(e){throw W_(e)}return r})}function K_(e){try{return y(e)}catch(t){if(t.code===`ENOENT`)return P(e);throw Error(`Cannot resolve state directory ${e}`)}}function q_(e,t){try{return e.process.computerFp===t.computerFp&&K_(e.process.stateDir)===K_(t.stateDir)&&(t.serviceInstance===void 0||e.process.serviceInstance===t.serviceInstance)&&(t.pid===void 0||e.process.pid===t.pid)}catch{return!1}}var J_=class{clock;probe;constructor(e={}){this.clock=e.clock??{now:()=>de.now(),sleep:e=>new Promise(t=>setTimeout(t,e))},this.probe=e.probe??((e,t)=>Tg(e,`status`,void 0,{timeoutMs:t,maxResponseBytes:65536}))}async observe(e,t,n=500){let r;try{r=await this.probe(e,n)}catch(e){let t=e.code;return t===`ENOENT`||t===`ECONNREFUSED`?{kind:`absent`,local:null,diagnostic:`Local endpoint is absent`}:{kind:`unverified`,local:null,diagnostic:`Local endpoint did not return a bounded status response`}}let i=Nh.safeParse(r);return i.success?t&&!q_(i.data,t)?{kind:`foreign`,local:i.data,diagnostic:`Local endpoint belongs to a different process, identity, state directory, or service instance`}:{kind:`verified`,local:i.data}:{kind:`unverified`,local:null,diagnostic:`Local endpoint uses an unsupported or malformed status protocol`}}async waitReady(e,t){return(await this.wait(e,t,!1)).local}async waitStopped(e){await this.wait(e,void 0,!0)}async wait(e,t,n){let r=this.clock.now()+1e4,i=`Local endpoint is absent`;for(;this.clock.now()<r;){let a=await this.observe(e,t,Math.min(500,r-this.clock.now()));if(n?a.kind===`absent`:a.kind===`verified`)return a;if(i=a.diagnostic??`Local endpoint is still responding`,!n&&a.kind===`foreign`)throw Error(`Service readiness conflict: ${i}; stop the foreground owner before retrying`);let o=r-this.clock.now();o>0&&await this.clock.sleep(Math.min(100,o))}throw Error(`${n?`Service stop`:`Service readiness`} timed out: ${i}`)}};const Y_=new Set([`.npm`,`_npx`,`dlx`]),X_=[[`npm`,`config`,`cache`].join(`_`),`NPM_CONFIG_CACHE`];function Z_(e,t){throw Error(`Shellbell service runtime at ${e} ${t}; install a built Shellbell package in a durable directory, then run shellbell install again`)}function Q_(e){try{return y(e)}catch{return ne(e)}}function $_(){let e=[k(),`/tmp`,`/private/tmp`,`/var/tmp`,`/private/var/tmp`];for(let t of X_){let n=process.env[t];n&&M(n)&&e.push(n)}return[...new Set(e.flatMap(e=>[ne(e),Q_(e)]))]}function ev(e,t){let n=re(t,e);return n===``||n!==`..`&&!n.startsWith(`..${ie}`)&&!M(n)}function tv(e){let t=ne(e);(t.split(ie).some(e=>Y_.has(e))||$_().some(e=>ev(t,e)))&&Z_(e,`is in a temporary or package-manager cache location`)}function nv(e,t){M(e)||Z_(e,`${t} path must be absolute`),tv(e);let n;try{n=y(e)}catch{Z_(e,`${t} does not exist`)}return tv(n),(()=>{try{return S(n)}catch{return Z_(n,`${t} does not exist`)}})().isFile()||Z_(n,`${t} must be a regular file`),n}function rv(e,t,r){try{n(e,t)}catch{Z_(e,r)}}function iv(e){let t=`${e}${ie}package.json`,n=(()=>{try{return S(t)}catch{return Z_(t,`package.json is missing`)}})();n.isFile()||Z_(t,`package.json must be a regular file`),n.size>1048576&&Z_(t,`package.json exceeds 1 MiB`);let r;try{r=g(t,`utf8`)}catch{Z_(t,`package.json is not readable`)}let i;try{i=JSON.parse(r)}catch{Z_(t,`package.json is not valid JSON`)}return(typeof i!=`object`||!i||Array.isArray(i))&&Z_(t,`package.json is not a valid manifest`),i}function av(e){let t=e.bin,n=typeof t==`string`?t:typeof t==`object`&&t&&!Array.isArray(t)?t.shellbell:void 0;return n===`dist/cli.js`||n===`./dist/cli.js`}function ov(e=process.execPath,t=process.argv[1]??``){let n=Number.parseInt(process.versions.node.split(`.`)[0]??``,10);(!Number.isInteger(n)||n<22)&&Z_(process.execPath,`requires the currently running Node.js major version to be at least 22`);let r=nv(e,`Node executable`);rv(r,o.X_OK,`Node executable is not executable`);let i=nv(t,`CLI entrypoint`);rv(i,o.R_OK,`CLI entrypoint is not readable`),(A(i)!==`cli.js`||A(j(i))!==`dist`)&&Z_(i,`is not an installed built CLI entrypoint`);let a=j(j(i)),c=`${a}${ie}src${ie}cli.ts`;s(c)&&Z_(a,`is a source checkout rather than an installed built package`);let l=iv(a);return l.name!==`shellbell`&&Z_(`${a}${ie}package.json`,`has the wrong package name`),av(l)||Z_(`${a}${ie}package.json`,`does not declare the Shellbell bin entrypoint`),{nodePath:r,cliPath:i,packageRoot:a}}var sv=class extends Error{rollback=`not-needed`;rollbackDiagnostic;recoveryPath};function cv(e,t,n){let r=e.definition?.stateDir,i=K_(r??(t||n));if(r&&t&&K_(t)!==i)throw new sv(`SHELLBELL_DIR conflicts with the installed service state directory; state migration is not an implicit install operation`);return fm(i)}function lv(e){return e instanceof sv?e:new sv(e instanceof Error?e.message.slice(0,600):`Service operation failed`)}async function uv(e,t,n){let r=j(e.definitionPath),i;try{return t&&m(r,{recursive:!0,mode:448}),s(r)&&(i=Pp(e.definitionPath)),await n(e)}finally{i?.()}}var dv=class{options;manager;readiness;constructor(e){this.options=e,this.manager=e.manager,this.readiness=new J_(e)}selected(e){return cv(e,this.options.requestedStateDir,this.options.defaultStateDir)}definitionFor(e,t,n){let r=Ig({stateDir:t.dir,serviceInstance:n,nodePath:e.nodePath,env:this.options.env}),i={nodePath:e.nodePath,cliPath:e.cliPath,stateDir:t.dir,serviceInstance:n,environment:r,logPath:t.log};for(let e of Object.values(i))typeof e==`string`&&Pg(e);for(let[e,t]of Object.entries(r))Pg(e),Pg(t);return i}expected(e,t){let n=Dg(t);return n?{computerFp:n.fp,stateDir:t.dir,serviceInstance:e.definition?.serviceInstance??null}:void 0}result(e,t,n,r=null,i){let a=e.installed&&e.definition?.serviceInstance===null,o=e.installed&&e.loaded&&!!n&&t.kind===`verified`&&(!a||r!==null),s=i??(n?a&&r===null?`Legacy service cannot be verified by read-only status; run service install to upgrade`:void 0:`Local identity is missing; no keys were created`),c=e.definition&&!e.definition.environment.SHELLBELL_DIR?`Legacy definition assumes the historical ~/.shellbell state directory`:void 0;return{manager:this.manager.kind,definitionPath:this.manager.definitionPath,installed:e.installed,loaded:e.loaded,startupEnabled:e.startupEnabled??null,autostartConfigured:e.installed&&e.startupEnabled===!0,managedPid:r,ownership:t.kind===`foreign`?`foreign`:a&&!o?`legacy`:o?`verified`:`none`,local:t.local,ready:o,...t.diagnostic||s||c?{diagnostic:[t.diagnostic,s,c].filter(Boolean).join(`; `)}:{}}}async installedRuntime(){let{definition:e}=await this.manager.inspect();return e?{nodePath:e.nodePath,cliPath:e.cliPath,stateDir:e.stateDir}:null}async status(){let e=await this.manager.inspect(),t=this.selected(e),n=this.expected(e,t);return this.result(e,await this.readiness.observe(t.sock,n),n)}async serialized(e,t){try{let n=await this.manager.inspect();return await G_({stateDir:Ip(this.selected(n).dir),uid:process.getuid(),create:e},()=>uv(this.manager,e,t))}catch(e){throw lv(e)}}assertAvailable(e,t,n){if(t.kind!==`absent`&&!(e.loaded&&e.definition?.serviceInstance===null&&t.kind===`unverified`)&&!(e.loaded&&n&&t.kind===`verified`))throw new sv(`Local endpoint ownership is unverified or foreign; stop the foreground owner before retrying service changes`)}async rollback(e,t,n,r,i){let a=lv(i);if(!r.unloadAttempted&&!r.written&&!r.loaded)throw a;try{if(r.loaded&&await this.manager.unload(),(r.unloadAttempted||r.loaded)&&await this.readiness.waitStopped(t.sock),r.written&&await this.manager.restore(e.raw),e.loaded){let r=await this.manager.load();e.definition?.serviceInstance&&n&&await this.readiness.waitReady(t.sock,{...n,pid:r})}a.rollback=`restored`}catch(t){if(a.rollback=`failed`,a.rollbackDiagnostic=lv(t).message,e.raw){let t=`${this.manager.definitionPath}.recovery-${ce()}`;try{T(t,e.raw,{mode:384,flag:`wx`}),a.recoveryPath=t}catch{a.rollbackDiagnostic+=`; could not save a private recovery definition`}}}throw a}async install(){try{let e=ov(),t=ce();return this.definitionFor(e,fm(K_(this.options.requestedStateDir||this.options.defaultStateDir)),t),await this.serialized(!0,async()=>{let n=await this.manager.inspect(),r=this.selected(n),i=this.definitionFor(e,r,t),a=this.expected(n,r);if(n.installed&&!a)throw new sv(`Installed service identity is missing at ${r.identity}; restore it before upgrading`);this.assertAvailable(n,await this.readiness.observe(r.sock,a),a);let o=Dg(r)??Og(r);Jg(r.log);let s={computerFp:o.fp,stateDir:r.dir,serviceInstance:t},c={unloadAttempted:!1,written:!1,loaded:!1};try{n.loaded&&(c.unloadAttempted=!0,await this.manager.unload(),await this.readiness.waitStopped(r.sock)),c.written=!0,await this.manager.write(i),c.loaded=!0;let e=await this.manager.load(),t=await this.readiness.waitReady(r.sock,{...s,pid:e}),a=await this.manager.inspect();if(!a.loaded)throw Error(`Service unloaded before readiness could be confirmed`);return this.result(a,{kind:`verified`,local:t},s,e)}catch(e){return this.rollback(n,r,a,c,e)}})}catch(e){throw lv(e)}}start(){return this.runInstalled(`start`)}restart(){return this.runInstalled(`restart`)}stop(){return this.runInstalled(`stop`)}enable(){return this.setStartup(!0)}disable(){return this.setStartup(!1)}async setStartup(e){return this.serialized(!1,async()=>{let t=await this.manager.inspect(),n=this.selected(t);if(!t.installed)throw new sv(`Service is not installed; run service install first`);await this.manager.setStartupEnabled(e);let r=await this.manager.inspect();if(r.startupEnabled!==e||r.loaded!==t.loaded)throw new sv(`Startup preference or current execution could not be verified`);let i=this.expected(r,n);return this.result(r,await this.readiness.observe(n.sock,i),i)})}uninstall(){return this.runInstalled(`uninstall`)}runInstalled(e){return this.serialized(!1,async()=>{let t=await this.manager.inspect(),n=this.selected(t),r=e===`stop`||e===`uninstall`,i,a;try{i=this.expected(t,n)}catch(e){if(!r)throw e;a=lv(e).message}let o=await this.readiness.observe(n.sock,i);if(!t.installed){if(!r)throw new sv(`Service is not installed; run service install first`);return this.result(t,o,i,null,a)}if(!r&&!i)throw new sv(`Local identity is missing at ${n.identity}; restore it before starting`);r&&t.loaded&&o.kind===`unverified`||this.assertAvailable(t,o,i);let s={unloadAttempted:!1,written:!1,loaded:!1};try{if(e!==`start`&&t.loaded&&(s.unloadAttempted=!0,await this.manager.unload(),await this.readiness.waitStopped(n.sock)),r){e===`uninstall`&&await this.manager.restore(null);let t=await this.manager.inspect();if(t.loaded)throw Error(`Service remains loaded after stop`);return this.result(t,{kind:`absent`,local:null,diagnostic:e===`stop`?`Service stopped; definition remains and it may start at next login`:`Service uninstalled; identity and pairings remain`},i,null,a)}s.loaded=!t.loaded||e===`restart`;let c=await this.manager.load();if(e===`restart`&&o.local?.process.pid===c)throw Error(`Service restart did not produce a new manager-certified process`);let l=await this.readiness.waitReady(n.sock,{...i,pid:c}),u=await this.manager.inspect();if(!u.loaded)throw Error(`Service unloaded before readiness could be confirmed`);return this.result(u,{kind:`verified`,local:l},i,c)}catch(e){if(r)throw lv(e);return this.rollback(t,n,i,s,e)}})}};export{$m as $,Ir as $n,af as $t,Dg as A,Wc as An,zp as At,Ph as B,xc as Bn,Op as Bt,y_ as C,_u as Cn,cm as Ct,qg as D,ul as Dn,Kp as Dt,Yg as E,cl as En,Xp as Et,Sg as F,Ic as Fn,Z as Ft,hh as G,bc as Gn,xp as Gt,Ch as H,rc as Hn,Tp as Ht,Wh as I,lc as In,Fp as It,ch as J,cc as Jn,Bf as Jt,mh as K,dc as Kn,op as Kt,Hh as L,mc as Ln,Pp as Lt,Eg as M,Cc as Mn,Rp as Mt,Tg as N,Tc as Nn,Ip as Nt,jg as O,sl as On,Gp as Ot,Q as P,Dc as Pn,X as Pt,Jm as Q,Dr as Qn,lf as Qt,Fh as R,pc as Rn,jp as Rt,u_ as S,nu as Sn,tm as St,Qg as T,Kl as Tn,qp as Tt,vh as U,fc as Un,Cp as Ut,Sh as V,ec as Vn,Dp as Vt,dh as W,yc as Wn,Sp as Wt,ah as X,ya as Xn,ef as Xt,nh as Y,La as Yn,Of as Yt,ih as Z,Er as Zn,$d as Zt,A_ as _,$u as _n,Gn as _r,xm as _t,ov as a,Gd as an,nr as ar,Gm as at,m_ as b,xu as bn,rm as bt,L_ as c,ad as cn,K as cr,Tm as ct,V_ as d,Cu as dn,W as dr,Nm as dt,sf as en,Lr as er,Qm as et,G_ as f,Su as fn,Jn as fr,pm as ft,w_ as g,ku as gn,V as gr,fm as gt,j_ as h,td as hn,$n as hr,Pm as ht,uv as i,Qd as in,yr as ir,Km as it,wg as j,Sc as jn,Y as jt,Og as k,Vc as kn,Wp as kt,z_ as l,od as ln,lr,gm as lt,t_ as m,Au as mn,Qn as mr,Sm as mt,sv as n,Xd as nn,br as nr,Xm as nt,J_ as o,qd as on,rr as or,zm as ot,I_ as p,ju as pn,er as pr,Cm as pt,lh as q,sc as qn,Vf as qt,cv as r,Zd as rn,Cr as rr,Zm as rt,q_ as s,vd as sn,G as sr,Lm as st,dv as t,of as tn,Tr as tr,Ym as tt,B_ as u,Mu as un,tr as ur,bm as ut,M_ as v,dd as vn,H as vr,Fm as vt,s_ as w,bu as wn,sm as wt,k_ as x,J as xn,im as xt,g_ as y,$l as yn,mm as yt,Nh as z,ac as zn,Ap as zt};